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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/lbfgsb.py
python
LbfgsInvHessProduct._matvec
(self, x)
return r
Efficient matrix-vector multiply with the BFGS matrices. This calculation is described in Section (4) of [1]. Parameters ---------- x : ndarray An array with shape (n,) or (n,1). Returns ------- y : ndarray The matrix-vector product
Efficient matrix-vector multiply with the BFGS matrices.
[ "Efficient", "matrix", "-", "vector", "multiply", "with", "the", "BFGS", "matrices", "." ]
def _matvec(self, x): """Efficient matrix-vector multiply with the BFGS matrices. This calculation is described in Section (4) of [1]. Parameters ---------- x : ndarray An array with shape (n,) or (n,1). Returns ------- y : ndarray The matrix-vector product """ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho q = np.array(x, dtype=self.dtype, copy=True) if q.ndim == 2 and q.shape[1] == 1: q = q.reshape(-1) alpha = np.zeros(n_corrs) for i in range(n_corrs-1, -1, -1): alpha[i] = rho[i] * np.dot(s[i], q) q = q - alpha[i]*y[i] r = q for i in range(n_corrs): beta = rho[i] * np.dot(y[i], r) r = r + s[i] * (alpha[i] - beta) return r
[ "def", "_matvec", "(", "self", ",", "x", ")", ":", "s", ",", "y", ",", "n_corrs", ",", "rho", "=", "self", ".", "sk", ",", "self", ".", "yk", ",", "self", ".", "n_corrs", ",", "self", ".", "rho", "q", "=", "np", ".", "array", "(", "x", ",", "dtype", "=", "self", ".", "dtype", ",", "copy", "=", "True", ")", "if", "q", ".", "ndim", "==", "2", "and", "q", ".", "shape", "[", "1", "]", "==", "1", ":", "q", "=", "q", ".", "reshape", "(", "-", "1", ")", "alpha", "=", "np", ".", "zeros", "(", "n_corrs", ")", "for", "i", "in", "range", "(", "n_corrs", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "alpha", "[", "i", "]", "=", "rho", "[", "i", "]", "*", "np", ".", "dot", "(", "s", "[", "i", "]", ",", "q", ")", "q", "=", "q", "-", "alpha", "[", "i", "]", "*", "y", "[", "i", "]", "r", "=", "q", "for", "i", "in", "range", "(", "n_corrs", ")", ":", "beta", "=", "rho", "[", "i", "]", "*", "np", ".", "dot", "(", "y", "[", "i", "]", ",", "r", ")", "r", "=", "r", "+", "s", "[", "i", "]", "*", "(", "alpha", "[", "i", "]", "-", "beta", ")", "return", "r" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/lbfgsb.py#L414-L446
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pyedbglib/serialport/serialcdc.py
python
SerialCDC.open
(self)
Overriding parent's open(), with timeout.
Overriding parent's open(), with timeout.
[ "Overriding", "parent", "s", "open", "()", "with", "timeout", "." ]
def open(self): """ Overriding parent's open(), with timeout. """ if self.open_timeout <= 0: # Just do parent's open and let any exception propagate to caller super(SerialCDC, self).open() return for to in reversed(range(self.open_timeout)): try: super(SerialCDC, self).open() return except SerialException as e: self.logger.info("Waiting for opening serial port %s (%d)", self.port, to) self.logger.debug(e) if to == 0: # Propagate exception to caller when timed out raise e sleep(1)
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "open_timeout", "<=", "0", ":", "# Just do parent's open and let any exception propagate to caller", "super", "(", "SerialCDC", ",", "self", ")", ".", "open", "(", ")", "return", "for", "to", "in", "reversed", "(", "range", "(", "self", ".", "open_timeout", ")", ")", ":", "try", ":", "super", "(", "SerialCDC", ",", "self", ")", ".", "open", "(", ")", "return", "except", "SerialException", "as", "e", ":", "self", ".", "logger", ".", "info", "(", "\"Waiting for opening serial port %s (%d)\"", ",", "self", ".", "port", ",", "to", ")", "self", ".", "logger", ".", "debug", "(", "e", ")", "if", "to", "==", "0", ":", "# Propagate exception to caller when timed out", "raise", "e", "sleep", "(", "1", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/serialport/serialcdc.py#L45-L63
twhui/LiteFlowNet
00925aebf2db9ac50f4b1666f718688b10dd10d1
python/caffe/io.py
python
Transformer.deprocess
(self, in_, data)
return decaf_in
Invert Caffe formatting; see preprocess().
Invert Caffe formatting; see preprocess().
[ "Invert", "Caffe", "formatting", ";", "see", "preprocess", "()", "." ]
def deprocess(self, in_, data): """ Invert Caffe formatting; see preprocess(). """ self.__check_input(in_) decaf_in = data.copy().squeeze() transpose = self.transpose.get(in_) channel_swap = self.channel_swap.get(in_) raw_scale = self.raw_scale.get(in_) mean = self.mean.get(in_) input_scale = self.input_scale.get(in_) if input_scale is not None: decaf_in /= input_scale if mean is not None: decaf_in += mean if raw_scale is not None: decaf_in /= raw_scale if channel_swap is not None: decaf_in = decaf_in[np.argsort(channel_swap), :, :] if transpose is not None: decaf_in = decaf_in.transpose(np.argsort(transpose)) return decaf_in
[ "def", "deprocess", "(", "self", ",", "in_", ",", "data", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "decaf_in", "=", "data", ".", "copy", "(", ")", ".", "squeeze", "(", ")", "transpose", "=", "self", ".", "transpose", ".", "get", "(", "in_", ")", "channel_swap", "=", "self", ".", "channel_swap", ".", "get", "(", "in_", ")", "raw_scale", "=", "self", ".", "raw_scale", ".", "get", "(", "in_", ")", "mean", "=", "self", ".", "mean", ".", "get", "(", "in_", ")", "input_scale", "=", "self", ".", "input_scale", ".", "get", "(", "in_", ")", "if", "input_scale", "is", "not", "None", ":", "decaf_in", "/=", "input_scale", "if", "mean", "is", "not", "None", ":", "decaf_in", "+=", "mean", "if", "raw_scale", "is", "not", "None", ":", "decaf_in", "/=", "raw_scale", "if", "channel_swap", "is", "not", "None", ":", "decaf_in", "=", "decaf_in", "[", "np", ".", "argsort", "(", "channel_swap", ")", ",", ":", ",", ":", "]", "if", "transpose", "is", "not", "None", ":", "decaf_in", "=", "decaf_in", ".", "transpose", "(", "np", ".", "argsort", "(", "transpose", ")", ")", "return", "decaf_in" ]
https://github.com/twhui/LiteFlowNet/blob/00925aebf2db9ac50f4b1666f718688b10dd10d1/python/caffe/io.py#L164-L185
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/build/lib.linux-x86_64-2.7/mxnet/io.py
python
NDArrayIter.hard_reset
(self)
Igore roll over data and set to start
Igore roll over data and set to start
[ "Igore", "roll", "over", "data", "and", "set", "to", "start" ]
def hard_reset(self): """Igore roll over data and set to start""" self.cursor = -self.batch_size
[ "def", "hard_reset", "(", "self", ")", ":", "self", ".", "cursor", "=", "-", "self", ".", "batch_size" ]
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/io.py#L378-L380
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
libraries/AP_Terrain/tools/create_terrain.py
python
DataFile.check_filled
(self, block)
return True
read a grid block and check if already filled
read a grid block and check if already filled
[ "read", "a", "grid", "block", "and", "check", "if", "already", "filled" ]
def check_filled(self, block): '''read a grid block and check if already filled''' self.seek_offset(block) if self.fh is None: return False buf = self.fh.read(IO_BLOCK_SIZE) if len(buf) != IO_BLOCK_SIZE: return False (bitmap, lat, lon, crc, version, spacing) = struct.unpack("<QiiHHH", buf[:22]) if (version != TERRAIN_GRID_FORMAT_VERSION or abs(lat - block.lat)>2 or abs(lon - block.lon)>2 or spacing != GRID_SPACING or bitmap != (1<<56)-1): return False buf = buf[:16] + struct.pack("<H", 0) + buf[18:] crc2 = crc16.crc16xmodem(buf[:IO_BLOCK_DATA_SIZE]) if crc2 != crc: return False return True
[ "def", "check_filled", "(", "self", ",", "block", ")", ":", "self", ".", "seek_offset", "(", "block", ")", "if", "self", ".", "fh", "is", "None", ":", "return", "False", "buf", "=", "self", ".", "fh", ".", "read", "(", "IO_BLOCK_SIZE", ")", "if", "len", "(", "buf", ")", "!=", "IO_BLOCK_SIZE", ":", "return", "False", "(", "bitmap", ",", "lat", ",", "lon", ",", "crc", ",", "version", ",", "spacing", ")", "=", "struct", ".", "unpack", "(", "\"<QiiHHH\"", ",", "buf", "[", ":", "22", "]", ")", "if", "(", "version", "!=", "TERRAIN_GRID_FORMAT_VERSION", "or", "abs", "(", "lat", "-", "block", ".", "lat", ")", ">", "2", "or", "abs", "(", "lon", "-", "block", ".", "lon", ")", ">", "2", "or", "spacing", "!=", "GRID_SPACING", "or", "bitmap", "!=", "(", "1", "<<", "56", ")", "-", "1", ")", ":", "return", "False", "buf", "=", "buf", "[", ":", "16", "]", "+", "struct", ".", "pack", "(", "\"<H\"", ",", "0", ")", "+", "buf", "[", "18", ":", "]", "crc2", "=", "crc16", ".", "crc16xmodem", "(", "buf", "[", ":", "IO_BLOCK_DATA_SIZE", "]", ")", "if", "crc2", "!=", "crc", ":", "return", "False", "return", "True" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/AP_Terrain/tools/create_terrain.py#L251-L270
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/summary/event_accumulator.py
python
EventAccumulator.Tags
(self)
return {IMAGES: self._images.Keys(), AUDIO: self._audio.Keys(), HISTOGRAMS: self._histograms.Keys(), SCALARS: self._scalars.Keys(), COMPRESSED_HISTOGRAMS: self._compressed_histograms.Keys(), GRAPH: self._graph is not None, RUN_METADATA: list(self._tagged_metadata.keys())}
Return all tags found in the value stream. Returns: A `{tagType: ['list', 'of', 'tags']}` dictionary.
Return all tags found in the value stream.
[ "Return", "all", "tags", "found", "in", "the", "value", "stream", "." ]
def Tags(self): """Return all tags found in the value stream. Returns: A `{tagType: ['list', 'of', 'tags']}` dictionary. """ return {IMAGES: self._images.Keys(), AUDIO: self._audio.Keys(), HISTOGRAMS: self._histograms.Keys(), SCALARS: self._scalars.Keys(), COMPRESSED_HISTOGRAMS: self._compressed_histograms.Keys(), GRAPH: self._graph is not None, RUN_METADATA: list(self._tagged_metadata.keys())}
[ "def", "Tags", "(", "self", ")", ":", "return", "{", "IMAGES", ":", "self", ".", "_images", ".", "Keys", "(", ")", ",", "AUDIO", ":", "self", ".", "_audio", ".", "Keys", "(", ")", ",", "HISTOGRAMS", ":", "self", ".", "_histograms", ".", "Keys", "(", ")", ",", "SCALARS", ":", "self", ".", "_scalars", ".", "Keys", "(", ")", ",", "COMPRESSED_HISTOGRAMS", ":", "self", ".", "_compressed_histograms", ".", "Keys", "(", ")", ",", "GRAPH", ":", "self", ".", "_graph", "is", "not", "None", ",", "RUN_METADATA", ":", "list", "(", "self", ".", "_tagged_metadata", ".", "keys", "(", ")", ")", "}" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/summary/event_accumulator.py#L262-L274
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
python/lbann/launcher/batch_script.py
python
BatchScript.submit
(self, overwrite=False)
Submit batch job to job scheduler. The script file is written before being submitted. Args: overwrite (bool): Whether to overwrite script file if it already exists (default: false). Returns: int: Exit status from submitting to job scheduler.
Submit batch job to job scheduler.
[ "Submit", "batch", "job", "to", "job", "scheduler", "." ]
def submit(self, overwrite=False): """Submit batch job to job scheduler. The script file is written before being submitted. Args: overwrite (bool): Whether to overwrite script file if it already exists (default: false). Returns: int: Exit status from submitting to job scheduler. """ raise NotImplementedError( 'classes that inherit from `BatchScript` should implement ' '`submit` to use a specific job scheduler' )
[ "def", "submit", "(", "self", ",", "overwrite", "=", "False", ")", ":", "raise", "NotImplementedError", "(", "'classes that inherit from `BatchScript` should implement '", "'`submit` to use a specific job scheduler'", ")" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/launcher/batch_script.py#L177-L193
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
AuiManager.CreateNotebookBase
(self, panes, paneInfo)
Creates an auto-notebook base from a pane, and then add that pane as a page. :param list `panes`: set of panes to append new notebook base pane to :param AuiPaneInfo `paneInfo`: the pane to be converted to a new notebook.
Creates an auto-notebook base from a pane, and then add that pane as a page.
[ "Creates", "an", "auto", "-", "notebook", "base", "from", "a", "pane", "and", "then", "add", "that", "pane", "as", "a", "page", "." ]
def CreateNotebookBase(self, panes, paneInfo): """ Creates an auto-notebook base from a pane, and then add that pane as a page. :param list `panes`: set of panes to append new notebook base pane to :param AuiPaneInfo `paneInfo`: the pane to be converted to a new notebook. """ # Create base notebook pane ... nbid = len(self._notebooks) baseInfo = AuiPaneInfo() baseInfo.SetDockPos(paneInfo).NotebookControl(nbid). \ CloseButton(False).SetNameFromNotebookId(). \ NotebookDockable(False).Floatable(paneInfo.IsFloatable()) baseInfo.best_size = paneInfo.best_size panes.append(baseInfo) # add original pane as tab ... paneInfo.NotebookPage(nbid)
[ "def", "CreateNotebookBase", "(", "self", ",", "panes", ",", "paneInfo", ")", ":", "# Create base notebook pane ...", "nbid", "=", "len", "(", "self", ".", "_notebooks", ")", "baseInfo", "=", "AuiPaneInfo", "(", ")", "baseInfo", ".", "SetDockPos", "(", "paneInfo", ")", ".", "NotebookControl", "(", "nbid", ")", ".", "CloseButton", "(", "False", ")", ".", "SetNameFromNotebookId", "(", ")", ".", "NotebookDockable", "(", "False", ")", ".", "Floatable", "(", "paneInfo", ".", "IsFloatable", "(", ")", ")", "baseInfo", ".", "best_size", "=", "paneInfo", ".", "best_size", "panes", ".", "append", "(", "baseInfo", ")", "# add original pane as tab ...", "paneInfo", ".", "NotebookPage", "(", "nbid", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L10207-L10226
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
DC.GetImpl
(*args, **kwargs)
return _gdi_.DC_GetImpl(*args, **kwargs)
GetImpl(self) -> DCImpl
GetImpl(self) -> DCImpl
[ "GetImpl", "(", "self", ")", "-", ">", "DCImpl" ]
def GetImpl(*args, **kwargs): """GetImpl(self) -> DCImpl""" return _gdi_.DC_GetImpl(*args, **kwargs)
[ "def", "GetImpl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_GetImpl", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3312-L3314
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Base/Python/slicer/ScriptedLoadableModule.py
python
ScriptedLoadableModule.runTest
(self, msec=100, **kwargs)
:param msec: delay to associate with :func:`ScriptedLoadableModuleTest.delayDisplay()`.
:param msec: delay to associate with :func:`ScriptedLoadableModuleTest.delayDisplay()`.
[ ":", "param", "msec", ":", "delay", "to", "associate", "with", ":", "func", ":", "ScriptedLoadableModuleTest", ".", "delayDisplay", "()", "." ]
def runTest(self, msec=100, **kwargs): """ :param msec: delay to associate with :func:`ScriptedLoadableModuleTest.delayDisplay()`. """ # Name of the test case class is expected to be <ModuleName>Test module = importlib.import_module(self.__module__) className = self.moduleName + 'Test' try: TestCaseClass = getattr(module, className) except AttributeError: # Treat missing test case class as a failure; provide useful error message raise AssertionError(f'Test case class not found: {self.__module__}.{className} ') testCase = TestCaseClass() testCase.messageDelay = msec testCase.runTest(**kwargs)
[ "def", "runTest", "(", "self", ",", "msec", "=", "100", ",", "*", "*", "kwargs", ")", ":", "# Name of the test case class is expected to be <ModuleName>Test", "module", "=", "importlib", ".", "import_module", "(", "self", ".", "__module__", ")", "className", "=", "self", ".", "moduleName", "+", "'Test'", "try", ":", "TestCaseClass", "=", "getattr", "(", "module", ",", "className", ")", "except", "AttributeError", ":", "# Treat missing test case class as a failure; provide useful error message", "raise", "AssertionError", "(", "f'Test case class not found: {self.__module__}.{className} '", ")", "testCase", "=", "TestCaseClass", "(", ")", "testCase", ".", "messageDelay", "=", "msec", "testCase", ".", "runTest", "(", "*", "*", "kwargs", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/ScriptedLoadableModule.py#L57-L72
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGridEvent.GetValue
(*args, **kwargs)
return _propgrid.PropertyGridEvent_GetValue(*args, **kwargs)
GetValue(self) -> wxVariant
GetValue(self) -> wxVariant
[ "GetValue", "(", "self", ")", "-", ">", "wxVariant" ]
def GetValue(*args, **kwargs): """GetValue(self) -> wxVariant""" return _propgrid.PropertyGridEvent_GetValue(*args, **kwargs)
[ "def", "GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridEvent_GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2541-L2543
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/tensor_shape.py
python
Dimension.__mul__
(self, other)
Returns the product of `self` and `other`. Dimensions are summed as follows: ``` Dimension(m) * Dimension(n) == Dimension(m * n) Dimension(m) * Dimension(None) == Dimension(None) Dimension(None) * Dimension(n) == Dimension(None) Dimension(None) * Dimension(None) == Dimension(None) ``` Args: other: Another Dimension. Returns: A Dimension whose value is the product of `self` and `other`.
Returns the product of `self` and `other`.
[ "Returns", "the", "product", "of", "self", "and", "other", "." ]
def __mul__(self, other): """Returns the product of `self` and `other`. Dimensions are summed as follows: ``` Dimension(m) * Dimension(n) == Dimension(m * n) Dimension(m) * Dimension(None) == Dimension(None) Dimension(None) * Dimension(n) == Dimension(None) Dimension(None) * Dimension(None) == Dimension(None) ``` Args: other: Another Dimension. Returns: A Dimension whose value is the product of `self` and `other`. """ other = as_dimension(other) if self._value is None or other.value is None: return Dimension(None) else: return Dimension(self._value * other.value)
[ "def", "__mul__", "(", "self", ",", "other", ")", ":", "other", "=", "as_dimension", "(", "other", ")", "if", "self", ".", "_value", "is", "None", "or", "other", ".", "value", "is", "None", ":", "return", "Dimension", "(", "None", ")", "else", ":", "return", "Dimension", "(", "self", ".", "_value", "*", "other", ".", "value", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/tensor_shape.py#L188-L210
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/examples/python/mach_o.py
python
TerminalColors.reset
(self)
return ''
Reset all terminal colors and formatting.
Reset all terminal colors and formatting.
[ "Reset", "all", "terminal", "colors", "and", "formatting", "." ]
def reset(self): '''Reset all terminal colors and formatting.''' if self.enabled: return "\x1b[0m" return ''
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "enabled", ":", "return", "\"\\x1b[0m\"", "return", "''" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/examples/python/mach_o.py#L220-L224
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/smartquotes.py
python
educateBackticks
(text, language='en')
return text
Parameter: String (unicode or bytes). Returns: The `text`, with ``backticks'' -style double quotes translated into HTML curly quote entities. Example input: ``Isn't this fun?'' Example output: “Isn't this fun?“;
Parameter: String (unicode or bytes). Returns: The `text`, with ``backticks'' -style double quotes translated into HTML curly quote entities. Example input: ``Isn't this fun?'' Example output: “Isn't this fun?“;
[ "Parameter", ":", "String", "(", "unicode", "or", "bytes", ")", ".", "Returns", ":", "The", "text", "with", "backticks", "-", "style", "double", "quotes", "translated", "into", "HTML", "curly", "quote", "entities", ".", "Example", "input", ":", "Isn", "t", "this", "fun?", "Example", "output", ":", "“Isn", "t", "this", "fun?“", ";" ]
def educateBackticks(text, language='en'): """ Parameter: String (unicode or bytes). Returns: The `text`, with ``backticks'' -style double quotes translated into HTML curly quote entities. Example input: ``Isn't this fun?'' Example output: “Isn't this fun?“; """ smart = smartchars(language) text = re.sub(r"""``""", smart.opquote, text) text = re.sub(r"""''""", smart.cpquote, text) return text
[ "def", "educateBackticks", "(", "text", ",", "language", "=", "'en'", ")", ":", "smart", "=", "smartchars", "(", "language", ")", "text", "=", "re", ".", "sub", "(", "r\"\"\"``\"\"\"", ",", "smart", ".", "opquote", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r\"\"\"''\"\"\"", ",", "smart", ".", "cpquote", ",", "text", ")", "return", "text" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/smartquotes.py#L736-L748
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/robotparser.py
python
RobotFileParser.mtime
(self)
return self.last_checked
Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically.
Returns the time the robots.txt file was last fetched.
[ "Returns", "the", "time", "the", "robots", ".", "txt", "file", "was", "last", "fetched", "." ]
def mtime(self): """Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically. """ return self.last_checked
[ "def", "mtime", "(", "self", ")", ":", "return", "self", ".", "last_checked" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/robotparser.py#L32-L39
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/poolmanager.py
python
PoolManager.clear
(self)
Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion.
Empty our store of pools and direct them all to close.
[ "Empty", "our", "store", "of", "pools", "and", "direct", "them", "all", "to", "close", "." ]
def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "pools", ".", "clear", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/poolmanager.py#L215-L222
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/imaplib.py
python
Int2AP
(num)
return val
Convert integer to A-P string representation.
Convert integer to A-P string representation.
[ "Convert", "integer", "to", "A", "-", "P", "string", "representation", "." ]
def Int2AP(num): """Convert integer to A-P string representation.""" val = ''; AP = 'ABCDEFGHIJKLMNOP' num = int(abs(num)) while num: num, mod = divmod(num, 16) val = AP[mod] + val return val
[ "def", "Int2AP", "(", "num", ")", ":", "val", "=", "''", "AP", "=", "'ABCDEFGHIJKLMNOP'", "num", "=", "int", "(", "abs", "(", "num", ")", ")", "while", "num", ":", "num", ",", "mod", "=", "divmod", "(", "num", ",", "16", ")", "val", "=", "AP", "[", "mod", "]", "+", "val", "return", "val" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/imaplib.py#L1357-L1366
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py
python
GroupBy.size
(self)
return self._reindex_output(result, fill_value=0)
Compute group sizes. Returns ------- Series Number of rows in each group.
Compute group sizes.
[ "Compute", "group", "sizes", "." ]
def size(self): """ Compute group sizes. Returns ------- Series Number of rows in each group. """ result = self.grouper.size() if isinstance(self.obj, Series): result.name = self.obj.name return self._reindex_output(result, fill_value=0)
[ "def", "size", "(", "self", ")", ":", "result", "=", "self", ".", "grouper", ".", "size", "(", ")", "if", "isinstance", "(", "self", ".", "obj", ",", "Series", ")", ":", "result", ".", "name", "=", "self", ".", "obj", ".", "name", "return", "self", ".", "_reindex_output", "(", "result", ",", "fill_value", "=", "0", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py#L1320-L1333
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
GetMacInfoPlist
(product_dir, xcode_settings, gyp_path_to_build_path)
return info_plist, dest_plist, defines, extra_env
Returns (info_plist, dest_plist, defines, extra_env), where: * |info_plist| is the source plist path, relative to the build directory, * |dest_plist| is the destination plist path, relative to the build directory, * |defines| is a list of preprocessor defines (empty if the plist shouldn't be preprocessed, * |extra_env| is a dict of env variables that should be exported when invoking |mac_tool copy-info-plist|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build directory.
Returns (info_plist, dest_plist, defines, extra_env), where: * |info_plist| is the source plist path, relative to the build directory, * |dest_plist| is the destination plist path, relative to the build directory, * |defines| is a list of preprocessor defines (empty if the plist shouldn't be preprocessed, * |extra_env| is a dict of env variables that should be exported when invoking |mac_tool copy-info-plist|.
[ "Returns", "(", "info_plist", "dest_plist", "defines", "extra_env", ")", "where", ":", "*", "|info_plist|", "is", "the", "source", "plist", "path", "relative", "to", "the", "build", "directory", "*", "|dest_plist|", "is", "the", "destination", "plist", "path", "relative", "to", "the", "build", "directory", "*", "|defines|", "is", "a", "list", "of", "preprocessor", "defines", "(", "empty", "if", "the", "plist", "shouldn", "t", "be", "preprocessed", "*", "|extra_env|", "is", "a", "dict", "of", "env", "variables", "that", "should", "be", "exported", "when", "invoking", "|mac_tool", "copy", "-", "info", "-", "plist|", "." ]
def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path): """Returns (info_plist, dest_plist, defines, extra_env), where: * |info_plist| is the source plist path, relative to the build directory, * |dest_plist| is the destination plist path, relative to the build directory, * |defines| is a list of preprocessor defines (empty if the plist shouldn't be preprocessed, * |extra_env| is a dict of env variables that should be exported when invoking |mac_tool copy-info-plist|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build directory. """ info_plist = xcode_settings.GetPerTargetSetting("INFOPLIST_FILE") if not info_plist: return None, None, [], {} # The make generator doesn't support it, so forbid it everywhere # to keep the generators more interchangeable. assert " " not in info_plist, ( "Spaces in Info.plist filenames not supported (%s)" % info_plist ) info_plist = gyp_path_to_build_path(info_plist) # If explicitly set to preprocess the plist, invoke the C preprocessor and # specify any defines as -D flags. if ( xcode_settings.GetPerTargetSetting("INFOPLIST_PREPROCESS", default="NO") == "YES" ): # Create an intermediate file based on the path. defines = shlex.split( xcode_settings.GetPerTargetSetting( "INFOPLIST_PREPROCESSOR_DEFINITIONS", default="" ) ) else: defines = [] dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath()) extra_env = xcode_settings.GetPerTargetSettings() return info_plist, dest_plist, defines, extra_env
[ "def", "GetMacInfoPlist", "(", "product_dir", ",", "xcode_settings", ",", "gyp_path_to_build_path", ")", ":", "info_plist", "=", "xcode_settings", ".", "GetPerTargetSetting", "(", "\"INFOPLIST_FILE\"", ")", "if", "not", "info_plist", ":", "return", "None", ",", "None", ",", "[", "]", ",", "{", "}", "# The make generator doesn't support it, so forbid it everywhere", "# to keep the generators more interchangeable.", "assert", "\" \"", "not", "in", "info_plist", ",", "(", "\"Spaces in Info.plist filenames not supported (%s)\"", "%", "info_plist", ")", "info_plist", "=", "gyp_path_to_build_path", "(", "info_plist", ")", "# If explicitly set to preprocess the plist, invoke the C preprocessor and", "# specify any defines as -D flags.", "if", "(", "xcode_settings", ".", "GetPerTargetSetting", "(", "\"INFOPLIST_PREPROCESS\"", ",", "default", "=", "\"NO\"", ")", "==", "\"YES\"", ")", ":", "# Create an intermediate file based on the path.", "defines", "=", "shlex", ".", "split", "(", "xcode_settings", ".", "GetPerTargetSetting", "(", "\"INFOPLIST_PREPROCESSOR_DEFINITIONS\"", ",", "default", "=", "\"\"", ")", ")", "else", ":", "defines", "=", "[", "]", "dest_plist", "=", "os", ".", "path", ".", "join", "(", "product_dir", ",", "xcode_settings", ".", "GetBundlePlistPath", "(", ")", ")", "extra_env", "=", "xcode_settings", ".", "GetPerTargetSettings", "(", ")", "return", "info_plist", ",", "dest_plist", ",", "defines", ",", "extra_env" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L1652-L1702
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
llvm/utils/lit/lit/Util.py
python
to_string
(b)
Return the parameter as type 'str', possibly encoding it. In Python2, the 'str' type is the same as 'bytes'. In Python3, the 'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is distinct.
Return the parameter as type 'str', possibly encoding it.
[ "Return", "the", "parameter", "as", "type", "str", "possibly", "encoding", "it", "." ]
def to_string(b): """Return the parameter as type 'str', possibly encoding it. In Python2, the 'str' type is the same as 'bytes'. In Python3, the 'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is distinct. """ if isinstance(b, str): # In Python2, this branch is taken for types 'str' and 'bytes'. # In Python3, this branch is taken only for 'str'. return b if isinstance(b, bytes): # In Python2, this branch is never taken ('bytes' is handled as 'str'). # In Python3, this is true only for 'bytes'. try: return b.decode('utf-8') except UnicodeDecodeError: # If the value is not valid Unicode, return the default # repr-line encoding. return str(b) # By this point, here's what we *don't* have: # # - In Python2: # - 'str' or 'bytes' (1st branch above) # - In Python3: # - 'str' (1st branch above) # - 'bytes' (2nd branch above) # # The last type we might expect is the Python2 'unicode' type. There is no # 'unicode' type in Python3 (all the Python3 cases were already handled). In # order to get a 'str' object, we need to encode the 'unicode' object. try: return b.encode('utf-8') except AttributeError: raise TypeError('not sure how to convert %s to %s' % (type(b), str))
[ "def", "to_string", "(", "b", ")", ":", "if", "isinstance", "(", "b", ",", "str", ")", ":", "# In Python2, this branch is taken for types 'str' and 'bytes'.", "# In Python3, this branch is taken only for 'str'.", "return", "b", "if", "isinstance", "(", "b", ",", "bytes", ")", ":", "# In Python2, this branch is never taken ('bytes' is handled as 'str').", "# In Python3, this is true only for 'bytes'.", "try", ":", "return", "b", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "# If the value is not valid Unicode, return the default", "# repr-line encoding.", "return", "str", "(", "b", ")", "# By this point, here's what we *don't* have:", "#", "# - In Python2:", "# - 'str' or 'bytes' (1st branch above)", "# - In Python3:", "# - 'str' (1st branch above)", "# - 'bytes' (2nd branch above)", "#", "# The last type we might expect is the Python2 'unicode' type. There is no", "# 'unicode' type in Python3 (all the Python3 cases were already handled). In", "# order to get a 'str' object, we need to encode the 'unicode' object.", "try", ":", "return", "b", ".", "encode", "(", "'utf-8'", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "'not sure how to convert %s to %s'", "%", "(", "type", "(", "b", ")", ",", "str", ")", ")" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/utils/lit/lit/Util.py#L66-L102
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/site_compare/command_line.py
python
CommandLine.ParseCommandLine
(self, argv=None, prog=None, execute=True)
return self.command
Does the work of parsing a command line. Args: argv: list of arguments, defaults to sys.args[1:] prog: name of the command, defaults to the base name of the script execute: if false, just parse, don't invoke the 'impl' member Returns: The command that was executed
Does the work of parsing a command line.
[ "Does", "the", "work", "of", "parsing", "a", "command", "line", "." ]
def ParseCommandLine(self, argv=None, prog=None, execute=True): """Does the work of parsing a command line. Args: argv: list of arguments, defaults to sys.args[1:] prog: name of the command, defaults to the base name of the script execute: if false, just parse, don't invoke the 'impl' member Returns: The command that was executed """ if argv is None: argv = sys.argv[1:] if prog is None: prog = os.path.basename(sys.argv[0]).split('.')[0] # Store off our parameters, we may need them someday self.argv = argv self.prog = prog # We shouldn't be invoked without arguments, that's just lame if not len(argv): self.out.writelines(self.GetUsageString()) self.Exit() return None # in case the client overrides Exit # Is it a valid command? self.command_string = argv[0].lower() if not self.command_string in self.cmd_dict: self.err.write("Unknown command: '%s'\n\n" % self.command_string) self.out.write(self.GetUsageString()) self.Exit() return None # in case the client overrides Exit self.command = self.cmd_dict[self.command_string] # "rargs" = remaining (unparsed) arguments # "largs" = already parsed, "left" of the read head self.rargs = argv[1:] self.largs = [] # let the command object do the parsing self.command.ParseArguments() if self.command.parse_errors: # there were errors, output the usage string and exit self.err.write(self.command.GetUsageString()+"\n\n") self.err.write("\n".join(self.command.parse_errors)) self.err.write("\n\n") self.Exit() elif execute and self.command.impl: self.command.impl(self.command) return self.command
[ "def", "ParseCommandLine", "(", "self", ",", "argv", "=", "None", ",", "prog", "=", "None", ",", "execute", "=", "True", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "prog", "is", "None", ":", "prog", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "# Store off our parameters, we may need them someday", "self", ".", "argv", "=", "argv", "self", ".", "prog", "=", "prog", "# We shouldn't be invoked without arguments, that's just lame", "if", "not", "len", "(", "argv", ")", ":", "self", ".", "out", ".", "writelines", "(", "self", ".", "GetUsageString", "(", ")", ")", "self", ".", "Exit", "(", ")", "return", "None", "# in case the client overrides Exit", "# Is it a valid command?", "self", ".", "command_string", "=", "argv", "[", "0", "]", ".", "lower", "(", ")", "if", "not", "self", ".", "command_string", "in", "self", ".", "cmd_dict", ":", "self", ".", "err", ".", "write", "(", "\"Unknown command: '%s'\\n\\n\"", "%", "self", ".", "command_string", ")", "self", ".", "out", ".", "write", "(", "self", ".", "GetUsageString", "(", ")", ")", "self", ".", "Exit", "(", ")", "return", "None", "# in case the client overrides Exit", "self", ".", "command", "=", "self", ".", "cmd_dict", "[", "self", ".", "command_string", "]", "# \"rargs\" = remaining (unparsed) arguments", "# \"largs\" = already parsed, \"left\" of the read head", "self", ".", "rargs", "=", "argv", "[", "1", ":", "]", "self", ".", "largs", "=", "[", "]", "# let the command object do the parsing", "self", ".", "command", ".", "ParseArguments", "(", ")", "if", "self", ".", "command", ".", "parse_errors", ":", "# there were errors, output the usage string and exit", "self", ".", "err", ".", "write", "(", "self", ".", "command", ".", "GetUsageString", "(", ")", "+", "\"\\n\\n\"", ")", "self", ".", "err", ".", "write", "(", "\"\\n\"", ".", "join", "(", "self", ".", "command", ".", "parse_errors", ")", ")", "self", ".", "err", ".", "write", "(", "\"\\n\\n\"", ")", "self", ".", "Exit", "(", ")", "elif", "execute", "and", "self", ".", "command", ".", "impl", ":", "self", ".", "command", ".", "impl", "(", "self", ".", "command", ")", "return", "self", ".", "command" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/site_compare/command_line.py#L554-L607
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py
python
random_brightness
(image, max_delta, seed=None)
return adjust_brightness(image, delta)
Adjust the brightness of images by a random factor. Equivalent to `adjust_brightness()` using a `delta` randomly picked in the interval `[-max_delta, max_delta)`. Args: image: An image or images to adjust. max_delta: float, must be non-negative. seed: A Python integer. Used to create a random seed. See `tf.compat.v1.set_random_seed` for behavior. Returns: The brightness-adjusted image(s). Raises: ValueError: if `max_delta` is negative.
Adjust the brightness of images by a random factor.
[ "Adjust", "the", "brightness", "of", "images", "by", "a", "random", "factor", "." ]
def random_brightness(image, max_delta, seed=None): """Adjust the brightness of images by a random factor. Equivalent to `adjust_brightness()` using a `delta` randomly picked in the interval `[-max_delta, max_delta)`. Args: image: An image or images to adjust. max_delta: float, must be non-negative. seed: A Python integer. Used to create a random seed. See `tf.compat.v1.set_random_seed` for behavior. Returns: The brightness-adjusted image(s). Raises: ValueError: if `max_delta` is negative. """ if max_delta < 0: raise ValueError('max_delta must be non-negative.') delta = random_ops.random_uniform([], -max_delta, max_delta, seed=seed) return adjust_brightness(image, delta)
[ "def", "random_brightness", "(", "image", ",", "max_delta", ",", "seed", "=", "None", ")", ":", "if", "max_delta", "<", "0", ":", "raise", "ValueError", "(", "'max_delta must be non-negative.'", ")", "delta", "=", "random_ops", ".", "random_uniform", "(", "[", "]", ",", "-", "max_delta", ",", "max_delta", ",", "seed", "=", "seed", ")", "return", "adjust_brightness", "(", "image", ",", "delta", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py#L1523-L1545
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextCtrl.EndCharacterStyle
(*args, **kwargs)
return _richtext.RichTextCtrl_EndCharacterStyle(*args, **kwargs)
EndCharacterStyle(self) -> bool End named character style
EndCharacterStyle(self) -> bool
[ "EndCharacterStyle", "(", "self", ")", "-", ">", "bool" ]
def EndCharacterStyle(*args, **kwargs): """ EndCharacterStyle(self) -> bool End named character style """ return _richtext.RichTextCtrl_EndCharacterStyle(*args, **kwargs)
[ "def", "EndCharacterStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_EndCharacterStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L3569-L3575
microsoft/EdgeML
ef9f8a77f096acbdeb941014791f8eda1c1bc35b
tools/SeeDot/seedot/compiler/ir/irBuilder.py
python
IRBuilder.visitMathExp
(self, node: AST.Func)
return (prog_out, expr_out)
1. y = ((int) (exp(((float)e) / shr1) * shr2))
1. y = ((int) (exp(((float)e) / shr1) * shr2))
[ "1", ".", "y", "=", "((", "int", ")", "(", "exp", "(((", "float", ")", "e", ")", "/", "shr1", ")", "*", "shr2", "))" ]
def visitMathExp(self, node: AST.Func): # Used in the old SeeDot (PLDI '19) version. # Tunable parameter. MIN = 0.1 (prog_in, expr_in) = self.visit(node.expr) type_in = node.expr.type # Reading input scale and bit-width. bitwidth_in, scale_in = self.getBitwidthAndScale(expr_in.idf) ''' 1. y = ((int) (exp(((float)e) / shr1) * shr2)) ''' maxExp = np.exp(MIN) expr_out = self.getTempVar() # Reading / Computing output bit-width. if self.ddsEnabled: bitwidth_out, _ = self.getBitwidthAndScale(expr_out.idf) else: bitwidth_out = config.wordLength // 2 if expr_out.idf in self.demotedVarsList else config.wordLength # Computing output scale. scale_out = self.getScale(maxExp) + config.wordLength // 2 if expr_out.idf in self.demotedVarsList else self.getScale(maxExp) intv_out = self.getInterval(scale_out, maxExp, maxExp) [I, J] = type_in.shape # Scaling hyperparameters. shr1 = 2 ** -scale_in shr2 = 2 ** -scale_out shr1 = self.formatShr(shr1, "shr") shr2 = self.formatShr(shr2, "shr") cmd0 = IR.Comment('exp(' + expr_in.idf + ')', self.counter_inst+1) self.allDepths[self.counter_inst+1] = self.curDepth funcCall = IR.FuncCall("Exp", { expr_in: "A", IR.Int(I): "I", IR.Int(J): "J", shr1: "shrA", shr2: "shrB", expr_out: "B" }) if not self.vbwEnabled else IR.FuncCall("Exp<int%d_t, int%d_t>"%(bitwidth_in, bitwidth_out), { expr_in: "A", IR.Int(I): "I", IR.Int(J): "J", shr1: "shrA", shr2: "shrB", expr_out: "B", IR.Int(1): "demote" }) self.counter_inst += 1 self.updateLiveRange([expr_in, expr_out]) # This method is used in the profiling floating point stage to check whether the input values are beyond a threshold. # Input values beyond a threshold are always mapped to zero in fixed-point code, hence these datapoints hold little use in the fixed-point mode. rangeCheck = IR.FuncCall("checkRange2", { expr_in: "A", IR.Int(I): "I", IR.Int(J): "J" }) if self.functionReducedProfiling and forFloat() else IR.Comment("Recommend switching on Function Reduced Profiling for sound output") profile = IR.FuncCall("Profile2", { expr_out: "Var", IR.Int(I): "I", IR.Int(J): "J", IR.String(expr_out): "VarName" }) if forFloat(): self.independentVars.append(expr_out.idf) prog_exp = IR.Prog([cmd0, rangeCheck, funcCall, profile] if forFloat() and self.ddsEnabled else [cmd0, funcCall]) prog_out = IRUtil.concatPrograms(prog_in, prog_exp) # Update metadata. self.varDeclarations[expr_out.idf] = type_in self.varScales[expr_out.idf] = scale_out self.varIntervals[expr_out.idf] = intv_out return (prog_out, expr_out)
[ "def", "visitMathExp", "(", "self", ",", "node", ":", "AST", ".", "Func", ")", ":", "# Used in the old SeeDot (PLDI '19) version.", "# Tunable parameter.", "MIN", "=", "0.1", "(", "prog_in", ",", "expr_in", ")", "=", "self", ".", "visit", "(", "node", ".", "expr", ")", "type_in", "=", "node", ".", "expr", ".", "type", "# Reading input scale and bit-width.", "bitwidth_in", ",", "scale_in", "=", "self", ".", "getBitwidthAndScale", "(", "expr_in", ".", "idf", ")", "maxExp", "=", "np", ".", "exp", "(", "MIN", ")", "expr_out", "=", "self", ".", "getTempVar", "(", ")", "# Reading / Computing output bit-width.", "if", "self", ".", "ddsEnabled", ":", "bitwidth_out", ",", "_", "=", "self", ".", "getBitwidthAndScale", "(", "expr_out", ".", "idf", ")", "else", ":", "bitwidth_out", "=", "config", ".", "wordLength", "//", "2", "if", "expr_out", ".", "idf", "in", "self", ".", "demotedVarsList", "else", "config", ".", "wordLength", "# Computing output scale.", "scale_out", "=", "self", ".", "getScale", "(", "maxExp", ")", "+", "config", ".", "wordLength", "//", "2", "if", "expr_out", ".", "idf", "in", "self", ".", "demotedVarsList", "else", "self", ".", "getScale", "(", "maxExp", ")", "intv_out", "=", "self", ".", "getInterval", "(", "scale_out", ",", "maxExp", ",", "maxExp", ")", "[", "I", ",", "J", "]", "=", "type_in", ".", "shape", "# Scaling hyperparameters.", "shr1", "=", "2", "**", "-", "scale_in", "shr2", "=", "2", "**", "-", "scale_out", "shr1", "=", "self", ".", "formatShr", "(", "shr1", ",", "\"shr\"", ")", "shr2", "=", "self", ".", "formatShr", "(", "shr2", ",", "\"shr\"", ")", "cmd0", "=", "IR", ".", "Comment", "(", "'exp('", "+", "expr_in", ".", "idf", "+", "')'", ",", "self", ".", "counter_inst", "+", "1", ")", "self", ".", "allDepths", "[", "self", ".", "counter_inst", "+", "1", "]", "=", "self", ".", "curDepth", "funcCall", "=", "IR", ".", "FuncCall", "(", "\"Exp\"", ",", "{", "expr_in", ":", "\"A\"", ",", "IR", ".", "Int", "(", "I", ")", ":", "\"I\"", ",", "IR", ".", "Int", "(", "J", ")", ":", "\"J\"", ",", "shr1", ":", "\"shrA\"", ",", "shr2", ":", "\"shrB\"", ",", "expr_out", ":", "\"B\"", "}", ")", "if", "not", "self", ".", "vbwEnabled", "else", "IR", ".", "FuncCall", "(", "\"Exp<int%d_t, int%d_t>\"", "%", "(", "bitwidth_in", ",", "bitwidth_out", ")", ",", "{", "expr_in", ":", "\"A\"", ",", "IR", ".", "Int", "(", "I", ")", ":", "\"I\"", ",", "IR", ".", "Int", "(", "J", ")", ":", "\"J\"", ",", "shr1", ":", "\"shrA\"", ",", "shr2", ":", "\"shrB\"", ",", "expr_out", ":", "\"B\"", ",", "IR", ".", "Int", "(", "1", ")", ":", "\"demote\"", "}", ")", "self", ".", "counter_inst", "+=", "1", "self", ".", "updateLiveRange", "(", "[", "expr_in", ",", "expr_out", "]", ")", "# This method is used in the profiling floating point stage to check whether the input values are beyond a threshold.", "# Input values beyond a threshold are always mapped to zero in fixed-point code, hence these datapoints hold little use in the fixed-point mode.", "rangeCheck", "=", "IR", ".", "FuncCall", "(", "\"checkRange2\"", ",", "{", "expr_in", ":", "\"A\"", ",", "IR", ".", "Int", "(", "I", ")", ":", "\"I\"", ",", "IR", ".", "Int", "(", "J", ")", ":", "\"J\"", "}", ")", "if", "self", ".", "functionReducedProfiling", "and", "forFloat", "(", ")", "else", "IR", ".", "Comment", "(", "\"Recommend switching on Function Reduced Profiling for sound output\"", ")", "profile", "=", "IR", ".", "FuncCall", "(", "\"Profile2\"", ",", "{", "expr_out", ":", "\"Var\"", ",", "IR", ".", "Int", "(", "I", ")", ":", "\"I\"", ",", "IR", ".", "Int", "(", "J", ")", ":", "\"J\"", ",", "IR", ".", "String", "(", "expr_out", ")", ":", "\"VarName\"", "}", ")", "if", "forFloat", "(", ")", ":", "self", ".", "independentVars", ".", "append", "(", "expr_out", ".", "idf", ")", "prog_exp", "=", "IR", ".", "Prog", "(", "[", "cmd0", ",", "rangeCheck", ",", "funcCall", ",", "profile", "]", "if", "forFloat", "(", ")", "and", "self", ".", "ddsEnabled", "else", "[", "cmd0", ",", "funcCall", "]", ")", "prog_out", "=", "IRUtil", ".", "concatPrograms", "(", "prog_in", ",", "prog_exp", ")", "# Update metadata.", "self", ".", "varDeclarations", "[", "expr_out", ".", "idf", "]", "=", "type_in", "self", ".", "varScales", "[", "expr_out", ".", "idf", "]", "=", "scale_out", "self", ".", "varIntervals", "[", "expr_out", ".", "idf", "]", "=", "intv_out", "return", "(", "prog_out", ",", "expr_out", ")" ]
https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/tools/SeeDot/seedot/compiler/ir/irBuilder.py#L2454-L2542
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/GifImagePlugin.py
python
getheader
(im, palette=None, info=None)
return header, used_palette_colors
Legacy Method to get Gif data from image. Warning:: May modify image data. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: tuple of(list of header items, optimized palette)
Legacy Method to get Gif data from image.
[ "Legacy", "Method", "to", "get", "Gif", "data", "from", "image", "." ]
def getheader(im, palette=None, info=None): """ Legacy Method to get Gif data from image. Warning:: May modify image data. :param im: Image object :param palette: bytes object containing the source palette, or .... :param info: encoderinfo :returns: tuple of(list of header items, optimized palette) """ used_palette_colors = _get_optimize(im, info) if info is None: info = {} if "background" not in info and "background" in im.info: info["background"] = im.info["background"] im_mod = _normalize_palette(im, palette, info) im.palette = im_mod.palette im.im = im_mod.im header = _get_global_header(im, info) return header, used_palette_colors
[ "def", "getheader", "(", "im", ",", "palette", "=", "None", ",", "info", "=", "None", ")", ":", "used_palette_colors", "=", "_get_optimize", "(", "im", ",", "info", ")", "if", "info", "is", "None", ":", "info", "=", "{", "}", "if", "\"background\"", "not", "in", "info", "and", "\"background\"", "in", "im", ".", "info", ":", "info", "[", "\"background\"", "]", "=", "im", ".", "info", "[", "\"background\"", "]", "im_mod", "=", "_normalize_palette", "(", "im", ",", "palette", ",", "info", ")", "im", ".", "palette", "=", "im_mod", ".", "palette", "im", ".", "im", "=", "im_mod", ".", "im", "header", "=", "_get_global_header", "(", "im", ",", "info", ")", "return", "header", ",", "used_palette_colors" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/GifImagePlugin.py#L812-L837
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
GeneratorInterface/LHEInterface/scripts/mergeLHE.py
python
DefaultLHEMerger.check_header_compatibility
(self)
Check if all headers for input files are consistent.
Check if all headers for input files are consistent.
[ "Check", "if", "all", "headers", "for", "input", "files", "are", "consistent", "." ]
def check_header_compatibility(self): """Check if all headers for input files are consistent.""" if self.bypass_check: return inconsistent_error_info = ("Incompatibility found in LHE headers: %s. " "Use -b/--bypass-check to bypass the check.") allow_diff_keys = [ 'nevent', 'numevts', 'iseed', 'Seed', 'Random', '.log', '.dat', '.lhe', 'Number of Events', 'Integrated weight' ] self._header_lines = [header.split('\n') for header in self._header_str] # Iterate over header lines for all input files and check consistency logging.debug('header line number: %s' \ % ', '.join([str(len(lines)) for lines in self._header_lines])) assert all([ len(self._header_lines[0]) == len(lines) for lines in self._header_lines] ), inconsistent_error_info % "line number not matches" inconsistent_lines_set = [set() for _ in self._header_lines] for line_zip in zip(*self._header_lines): if any([k in line_zip[0] for k in allow_diff_keys]): logging.debug('Captured \'%s\', we allow difference in this line' % line_zip[0]) continue if not all([line_zip[0] == line for line in line_zip]): # Ok so meet inconsistency in some lines, then temporarily store them for i, line in enumerate(line_zip): inconsistent_lines_set[i].add(line) # Those inconsistent lines still match, meaning that it is only a change of order assert all([inconsistent_lines_set[0] == lset for lset in inconsistent_lines_set]), \ inconsistent_error_info % ('{' + ', '.join(inconsistent_lines_set[0]) + '}')
[ "def", "check_header_compatibility", "(", "self", ")", ":", "if", "self", ".", "bypass_check", ":", "return", "inconsistent_error_info", "=", "(", "\"Incompatibility found in LHE headers: %s. \"", "\"Use -b/--bypass-check to bypass the check.\"", ")", "allow_diff_keys", "=", "[", "'nevent'", ",", "'numevts'", ",", "'iseed'", ",", "'Seed'", ",", "'Random'", ",", "'.log'", ",", "'.dat'", ",", "'.lhe'", ",", "'Number of Events'", ",", "'Integrated weight'", "]", "self", ".", "_header_lines", "=", "[", "header", ".", "split", "(", "'\\n'", ")", "for", "header", "in", "self", ".", "_header_str", "]", "# Iterate over header lines for all input files and check consistency", "logging", ".", "debug", "(", "'header line number: %s'", "%", "', '", ".", "join", "(", "[", "str", "(", "len", "(", "lines", ")", ")", "for", "lines", "in", "self", ".", "_header_lines", "]", ")", ")", "assert", "all", "(", "[", "len", "(", "self", ".", "_header_lines", "[", "0", "]", ")", "==", "len", "(", "lines", ")", "for", "lines", "in", "self", ".", "_header_lines", "]", ")", ",", "inconsistent_error_info", "%", "\"line number not matches\"", "inconsistent_lines_set", "=", "[", "set", "(", ")", "for", "_", "in", "self", ".", "_header_lines", "]", "for", "line_zip", "in", "zip", "(", "*", "self", ".", "_header_lines", ")", ":", "if", "any", "(", "[", "k", "in", "line_zip", "[", "0", "]", "for", "k", "in", "allow_diff_keys", "]", ")", ":", "logging", ".", "debug", "(", "'Captured \\'%s\\', we allow difference in this line'", "%", "line_zip", "[", "0", "]", ")", "continue", "if", "not", "all", "(", "[", "line_zip", "[", "0", "]", "==", "line", "for", "line", "in", "line_zip", "]", ")", ":", "# Ok so meet inconsistency in some lines, then temporarily store them", "for", "i", ",", "line", "in", "enumerate", "(", "line_zip", ")", ":", "inconsistent_lines_set", "[", "i", "]", ".", "add", "(", "line", ")", "# Those inconsistent lines still match, meaning that it is only a change of order", "assert", "all", "(", "[", "inconsistent_lines_set", "[", "0", "]", "==", "lset", "for", "lset", "in", "inconsistent_lines_set", "]", ")", ",", "inconsistent_error_info", "%", "(", "'{'", "+", "', '", ".", "join", "(", "inconsistent_lines_set", "[", "0", "]", ")", "+", "'}'", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/GeneratorInterface/LHEInterface/scripts/mergeLHE.py#L46-L77
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/style/checker.py
python
check_webkit_style_configuration
(options)
return StyleProcessorConfiguration(filter_configuration=filter_configuration, max_reports_per_category=_MAX_REPORTS_PER_CATEGORY, min_confidence=options.min_confidence, output_format=options.output_format, stderr_write=sys.stderr.write)
Return a StyleProcessorConfiguration instance for check-webkit-style. Args: options: A CommandOptionValues instance.
Return a StyleProcessorConfiguration instance for check-webkit-style.
[ "Return", "a", "StyleProcessorConfiguration", "instance", "for", "check", "-", "webkit", "-", "style", "." ]
def check_webkit_style_configuration(options): """Return a StyleProcessorConfiguration instance for check-webkit-style. Args: options: A CommandOptionValues instance. """ filter_configuration = FilterConfiguration( base_rules=_BASE_FILTER_RULES, path_specific=_PATH_RULES_SPECIFIER, user_rules=options.filter_rules) return StyleProcessorConfiguration(filter_configuration=filter_configuration, max_reports_per_category=_MAX_REPORTS_PER_CATEGORY, min_confidence=options.min_confidence, output_format=options.output_format, stderr_write=sys.stderr.write)
[ "def", "check_webkit_style_configuration", "(", "options", ")", ":", "filter_configuration", "=", "FilterConfiguration", "(", "base_rules", "=", "_BASE_FILTER_RULES", ",", "path_specific", "=", "_PATH_RULES_SPECIFIER", ",", "user_rules", "=", "options", ".", "filter_rules", ")", "return", "StyleProcessorConfiguration", "(", "filter_configuration", "=", "filter_configuration", ",", "max_reports_per_category", "=", "_MAX_REPORTS_PER_CATEGORY", ",", "min_confidence", "=", "options", ".", "min_confidence", ",", "output_format", "=", "options", ".", "output_format", ",", "stderr_write", "=", "sys", ".", "stderr", ".", "write", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/style/checker.py#L272-L288
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Text.mark_unset
(self, *markNames)
Delete all marks in MARKNAMES.
Delete all marks in MARKNAMES.
[ "Delete", "all", "marks", "in", "MARKNAMES", "." ]
def mark_unset(self, *markNames): """Delete all marks in MARKNAMES.""" self.tk.call((self._w, 'mark', 'unset') + markNames)
[ "def", "mark_unset", "(", "self", ",", "*", "markNames", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'mark'", ",", "'unset'", ")", "+", "markNames", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L3061-L3063
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/youtube/service.py
python
YouTubeService.GetYouTubeVideoFeed
(self, uri)
return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
Retrieve a YouTubeVideoFeed. Args: uri: A string representing the URI of the feed that is to be retrieved. Returns: A YouTubeVideoFeed if successfully retrieved.
Retrieve a YouTubeVideoFeed.
[ "Retrieve", "a", "YouTubeVideoFeed", "." ]
def GetYouTubeVideoFeed(self, uri): """Retrieve a YouTubeVideoFeed. Args: uri: A string representing the URI of the feed that is to be retrieved. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
[ "def", "GetYouTubeVideoFeed", "(", "self", ",", "uri", ")", ":", "return", "self", ".", "Get", "(", "uri", ",", "converter", "=", "gdata", ".", "youtube", ".", "YouTubeVideoFeedFromString", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/youtube/service.py#L172-L181
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
applications/graph/communityGAN/util/__init__.py
python
ceildiv
(x, y)
return -(-x // y)
ceil(x/y)
ceil(x/y)
[ "ceil", "(", "x", "/", "y", ")" ]
def ceildiv(x, y): """ceil(x/y)""" return -(-x // y)
[ "def", "ceildiv", "(", "x", ",", "y", ")", ":", "return", "-", "(", "-", "x", "//", "y", ")" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/applications/graph/communityGAN/util/__init__.py#L19-L21
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
Co-Simulation/Sumo/sumo_integration/sumo_simulation.py
python
SumoTLManager.unsubscribe
(tlid)
Unsubscribe the given traffic ligth from receiving updated information each step.
Unsubscribe the given traffic ligth from receiving updated information each step.
[ "Unsubscribe", "the", "given", "traffic", "ligth", "from", "receiving", "updated", "information", "each", "step", "." ]
def unsubscribe(tlid): """ Unsubscribe the given traffic ligth from receiving updated information each step. """ traci.trafficlight.unsubscribe(tlid)
[ "def", "unsubscribe", "(", "tlid", ")", ":", "traci", ".", "trafficlight", ".", "unsubscribe", "(", "tlid", ")" ]
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/Co-Simulation/Sumo/sumo_integration/sumo_simulation.py#L197-L201
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/mixture/_base.py
python
BaseMixture.fit
(self, X, y=None)
return self
Estimate model parameters with the EM algorithm. The method fits the model ``n_init`` times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for ``max_iter`` times until the change of likelihood or lower bound is less than ``tol``, otherwise, a ``ConvergenceWarning`` is raised. If ``warm_start`` is ``True``, then ``n_init`` is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off. Parameters ---------- X : array-like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- self
Estimate model parameters with the EM algorithm.
[ "Estimate", "model", "parameters", "with", "the", "EM", "algorithm", "." ]
def fit(self, X, y=None): """Estimate model parameters with the EM algorithm. The method fits the model ``n_init`` times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for ``max_iter`` times until the change of likelihood or lower bound is less than ``tol``, otherwise, a ``ConvergenceWarning`` is raised. If ``warm_start`` is ``True``, then ``n_init`` is ignored and a single initialization is performed upon the first call. Upon consecutive calls, training starts where it left off. Parameters ---------- X : array-like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- self """ self.fit_predict(X, y) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "fit_predict", "(", "X", ",", "y", ")", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/mixture/_base.py#L170-L193
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/spreadsheet/service.py
python
SpreadsheetsService.DeleteRow
(self, entry)
Deletes a row, the provided entry Args: entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted Returns: The delete response
Deletes a row, the provided entry Args: entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted Returns: The delete response
[ "Deletes", "a", "row", "the", "provided", "entry", "Args", ":", "entry", ":", "gdata", ".", "spreadsheet", ".", "SpreadsheetsList", "The", "row", "to", "be", "deleted", "Returns", ":", "The", "delete", "response" ]
def DeleteRow(self, entry): """Deletes a row, the provided entry Args: entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted Returns: The delete response """ for a_link in entry.link: if a_link.rel == 'edit': return self.Delete(a_link.href)
[ "def", "DeleteRow", "(", "self", ",", "entry", ")", ":", "for", "a_link", "in", "entry", ".", "link", ":", "if", "a_link", ".", "rel", "==", "'edit'", ":", "return", "self", ".", "Delete", "(", "a_link", ".", "href", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/spreadsheet/service.py#L359-L370
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py
python
CGIHTTPRequestHandler.is_executable
(self, path)
return executable(path)
Test whether argument path is an executable file.
Test whether argument path is an executable file.
[ "Test", "whether", "argument", "path", "is", "an", "executable", "file", "." ]
def is_executable(self, path): """Test whether argument path is an executable file.""" return executable(path)
[ "def", "is_executable", "(", "self", ",", "path", ")", ":", "return", "executable", "(", "path", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py#L1018-L1020
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/results.py
python
Numbers.pc_covered_str
(self)
return "%.*f" % (self._precision, pc)
Returns the percent covered, as a string, without a percent sign. Note that "0" is only returned when the value is truly zero, and "100" is only returned when the value is truly 100. Rounding can never result in either "0" or "100".
Returns the percent covered, as a string, without a percent sign.
[ "Returns", "the", "percent", "covered", "as", "a", "string", "without", "a", "percent", "sign", "." ]
def pc_covered_str(self): """Returns the percent covered, as a string, without a percent sign. Note that "0" is only returned when the value is truly zero, and "100" is only returned when the value is truly 100. Rounding can never result in either "0" or "100". """ pc = self.pc_covered if 0 < pc < self._near0: pc = self._near0 elif self._near100 < pc < 100: pc = self._near100 else: pc = round(pc, self._precision) return "%.*f" % (self._precision, pc)
[ "def", "pc_covered_str", "(", "self", ")", ":", "pc", "=", "self", ".", "pc_covered", "if", "0", "<", "pc", "<", "self", ".", "_near0", ":", "pc", "=", "self", ".", "_near0", "elif", "self", ".", "_near100", "<", "pc", "<", "100", ":", "pc", "=", "self", ".", "_near100", "else", ":", "pc", "=", "round", "(", "pc", ",", "self", ".", "_precision", ")", "return", "\"%.*f\"", "%", "(", "self", ".", "_precision", ",", "pc", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/results.py#L222-L237
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/boxing.py
python
unbox_tuple
(typ, obj, c)
return NativeValue(c.builder.load(value_ptr), cleanup=cleanup, is_error=c.builder.load(is_error_ptr))
Convert tuple *obj* to a native array (if homogeneous) or structure.
Convert tuple *obj* to a native array (if homogeneous) or structure.
[ "Convert", "tuple", "*", "obj", "*", "to", "a", "native", "array", "(", "if", "homogeneous", ")", "or", "structure", "." ]
def unbox_tuple(typ, obj, c): """ Convert tuple *obj* to a native array (if homogeneous) or structure. """ n = len(typ) values = [] cleanups = [] lty = c.context.get_value_type(typ) is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) value_ptr = cgutils.alloca_once(c.builder, lty) # Issue #1638: need to check the tuple size actual_size = c.pyapi.tuple_size(obj) size_matches = c.builder.icmp_unsigned('==', actual_size, ir.Constant(actual_size.type, n)) with c.builder.if_then(c.builder.not_(size_matches), likely=False): c.pyapi.err_format( "PyExc_ValueError", "size mismatch for tuple, expected %d element(s) but got %%zd" % (n,), actual_size) c.builder.store(cgutils.true_bit, is_error_ptr) # We unbox the items even if not `size_matches`, to avoid issues with # the generated IR (instruction doesn't dominate all uses) for i, eltype in enumerate(typ): elem = c.pyapi.tuple_getitem(obj, i) native = c.unbox(eltype, elem) values.append(native.value) with c.builder.if_then(native.is_error, likely=False): c.builder.store(cgutils.true_bit, is_error_ptr) if native.cleanup is not None: cleanups.append(native.cleanup) value = c.context.make_tuple(c.builder, typ, values) c.builder.store(value, value_ptr) if cleanups: with c.builder.if_then(size_matches, likely=True): def cleanup(): for func in reversed(cleanups): func() else: cleanup = None return NativeValue(c.builder.load(value_ptr), cleanup=cleanup, is_error=c.builder.load(is_error_ptr))
[ "def", "unbox_tuple", "(", "typ", ",", "obj", ",", "c", ")", ":", "n", "=", "len", "(", "typ", ")", "values", "=", "[", "]", "cleanups", "=", "[", "]", "lty", "=", "c", ".", "context", ".", "get_value_type", "(", "typ", ")", "is_error_ptr", "=", "cgutils", ".", "alloca_once_value", "(", "c", ".", "builder", ",", "cgutils", ".", "false_bit", ")", "value_ptr", "=", "cgutils", ".", "alloca_once", "(", "c", ".", "builder", ",", "lty", ")", "# Issue #1638: need to check the tuple size", "actual_size", "=", "c", ".", "pyapi", ".", "tuple_size", "(", "obj", ")", "size_matches", "=", "c", ".", "builder", ".", "icmp_unsigned", "(", "'=='", ",", "actual_size", ",", "ir", ".", "Constant", "(", "actual_size", ".", "type", ",", "n", ")", ")", "with", "c", ".", "builder", ".", "if_then", "(", "c", ".", "builder", ".", "not_", "(", "size_matches", ")", ",", "likely", "=", "False", ")", ":", "c", ".", "pyapi", ".", "err_format", "(", "\"PyExc_ValueError\"", ",", "\"size mismatch for tuple, expected %d element(s) but got %%zd\"", "%", "(", "n", ",", ")", ",", "actual_size", ")", "c", ".", "builder", ".", "store", "(", "cgutils", ".", "true_bit", ",", "is_error_ptr", ")", "# We unbox the items even if not `size_matches`, to avoid issues with", "# the generated IR (instruction doesn't dominate all uses)", "for", "i", ",", "eltype", "in", "enumerate", "(", "typ", ")", ":", "elem", "=", "c", ".", "pyapi", ".", "tuple_getitem", "(", "obj", ",", "i", ")", "native", "=", "c", ".", "unbox", "(", "eltype", ",", "elem", ")", "values", ".", "append", "(", "native", ".", "value", ")", "with", "c", ".", "builder", ".", "if_then", "(", "native", ".", "is_error", ",", "likely", "=", "False", ")", ":", "c", ".", "builder", ".", "store", "(", "cgutils", ".", "true_bit", ",", "is_error_ptr", ")", "if", "native", ".", "cleanup", "is", "not", "None", ":", "cleanups", ".", "append", "(", "native", ".", "cleanup", ")", "value", "=", "c", ".", "context", ".", "make_tuple", "(", "c", ".", "builder", ",", "typ", ",", "values", ")", "c", ".", "builder", ".", "store", "(", "value", ",", "value_ptr", ")", "if", "cleanups", ":", "with", "c", ".", "builder", ".", "if_then", "(", "size_matches", ",", "likely", "=", "True", ")", ":", "def", "cleanup", "(", ")", ":", "for", "func", "in", "reversed", "(", "cleanups", ")", ":", "func", "(", ")", "else", ":", "cleanup", "=", "None", "return", "NativeValue", "(", "c", ".", "builder", ".", "load", "(", "value_ptr", ")", ",", "cleanup", "=", "cleanup", ",", "is_error", "=", "c", ".", "builder", ".", "load", "(", "is_error_ptr", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/boxing.py#L514-L560
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py
python
Dir._morph
(self)
Turn a file system Node (either a freshly initialized directory object or a separate Entry object) into a proper directory object. Set up this directory's entries and hook it into the file system tree. Specify that directories (this Node) don't use signatures for calculating whether they're current.
Turn a file system Node (either a freshly initialized directory object or a separate Entry object) into a proper directory object.
[ "Turn", "a", "file", "system", "Node", "(", "either", "a", "freshly", "initialized", "directory", "object", "or", "a", "separate", "Entry", "object", ")", "into", "a", "proper", "directory", "object", "." ]
def _morph(self): """Turn a file system Node (either a freshly initialized directory object or a separate Entry object) into a proper directory object. Set up this directory's entries and hook it into the file system tree. Specify that directories (this Node) don't use signatures for calculating whether they're current. """ self.repositories = [] self.srcdir = None self.entries = {} self.entries['.'] = self self.entries['..'] = self.dir self.cwd = self self.searched = 0 self._sconsign = None self.variant_dirs = [] self.root = self.dir.root self.changed_since_last_build = 3 self._func_sconsign = 1 self._func_exists = 2 self._func_get_contents = 2 self._abspath = SCons.Util.silent_intern(self.dir.entry_abspath(self.name)) self._labspath = SCons.Util.silent_intern(self.dir.entry_labspath(self.name)) if self.dir._path == '.': self._path = SCons.Util.silent_intern(self.name) else: self._path = SCons.Util.silent_intern(self.dir.entry_path(self.name)) if self.dir._tpath == '.': self._tpath = SCons.Util.silent_intern(self.name) else: self._tpath = SCons.Util.silent_intern(self.dir.entry_tpath(self.name)) self._path_elements = self.dir._path_elements + [self] # For directories, we make a difference between the directory # 'name' and the directory 'dirname'. The 'name' attribute is # used when we need to print the 'name' of the directory or # when we it is used as the last part of a path. The 'dirname' # is used when the directory is not the last element of the # path. The main reason for making that distinction is that # for RoorDir's the dirname can not be easily inferred from # the name. For example, we have to add a '/' after a drive # letter but not after a UNC path prefix ('//'). self.dirname = self.name + OS_SEP # Don't just reset the executor, replace its action list, # because it might have some pre-or post-actions that need to # be preserved. # # But don't reset the executor if there is a non-null executor # attached already. The existing executor might have other # targets, in which case replacing the action list with a # Mkdir action is a big mistake. if not hasattr(self, 'executor'): self.builder = get_MkdirBuilder() self.get_executor().set_action_list(self.builder.action) else: # Prepend MkdirBuilder action to existing action list l = self.get_executor().action_list a = get_MkdirBuilder().action l.insert(0, a) self.get_executor().set_action_list(l)
[ "def", "_morph", "(", "self", ")", ":", "self", ".", "repositories", "=", "[", "]", "self", ".", "srcdir", "=", "None", "self", ".", "entries", "=", "{", "}", "self", ".", "entries", "[", "'.'", "]", "=", "self", "self", ".", "entries", "[", "'..'", "]", "=", "self", ".", "dir", "self", ".", "cwd", "=", "self", "self", ".", "searched", "=", "0", "self", ".", "_sconsign", "=", "None", "self", ".", "variant_dirs", "=", "[", "]", "self", ".", "root", "=", "self", ".", "dir", ".", "root", "self", ".", "changed_since_last_build", "=", "3", "self", ".", "_func_sconsign", "=", "1", "self", ".", "_func_exists", "=", "2", "self", ".", "_func_get_contents", "=", "2", "self", ".", "_abspath", "=", "SCons", ".", "Util", ".", "silent_intern", "(", "self", ".", "dir", ".", "entry_abspath", "(", "self", ".", "name", ")", ")", "self", ".", "_labspath", "=", "SCons", ".", "Util", ".", "silent_intern", "(", "self", ".", "dir", ".", "entry_labspath", "(", "self", ".", "name", ")", ")", "if", "self", ".", "dir", ".", "_path", "==", "'.'", ":", "self", ".", "_path", "=", "SCons", ".", "Util", ".", "silent_intern", "(", "self", ".", "name", ")", "else", ":", "self", ".", "_path", "=", "SCons", ".", "Util", ".", "silent_intern", "(", "self", ".", "dir", ".", "entry_path", "(", "self", ".", "name", ")", ")", "if", "self", ".", "dir", ".", "_tpath", "==", "'.'", ":", "self", ".", "_tpath", "=", "SCons", ".", "Util", ".", "silent_intern", "(", "self", ".", "name", ")", "else", ":", "self", ".", "_tpath", "=", "SCons", ".", "Util", ".", "silent_intern", "(", "self", ".", "dir", ".", "entry_tpath", "(", "self", ".", "name", ")", ")", "self", ".", "_path_elements", "=", "self", ".", "dir", ".", "_path_elements", "+", "[", "self", "]", "# For directories, we make a difference between the directory", "# 'name' and the directory 'dirname'. The 'name' attribute is", "# used when we need to print the 'name' of the directory or", "# when we it is used as the last part of a path. The 'dirname'", "# is used when the directory is not the last element of the", "# path. The main reason for making that distinction is that", "# for RoorDir's the dirname can not be easily inferred from", "# the name. For example, we have to add a '/' after a drive", "# letter but not after a UNC path prefix ('//').", "self", ".", "dirname", "=", "self", ".", "name", "+", "OS_SEP", "# Don't just reset the executor, replace its action list,", "# because it might have some pre-or post-actions that need to", "# be preserved.", "#", "# But don't reset the executor if there is a non-null executor", "# attached already. The existing executor might have other", "# targets, in which case replacing the action list with a", "# Mkdir action is a big mistake.", "if", "not", "hasattr", "(", "self", ",", "'executor'", ")", ":", "self", ".", "builder", "=", "get_MkdirBuilder", "(", ")", "self", ".", "get_executor", "(", ")", ".", "set_action_list", "(", "self", ".", "builder", ".", "action", ")", "else", ":", "# Prepend MkdirBuilder action to existing action list", "l", "=", "self", ".", "get_executor", "(", ")", ".", "action_list", "a", "=", "get_MkdirBuilder", "(", ")", ".", "action", "l", ".", "insert", "(", "0", ",", "a", ")", "self", ".", "get_executor", "(", ")", ".", "set_action_list", "(", "l", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L1543-L1607
ProgerXP/Notepad2e
71585758099ec07d61dd14ba806068c0d937efd3
scintilla/scripts/Dependencies.py
python
InsertSynonym
(dependencies, current, additional)
return result
Insert a copy of one object file with dependencies under a different name. Used when one source file is used to create two object files with different preprocessor definitions.
Insert a copy of one object file with dependencies under a different name. Used when one source file is used to create two object files with different preprocessor definitions.
[ "Insert", "a", "copy", "of", "one", "object", "file", "with", "dependencies", "under", "a", "different", "name", ".", "Used", "when", "one", "source", "file", "is", "used", "to", "create", "two", "object", "files", "with", "different", "preprocessor", "definitions", "." ]
def InsertSynonym(dependencies, current, additional): """ Insert a copy of one object file with dependencies under a different name. Used when one source file is used to create two object files with different preprocessor definitions. """ result = [] for dep in dependencies: result.append(dep) if (dep[0] == current): depAdd = [additional, dep[1]] result.append(depAdd) return result
[ "def", "InsertSynonym", "(", "dependencies", ",", "current", ",", "additional", ")", ":", "result", "=", "[", "]", "for", "dep", "in", "dependencies", ":", "result", ".", "append", "(", "dep", ")", "if", "(", "dep", "[", "0", "]", "==", "current", ")", ":", "depAdd", "=", "[", "additional", ",", "dep", "[", "1", "]", "]", "result", ".", "append", "(", "depAdd", ")", "return", "result" ]
https://github.com/ProgerXP/Notepad2e/blob/71585758099ec07d61dd14ba806068c0d937efd3/scintilla/scripts/Dependencies.py#L89-L99
shader-slang/slang
b8982fcf43b86c1e39dcc3dd19bff2821633eda6
external/vulkan/registry/conventions.py
python
ConventionsBase.refpage_generated_include_path
(self)
Return path relative to the generated reference pages, to the generated API include files. Must implement.
Return path relative to the generated reference pages, to the generated API include files.
[ "Return", "path", "relative", "to", "the", "generated", "reference", "pages", "to", "the", "generated", "API", "include", "files", "." ]
def refpage_generated_include_path(self): """Return path relative to the generated reference pages, to the generated API include files. Must implement.""" raise NotImplementedError
[ "def", "refpage_generated_include_path", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/conventions.py#L344-L349
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/pythonlibs/download_helper.py
python
clone_repo
(url, target_directory)
return result
Clone the given git repo into the target_directory
Clone the given git repo into the target_directory
[ "Clone", "the", "given", "git", "repo", "into", "the", "target_directory" ]
def clone_repo(url, target_directory): """ Clone the given git repo into the target_directory """ global _cloned_repos repo_name = os.path.basename(url) saved = os.getcwd() repo = os.path.join(target_directory, repo_name) if url in _cloned_repos: return _cloned_repos[url] if url in _cloned_repos: return _cloned_repos[url] if os.path.isdir(repo): _logger.info("### Updating git repo: '{}' at '{}'".format(repo_name, target_directory)) os.chdir(repo) _run(["git", "pull"]) else: os.chdir(target_directory) _logger.info("### Cloning git repo: '{}' into '{}'".format(repo_name, target_directory)) _run(["git", "lfs", "install"]) _run(["git", "clone", url]) os.chdir(saved) result = repo + os.path.sep _cloned_repos[url] = result return result
[ "def", "clone_repo", "(", "url", ",", "target_directory", ")", ":", "global", "_cloned_repos", "repo_name", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "saved", "=", "os", ".", "getcwd", "(", ")", "repo", "=", "os", ".", "path", ".", "join", "(", "target_directory", ",", "repo_name", ")", "if", "url", "in", "_cloned_repos", ":", "return", "_cloned_repos", "[", "url", "]", "if", "url", "in", "_cloned_repos", ":", "return", "_cloned_repos", "[", "url", "]", "if", "os", ".", "path", ".", "isdir", "(", "repo", ")", ":", "_logger", ".", "info", "(", "\"### Updating git repo: '{}' at '{}'\"", ".", "format", "(", "repo_name", ",", "target_directory", ")", ")", "os", ".", "chdir", "(", "repo", ")", "_run", "(", "[", "\"git\"", ",", "\"pull\"", "]", ")", "else", ":", "os", ".", "chdir", "(", "target_directory", ")", "_logger", ".", "info", "(", "\"### Cloning git repo: '{}' into '{}'\"", ".", "format", "(", "repo_name", ",", "target_directory", ")", ")", "_run", "(", "[", "\"git\"", ",", "\"lfs\"", ",", "\"install\"", "]", ")", "_run", "(", "[", "\"git\"", ",", "\"clone\"", ",", "url", "]", ")", "os", ".", "chdir", "(", "saved", ")", "result", "=", "repo", "+", "os", ".", "path", ".", "sep", "_cloned_repos", "[", "url", "]", "=", "result", "return", "result" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/download_helper.py#L116-L146
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/numpy/linalg.py
python
inv
(a)
return _api_internal.inv(a)
r""" Compute the (multiplicative) inverse of a matrix. Given a square matrix `a`, return the matrix `ainv` satisfying ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``. Parameters ---------- a : (..., M, M) ndarray Matrix to be inverted. Returns ------- ainv : (..., M, M) ndarray (Multiplicative) inverse of the matrix `a`. Raises ------ MXNetError If `a` is not square or inversion fails. Examples -------- >>> from mxnet import np >>> a = np.array([[1., 2.], [3., 4.]]) array([[-2. , 1. ], [ 1.5, -0.5]]) Inverses of several matrices can be computed at once: >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) >>> np.linalg.inv(a) array([[[-2. , 1. ], [ 1.5 , -0.5 ]], [[-1.2500001 , 0.75000006], [ 0.75000006, -0.25000003]]])
r""" Compute the (multiplicative) inverse of a matrix.
[ "r", "Compute", "the", "(", "multiplicative", ")", "inverse", "of", "a", "matrix", "." ]
def inv(a): r""" Compute the (multiplicative) inverse of a matrix. Given a square matrix `a`, return the matrix `ainv` satisfying ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``. Parameters ---------- a : (..., M, M) ndarray Matrix to be inverted. Returns ------- ainv : (..., M, M) ndarray (Multiplicative) inverse of the matrix `a`. Raises ------ MXNetError If `a` is not square or inversion fails. Examples -------- >>> from mxnet import np >>> a = np.array([[1., 2.], [3., 4.]]) array([[-2. , 1. ], [ 1.5, -0.5]]) Inverses of several matrices can be computed at once: >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) >>> np.linalg.inv(a) array([[[-2. , 1. ], [ 1.5 , -0.5 ]], [[-1.2500001 , 0.75000006], [ 0.75000006, -0.25000003]]]) """ return _api_internal.inv(a)
[ "def", "inv", "(", "a", ")", ":", "return", "_api_internal", ".", "inv", "(", "a", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/linalg.py#L581-L620
microsoft/EdgeML
ef9f8a77f096acbdeb941014791f8eda1c1bc35b
pytorch/edgeml_pytorch/trainer/fastTrainer.py
python
FastTrainer.classifier
(self, feats)
return torch.matmul(feats, self.FC) + self.FCbias
Can be raplaced by any classifier TODO: Make this a separate class if needed
Can be raplaced by any classifier TODO: Make this a separate class if needed
[ "Can", "be", "raplaced", "by", "any", "classifier", "TODO", ":", "Make", "this", "a", "separate", "class", "if", "needed" ]
def classifier(self, feats): ''' Can be raplaced by any classifier TODO: Make this a separate class if needed ''' return torch.matmul(feats, self.FC) + self.FCbias
[ "def", "classifier", "(", "self", ",", "feats", ")", ":", "return", "torch", ".", "matmul", "(", "feats", ",", "self", ".", "FC", ")", "+", "self", ".", "FCbias" ]
https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/pytorch/edgeml_pytorch/trainer/fastTrainer.py#L64-L69
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/warnings.py
python
showwarning
(message, category, filename, lineno, file=None, line=None)
Hook to write a warning to a file; replace if you like.
Hook to write a warning to a file; replace if you like.
[ "Hook", "to", "write", "a", "warning", "to", "a", "file", ";", "replace", "if", "you", "like", "." ]
def showwarning(message, category, filename, lineno, file=None, line=None): """Hook to write a warning to a file; replace if you like.""" msg = WarningMessage(message, category, filename, lineno, file, line) _showwarnmsg_impl(msg)
[ "def", "showwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "file", "=", "None", ",", "line", "=", "None", ")", ":", "msg", "=", "WarningMessage", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "file", ",", "line", ")", "_showwarnmsg_impl", "(", "msg", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/warnings.py#L10-L13
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
dev/archery/archery/release.py
python
Release.commits
(self)
return list(map(Commit, self.repo.iter_commits(commit_range)))
All commits applied between two versions.
All commits applied between two versions.
[ "All", "commits", "applied", "between", "two", "versions", "." ]
def commits(self): """ All commits applied between two versions. """ if self.previous is None: # first release lower = '' else: lower = self.repo.tags[self.previous.tag] if self.version.released: upper = self.repo.tags[self.tag] else: try: upper = self.repo.branches[self.branch] except IndexError: warnings.warn("Release branch `{}` doesn't exist." .format(self.branch)) return [] commit_range = "{}..{}".format(lower, upper) return list(map(Commit, self.repo.iter_commits(commit_range)))
[ "def", "commits", "(", "self", ")", ":", "if", "self", ".", "previous", "is", "None", ":", "# first release", "lower", "=", "''", "else", ":", "lower", "=", "self", ".", "repo", ".", "tags", "[", "self", ".", "previous", ".", "tag", "]", "if", "self", ".", "version", ".", "released", ":", "upper", "=", "self", ".", "repo", ".", "tags", "[", "self", ".", "tag", "]", "else", ":", "try", ":", "upper", "=", "self", ".", "repo", ".", "branches", "[", "self", ".", "branch", "]", "except", "IndexError", ":", "warnings", ".", "warn", "(", "\"Release branch `{}` doesn't exist.\"", ".", "format", "(", "self", ".", "branch", ")", ")", "return", "[", "]", "commit_range", "=", "\"{}..{}\"", ".", "format", "(", "lower", ",", "upper", ")", "return", "list", "(", "map", "(", "Commit", ",", "self", ".", "repo", ".", "iter_commits", "(", "commit_range", ")", ")", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/release.py#L357-L378
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Wrapping/Python/vtkmodules/wx/wxVTKRenderWindow.py
python
wxVTKRenderWindow.__init__
(self, parent, ID, *args, **kw)
Default class constructor. @param parent: parent window @param ID: window id @param **kw: wxPython keywords (position, size, style) plus the 'stereo' keyword
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self, parent, ID, *args, **kw): """Default class constructor. @param parent: parent window @param ID: window id @param **kw: wxPython keywords (position, size, style) plus the 'stereo' keyword """ # miscellaneous protected variables self._CurrentRenderer = None self._CurrentCamera = None self._CurrentZoom = 1.0 self._CurrentLight = None self._ViewportCenterX = 0 self._ViewportCenterY = 0 self._Picker = vtkCellPicker() self._PickedActor = None self._PickedProperty = vtkProperty() self._PickedProperty.SetColor(1,0,0) self._PrePickedProperty = None # these record the previous mouse position self._LastX = 0 self._LastY = 0 # the current interaction mode (Rotate, Pan, Zoom, etc) self._Mode = None self._ActiveButton = None # private attributes self.__OldFocus = None # used by the LOD actors self._DesiredUpdateRate = 15 self._StillUpdateRate = 0.0001 # First do special handling of some keywords: # stereo, position, size, width, height, style try: stereo = bool(kw['stereo']) del kw['stereo'] except KeyError: stereo = False try: position = kw['position'] del kw['position'] except KeyError: position = wx.DefaultPosition try: size = kw['size'] del kw['size'] except KeyError: try: size = parent.GetSize() except AttributeError: size = wx.DefaultSize # wx.WANTS_CHARS says to give us e.g. TAB # wx.NO_FULL_REPAINT_ON_RESIZE cuts down resize flicker under GTK style = wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE try: style = style | kw['style'] del kw['style'] except KeyError: pass # the enclosing frame must be shown under GTK or the windows # don't connect together properly l = [] p = parent while p: # make a list of all parents l.append(p) p = p.GetParent() l.reverse() # sort list into descending order for p in l: p.Show(1) # initialize the wx.Window if baseClass.__name__ == 'GLCanvas': # Set the doublebuffer attribute of the GL canvas. baseClass.__init__(self, parent, ID, pos=position, size=size, style=style, attribList=[wx.glcanvas.WX_GL_DOUBLEBUFFER]) else: baseClass.__init__(self, parent, ID, pos=position, size=size, style=style) # create the RenderWindow and initialize it self._RenderWindow = vtkRenderWindow() self._RenderWindow.SetSize(size.width, size.height) if stereo: self._RenderWindow.StereoCapableWindowOn() self._RenderWindow.SetStereoTypeToCrystalEyes() self.__handle = None # refresh window by doing a Render self.Bind(wx.EVT_PAINT, self.OnPaint) # turn off background erase to reduce flicker self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None) # Bind the events to the event converters self.Bind(wx.EVT_RIGHT_DOWN, self._OnButtonDown) self.Bind(wx.EVT_LEFT_DOWN, self._OnButtonDown) self.Bind(wx.EVT_MIDDLE_DOWN, self._OnButtonDown) self.Bind(wx.EVT_RIGHT_UP, self._OnButtonUp) self.Bind(wx.EVT_LEFT_UP, self._OnButtonUp) self.Bind(wx.EVT_MIDDLE_UP, self._OnButtonUp) self.Bind(wx.EVT_MOTION, self.OnMotion) self.Bind(wx.EVT_ENTER_WINDOW, self._OnEnterWindow) self.Bind(wx.EVT_LEAVE_WINDOW, self._OnLeaveWindow) self.Bind(wx.EVT_CHAR, self.OnChar) # If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions # of all characters are always returned. EVT_CHAR also performs # other necessary keyboard-dependent translations. self.Bind(wx.EVT_CHAR, self.OnKeyDown) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.Bind(wx.EVT_SIZE, self._OnSize) self.Bind(wx.EVT_MOVE, self.OnMove) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
[ "def", "__init__", "(", "self", ",", "parent", ",", "ID", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# miscellaneous protected variables", "self", ".", "_CurrentRenderer", "=", "None", "self", ".", "_CurrentCamera", "=", "None", "self", ".", "_CurrentZoom", "=", "1.0", "self", ".", "_CurrentLight", "=", "None", "self", ".", "_ViewportCenterX", "=", "0", "self", ".", "_ViewportCenterY", "=", "0", "self", ".", "_Picker", "=", "vtkCellPicker", "(", ")", "self", ".", "_PickedActor", "=", "None", "self", ".", "_PickedProperty", "=", "vtkProperty", "(", ")", "self", ".", "_PickedProperty", ".", "SetColor", "(", "1", ",", "0", ",", "0", ")", "self", ".", "_PrePickedProperty", "=", "None", "# these record the previous mouse position", "self", ".", "_LastX", "=", "0", "self", ".", "_LastY", "=", "0", "# the current interaction mode (Rotate, Pan, Zoom, etc)", "self", ".", "_Mode", "=", "None", "self", ".", "_ActiveButton", "=", "None", "# private attributes", "self", ".", "__OldFocus", "=", "None", "# used by the LOD actors", "self", ".", "_DesiredUpdateRate", "=", "15", "self", ".", "_StillUpdateRate", "=", "0.0001", "# First do special handling of some keywords:", "# stereo, position, size, width, height, style", "try", ":", "stereo", "=", "bool", "(", "kw", "[", "'stereo'", "]", ")", "del", "kw", "[", "'stereo'", "]", "except", "KeyError", ":", "stereo", "=", "False", "try", ":", "position", "=", "kw", "[", "'position'", "]", "del", "kw", "[", "'position'", "]", "except", "KeyError", ":", "position", "=", "wx", ".", "DefaultPosition", "try", ":", "size", "=", "kw", "[", "'size'", "]", "del", "kw", "[", "'size'", "]", "except", "KeyError", ":", "try", ":", "size", "=", "parent", ".", "GetSize", "(", ")", "except", "AttributeError", ":", "size", "=", "wx", ".", "DefaultSize", "# wx.WANTS_CHARS says to give us e.g. TAB", "# wx.NO_FULL_REPAINT_ON_RESIZE cuts down resize flicker under GTK", "style", "=", "wx", ".", "WANTS_CHARS", "|", "wx", ".", "NO_FULL_REPAINT_ON_RESIZE", "try", ":", "style", "=", "style", "|", "kw", "[", "'style'", "]", "del", "kw", "[", "'style'", "]", "except", "KeyError", ":", "pass", "# the enclosing frame must be shown under GTK or the windows", "# don't connect together properly", "l", "=", "[", "]", "p", "=", "parent", "while", "p", ":", "# make a list of all parents", "l", ".", "append", "(", "p", ")", "p", "=", "p", ".", "GetParent", "(", ")", "l", ".", "reverse", "(", ")", "# sort list into descending order", "for", "p", "in", "l", ":", "p", ".", "Show", "(", "1", ")", "# initialize the wx.Window", "if", "baseClass", ".", "__name__", "==", "'GLCanvas'", ":", "# Set the doublebuffer attribute of the GL canvas.", "baseClass", ".", "__init__", "(", "self", ",", "parent", ",", "ID", ",", "pos", "=", "position", ",", "size", "=", "size", ",", "style", "=", "style", ",", "attribList", "=", "[", "wx", ".", "glcanvas", ".", "WX_GL_DOUBLEBUFFER", "]", ")", "else", ":", "baseClass", ".", "__init__", "(", "self", ",", "parent", ",", "ID", ",", "pos", "=", "position", ",", "size", "=", "size", ",", "style", "=", "style", ")", "# create the RenderWindow and initialize it", "self", ".", "_RenderWindow", "=", "vtkRenderWindow", "(", ")", "self", ".", "_RenderWindow", ".", "SetSize", "(", "size", ".", "width", ",", "size", ".", "height", ")", "if", "stereo", ":", "self", ".", "_RenderWindow", ".", "StereoCapableWindowOn", "(", ")", "self", ".", "_RenderWindow", ".", "SetStereoTypeToCrystalEyes", "(", ")", "self", ".", "__handle", "=", "None", "# refresh window by doing a Render", "self", ".", "Bind", "(", "wx", ".", "EVT_PAINT", ",", "self", ".", "OnPaint", ")", "# turn off background erase to reduce flicker", "self", ".", "Bind", "(", "wx", ".", "EVT_ERASE_BACKGROUND", ",", "lambda", "e", ":", "None", ")", "# Bind the events to the event converters", "self", ".", "Bind", "(", "wx", ".", "EVT_RIGHT_DOWN", ",", "self", ".", "_OnButtonDown", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_LEFT_DOWN", ",", "self", ".", "_OnButtonDown", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MIDDLE_DOWN", ",", "self", ".", "_OnButtonDown", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_RIGHT_UP", ",", "self", ".", "_OnButtonUp", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_LEFT_UP", ",", "self", ".", "_OnButtonUp", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MIDDLE_UP", ",", "self", ".", "_OnButtonUp", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MOTION", ",", "self", ".", "OnMotion", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_ENTER_WINDOW", ",", "self", ".", "_OnEnterWindow", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_LEAVE_WINDOW", ",", "self", ".", "_OnLeaveWindow", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_CHAR", ",", "self", ".", "OnChar", ")", "# If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions", "# of all characters are always returned. EVT_CHAR also performs", "# other necessary keyboard-dependent translations.", "self", ".", "Bind", "(", "wx", ".", "EVT_CHAR", ",", "self", ".", "OnKeyDown", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_KEY_UP", ",", "self", ".", "OnKeyUp", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_SIZE", ",", "self", ".", "_OnSize", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MOVE", ",", "self", ".", "OnMove", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_SET_FOCUS", ",", "self", ".", "OnSetFocus", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_KILL_FOCUS", ",", "self", ".", "OnKillFocus", ")" ]
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/wx/wxVTKRenderWindow.py#L109-L240
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetBundleResourceFolder
(self)
return os.path.join(self.GetBundleContentsFolderPath(), 'Resources')
Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.
Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.
[ "Returns", "the", "qualified", "path", "to", "the", "bundle", "s", "resource", "folder", ".", "E", ".", "g", ".", "Chromium", ".", "app", "/", "Contents", "/", "Resources", ".", "Only", "valid", "for", "bundles", "." ]
def GetBundleResourceFolder(self): """Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.""" assert self._IsBundle() if self.isIOS: return self.GetBundleContentsFolderPath() return os.path.join(self.GetBundleContentsFolderPath(), 'Resources')
[ "def", "GetBundleResourceFolder", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "if", "self", ".", "isIOS", ":", "return", "self", ".", "GetBundleContentsFolderPath", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetBundleContentsFolderPath", "(", ")", ",", "'Resources'", ")" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/xcode_emulation.py#L297-L303
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/upload.py
python
UploadPartTask._main
(self, client, fileobj, bucket, key, upload_id, part_number, extra_args)
return {'ETag': etag, 'PartNumber': part_number}
:param client: The client to use when calling PutObject :param fileobj: The file to upload. :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param part_number: The number representing the part of the multipart upload :param extra_args: A dictionary of any extra arguments that may be used in the upload. :rtype: dict :returns: A dictionary representing a part:: {'Etag': etag_value, 'PartNumber': part_number} This value can be appended to a list to be used to complete the multipart upload.
:param client: The client to use when calling PutObject :param fileobj: The file to upload. :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param part_number: The number representing the part of the multipart upload :param extra_args: A dictionary of any extra arguments that may be used in the upload.
[ ":", "param", "client", ":", "The", "client", "to", "use", "when", "calling", "PutObject", ":", "param", "fileobj", ":", "The", "file", "to", "upload", ".", ":", "param", "bucket", ":", "The", "name", "of", "the", "bucket", "to", "upload", "to", ":", "param", "key", ":", "The", "name", "of", "the", "key", "to", "upload", "to", ":", "param", "upload_id", ":", "The", "id", "of", "the", "upload", ":", "param", "part_number", ":", "The", "number", "representing", "the", "part", "of", "the", "multipart", "upload", ":", "param", "extra_args", ":", "A", "dictionary", "of", "any", "extra", "arguments", "that", "may", "be", "used", "in", "the", "upload", "." ]
def _main(self, client, fileobj, bucket, key, upload_id, part_number, extra_args): """ :param client: The client to use when calling PutObject :param fileobj: The file to upload. :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param part_number: The number representing the part of the multipart upload :param extra_args: A dictionary of any extra arguments that may be used in the upload. :rtype: dict :returns: A dictionary representing a part:: {'Etag': etag_value, 'PartNumber': part_number} This value can be appended to a list to be used to complete the multipart upload. """ with fileobj as body: response = client.upload_part( Bucket=bucket, Key=key, UploadId=upload_id, PartNumber=part_number, Body=body, **extra_args) etag = response['ETag'] return {'ETag': etag, 'PartNumber': part_number}
[ "def", "_main", "(", "self", ",", "client", ",", "fileobj", ",", "bucket", ",", "key", ",", "upload_id", ",", "part_number", ",", "extra_args", ")", ":", "with", "fileobj", "as", "body", ":", "response", "=", "client", ".", "upload_part", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "UploadId", "=", "upload_id", ",", "PartNumber", "=", "part_number", ",", "Body", "=", "body", ",", "*", "*", "extra_args", ")", "etag", "=", "response", "[", "'ETag'", "]", "return", "{", "'ETag'", ":", "etag", ",", "'PartNumber'", ":", "part_number", "}" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/upload.py#L697-L724
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlDoc.newDocPI
(self, name, content)
return __tmp
Creation of a processing instruction element.
Creation of a processing instruction element.
[ "Creation", "of", "a", "processing", "instruction", "element", "." ]
def newDocPI(self, name, content): """Creation of a processing instruction element. """ ret = libxml2mod.xmlNewDocPI(self._o, name, content) if ret is None:raise treeError('xmlNewDocPI() failed') __tmp = xmlNode(_obj=ret) return __tmp
[ "def", "newDocPI", "(", "self", ",", "name", ",", "content", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNewDocPI", "(", "self", ".", "_o", ",", "name", ",", "content", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewDocPI() failed'", ")", "__tmp", "=", "xmlNode", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L3572-L3577
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/rj_gameplay/gameplay_node.py
python
GameplayNode.create_partial_robots
(self, msg: msg.RobotStatus)
Creates the robot status which makes up part of the whole Robot class
Creates the robot status which makes up part of the whole Robot class
[ "Creates", "the", "robot", "status", "which", "makes", "up", "part", "of", "the", "whole", "Robot", "class" ]
def create_partial_robots(self, msg: msg.RobotStatus) -> None: """ Creates the robot status which makes up part of the whole Robot class """ if msg is not None: robot = conv.robotstatus_to_partial_robot(msg) index = robot.robot_id self.robot_statuses[index] = robot
[ "def", "create_partial_robots", "(", "self", ",", "msg", ":", "msg", ".", "RobotStatus", ")", "->", "None", ":", "if", "msg", "is", "not", "None", ":", "robot", "=", "conv", ".", "robotstatus_to_partial_robot", "(", "msg", ")", "index", "=", "robot", ".", "robot_id", "self", ".", "robot_statuses", "[", "index", "]", "=", "robot" ]
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/rj_gameplay/gameplay_node.py#L166-L173
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py
python
DataSet._matches_file
(self, image)
return os.path.join(self._matches_path(), '{}_matches.pkl.gz'.format(image))
File for matches for an image
File for matches for an image
[ "File", "for", "matches", "for", "an", "image" ]
def _matches_file(self, image): """File for matches for an image""" return os.path.join(self._matches_path(), '{}_matches.pkl.gz'.format(image))
[ "def", "_matches_file", "(", "self", ",", "image", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_matches_path", "(", ")", ",", "'{}_matches.pkl.gz'", ".", "format", "(", "image", ")", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py#L517-L519
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/sysconfig.py
python
get_platform
()
return "%s-%s-%s" % (osname, release, machine)
Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'.
Return a string that identifies the current platform.
[ "Return", "a", "string", "that", "identifies", "the", "current", "platform", "." ]
def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ import re if os.name == 'nt': # sniff sys.version for architecture. prefix = " bit (" i = sys.version.find(prefix) if i == -1: return sys.platform j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform # Set for cross builds explicitly if "_PYTHON_HOST_PLATFORM" in os.environ: return os.environ["_PYTHON_HOST_PLATFORM"] if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha, # Mac OS is M68k or PPC, etc. return sys.platform # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # We can't use "platform.architecture()[0]" because a # bootstrap problem. We use a dict to get an error # if some suspicious happens. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} machine += ".%s" % bitness[sys.maxint] # fall through to standard osname-release-machine representation elif osname[:4] == "irix": # could be "irix64"! return "%s-%s" % (osname, release) elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" rel_re = re.compile (r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": import _osx_support osname, release, machine = _osx_support.get_platform_osx( get_config_vars(), osname, release, machine) return "%s-%s-%s" % (osname, release, machine)
[ "def", "get_platform", "(", ")", ":", "import", "re", "if", "os", ".", "name", "==", "'nt'", ":", "# sniff sys.version for architecture.", "prefix", "=", "\" bit (\"", "i", "=", "sys", ".", "version", ".", "find", "(", "prefix", ")", "if", "i", "==", "-", "1", ":", "return", "sys", ".", "platform", "j", "=", "sys", ".", "version", ".", "find", "(", "\")\"", ",", "i", ")", "look", "=", "sys", ".", "version", "[", "i", "+", "len", "(", "prefix", ")", ":", "j", "]", ".", "lower", "(", ")", "if", "look", "==", "'amd64'", ":", "return", "'win-amd64'", "if", "look", "==", "'itanium'", ":", "return", "'win-ia64'", "return", "sys", ".", "platform", "# Set for cross builds explicitly", "if", "\"_PYTHON_HOST_PLATFORM\"", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "\"_PYTHON_HOST_PLATFORM\"", "]", "if", "os", ".", "name", "!=", "\"posix\"", "or", "not", "hasattr", "(", "os", ",", "'uname'", ")", ":", "# XXX what about the architecture? NT is Intel or Alpha,", "# Mac OS is M68k or PPC, etc.", "return", "sys", ".", "platform", "# Try to distinguish various flavours of Unix", "osname", ",", "host", ",", "release", ",", "version", ",", "machine", "=", "os", ".", "uname", "(", ")", "# Convert the OS name to lowercase, remove '/' characters", "# (to accommodate BSD/OS), and translate spaces (for \"Power Macintosh\")", "osname", "=", "osname", ".", "lower", "(", ")", ".", "replace", "(", "'/'", ",", "''", ")", "machine", "=", "machine", ".", "replace", "(", "' '", ",", "'_'", ")", "machine", "=", "machine", ".", "replace", "(", "'/'", ",", "'-'", ")", "if", "osname", "[", ":", "5", "]", "==", "\"linux\"", ":", "# At least on Linux/Intel, 'machine' is the processor --", "# i386, etc.", "# XXX what about Alpha, SPARC, etc?", "return", "\"%s-%s\"", "%", "(", "osname", ",", "machine", ")", "elif", "osname", "[", ":", "5", "]", "==", "\"sunos\"", ":", "if", "release", "[", "0", "]", ">=", "\"5\"", ":", "# SunOS 5 == Solaris 2", "osname", "=", "\"solaris\"", "release", "=", "\"%d.%s\"", "%", "(", "int", "(", "release", "[", "0", "]", ")", "-", "3", ",", "release", "[", "2", ":", "]", ")", "# We can't use \"platform.architecture()[0]\" because a", "# bootstrap problem. We use a dict to get an error", "# if some suspicious happens.", "bitness", "=", "{", "2147483647", ":", "\"32bit\"", ",", "9223372036854775807", ":", "\"64bit\"", "}", "machine", "+=", "\".%s\"", "%", "bitness", "[", "sys", ".", "maxint", "]", "# fall through to standard osname-release-machine representation", "elif", "osname", "[", ":", "4", "]", "==", "\"irix\"", ":", "# could be \"irix64\"!", "return", "\"%s-%s\"", "%", "(", "osname", ",", "release", ")", "elif", "osname", "[", ":", "3", "]", "==", "\"aix\"", ":", "return", "\"%s-%s.%s\"", "%", "(", "osname", ",", "version", ",", "release", ")", "elif", "osname", "[", ":", "6", "]", "==", "\"cygwin\"", ":", "osname", "=", "\"cygwin\"", "rel_re", "=", "re", ".", "compile", "(", "r'[\\d.]+'", ")", "m", "=", "rel_re", ".", "match", "(", "release", ")", "if", "m", ":", "release", "=", "m", ".", "group", "(", ")", "elif", "osname", "[", ":", "6", "]", "==", "\"darwin\"", ":", "import", "_osx_support", "osname", ",", "release", ",", "machine", "=", "_osx_support", ".", "get_platform_osx", "(", "get_config_vars", "(", ")", ",", "osname", ",", "release", ",", "machine", ")", "return", "\"%s-%s-%s\"", "%", "(", "osname", ",", "release", ",", "machine", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/sysconfig.py#L534-L623
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
libraries/SITL/examples/JSON/pybullet/walking_robot.py
python
quaternion_from_AP
(q)
return [q.q[1], -q.q[2], -q.q[3], q.q[0]]
convert ArduPilot quaternion to pybullet quaternion
convert ArduPilot quaternion to pybullet quaternion
[ "convert", "ArduPilot", "quaternion", "to", "pybullet", "quaternion" ]
def quaternion_from_AP(q): '''convert ArduPilot quaternion to pybullet quaternion''' return [q.q[1], -q.q[2], -q.q[3], q.q[0]]
[ "def", "quaternion_from_AP", "(", "q", ")", ":", "return", "[", "q", ".", "q", "[", "1", "]", ",", "-", "q", ".", "q", "[", "2", "]", ",", "-", "q", ".", "q", "[", "3", "]", ",", "q", ".", "q", "[", "0", "]", "]" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/SITL/examples/JSON/pybullet/walking_robot.py#L78-L80
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/monitors.py
python
CaptureVariable.values
(self)
return self._var_values
Returns the values captured so far. Returns: `dict` mapping `int` step numbers to that values of the variable at the respective step.
Returns the values captured so far.
[ "Returns", "the", "values", "captured", "so", "far", "." ]
def values(self): """Returns the values captured so far. Returns: `dict` mapping `int` step numbers to that values of the variable at the respective step. """ return self._var_values
[ "def", "values", "(", "self", ")", ":", "return", "self", ".", "_var_values" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/monitors.py#L812-L819
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBThreadPlan.QueueThreadPlanForRunToAddress
(self, address)
return _lldb.SBThreadPlan_QueueThreadPlanForRunToAddress(self, address)
QueueThreadPlanForRunToAddress(SBThreadPlan self, SBAddress address) -> SBThreadPlan
QueueThreadPlanForRunToAddress(SBThreadPlan self, SBAddress address) -> SBThreadPlan
[ "QueueThreadPlanForRunToAddress", "(", "SBThreadPlan", "self", "SBAddress", "address", ")", "-", ">", "SBThreadPlan" ]
def QueueThreadPlanForRunToAddress(self, address): """QueueThreadPlanForRunToAddress(SBThreadPlan self, SBAddress address) -> SBThreadPlan""" return _lldb.SBThreadPlan_QueueThreadPlanForRunToAddress(self, address)
[ "def", "QueueThreadPlanForRunToAddress", "(", "self", ",", "address", ")", ":", "return", "_lldb", ".", "SBThreadPlan_QueueThreadPlanForRunToAddress", "(", "self", ",", "address", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12203-L12205
yuxng/PoseCNN
9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04
lib/gt_data_layer/minibatch.py
python
_get_image_blob
(roidb, scale_ind)
return blob, blob_depth, blob_normal, im_scales
Builds an input blob from the images in the roidb at the specified scales.
Builds an input blob from the images in the roidb at the specified scales.
[ "Builds", "an", "input", "blob", "from", "the", "images", "in", "the", "roidb", "at", "the", "specified", "scales", "." ]
def _get_image_blob(roidb, scale_ind): """Builds an input blob from the images in the roidb at the specified scales. """ num_images = len(roidb) processed_ims = [] processed_ims_depth = [] processed_ims_normal = [] im_scales = [] for i in xrange(num_images): # depth raw im_depth_raw = pad_im(cv2.imread(roidb[i]['depth'], cv2.IMREAD_UNCHANGED), 16) # rgba rgba = pad_im(cv2.imread(roidb[i]['image'], cv2.IMREAD_UNCHANGED), 16) if rgba.shape[2] == 4: im = np.copy(rgba[:,:,:3]) alpha = rgba[:,:,3] I = np.where(alpha == 0) im[I[0], I[1], :] = 255 else: im = rgba # chromatic transform if cfg.EXP_DIR != 'lov': im = chromatic_transform(im) # mask the color image according to depth if cfg.EXP_DIR == 'rgbd_scene': I = np.where(im_depth_raw == 0) im[I[0], I[1], :] = 0 if roidb[i]['flipped']: im = im[:, ::-1, :] im_orig = im.astype(np.float32, copy=True) im_orig -= cfg.PIXEL_MEANS im_scale = cfg.TRAIN.SCALES_BASE[scale_ind] im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) im_scales.append(im_scale) processed_ims.append(im) # depth im_depth = im_depth_raw.astype(np.float32, copy=True) / float(im_depth_raw.max()) * 255 im_depth = np.tile(im_depth[:,:,np.newaxis], (1,1,3)) if roidb[i]['flipped']: im_depth = im_depth[:, ::-1] im_orig = im_depth.astype(np.float32, copy=True) im_orig -= cfg.PIXEL_MEANS im_depth = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) processed_ims_depth.append(im_depth) # meta data meta_data = scipy.io.loadmat(roidb[i]['meta_data']) K = meta_data['intrinsic_matrix'].astype(np.float32, copy=True) fx = K[0, 0] fy = K[1, 1] cx = K[0, 2] cy = K[1, 2] # normals depth = im_depth_raw.astype(np.float32, copy=True) / float(meta_data['factor_depth']) nmap = gpu_normals.gpu_normals(depth, fx, fy, cx, cy, 20.0, cfg.GPU_ID) im_normal = 127.5 * nmap + 127.5 im_normal = im_normal.astype(np.uint8) im_normal = im_normal[:, :, (2, 1, 0)] im_normal = cv2.bilateralFilter(im_normal, 9, 75, 75) if roidb[i]['flipped']: im_normal = im_normal[:, ::-1, :] im_orig = im_normal.astype(np.float32, copy=True) im_orig -= cfg.PIXEL_MEANS im_normal = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) processed_ims_normal.append(im_normal) # Create a blob to hold the input images blob = im_list_to_blob(processed_ims, 3) blob_depth = im_list_to_blob(processed_ims_depth, 3) blob_normal = im_list_to_blob(processed_ims_normal, 3) return blob, blob_depth, blob_normal, im_scales
[ "def", "_get_image_blob", "(", "roidb", ",", "scale_ind", ")", ":", "num_images", "=", "len", "(", "roidb", ")", "processed_ims", "=", "[", "]", "processed_ims_depth", "=", "[", "]", "processed_ims_normal", "=", "[", "]", "im_scales", "=", "[", "]", "for", "i", "in", "xrange", "(", "num_images", ")", ":", "# depth raw", "im_depth_raw", "=", "pad_im", "(", "cv2", ".", "imread", "(", "roidb", "[", "i", "]", "[", "'depth'", "]", ",", "cv2", ".", "IMREAD_UNCHANGED", ")", ",", "16", ")", "# rgba", "rgba", "=", "pad_im", "(", "cv2", ".", "imread", "(", "roidb", "[", "i", "]", "[", "'image'", "]", ",", "cv2", ".", "IMREAD_UNCHANGED", ")", ",", "16", ")", "if", "rgba", ".", "shape", "[", "2", "]", "==", "4", ":", "im", "=", "np", ".", "copy", "(", "rgba", "[", ":", ",", ":", ",", ":", "3", "]", ")", "alpha", "=", "rgba", "[", ":", ",", ":", ",", "3", "]", "I", "=", "np", ".", "where", "(", "alpha", "==", "0", ")", "im", "[", "I", "[", "0", "]", ",", "I", "[", "1", "]", ",", ":", "]", "=", "255", "else", ":", "im", "=", "rgba", "# chromatic transform", "if", "cfg", ".", "EXP_DIR", "!=", "'lov'", ":", "im", "=", "chromatic_transform", "(", "im", ")", "# mask the color image according to depth", "if", "cfg", ".", "EXP_DIR", "==", "'rgbd_scene'", ":", "I", "=", "np", ".", "where", "(", "im_depth_raw", "==", "0", ")", "im", "[", "I", "[", "0", "]", ",", "I", "[", "1", "]", ",", ":", "]", "=", "0", "if", "roidb", "[", "i", "]", "[", "'flipped'", "]", ":", "im", "=", "im", "[", ":", ",", ":", ":", "-", "1", ",", ":", "]", "im_orig", "=", "im", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "True", ")", "im_orig", "-=", "cfg", ".", "PIXEL_MEANS", "im_scale", "=", "cfg", ".", "TRAIN", ".", "SCALES_BASE", "[", "scale_ind", "]", "im", "=", "cv2", ".", "resize", "(", "im_orig", ",", "None", ",", "None", ",", "fx", "=", "im_scale", ",", "fy", "=", "im_scale", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ")", "im_scales", ".", "append", "(", "im_scale", ")", "processed_ims", ".", "append", "(", "im", ")", "# depth", "im_depth", "=", "im_depth_raw", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "True", ")", "/", "float", "(", "im_depth_raw", ".", "max", "(", ")", ")", "*", "255", "im_depth", "=", "np", ".", "tile", "(", "im_depth", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", ",", "(", "1", ",", "1", ",", "3", ")", ")", "if", "roidb", "[", "i", "]", "[", "'flipped'", "]", ":", "im_depth", "=", "im_depth", "[", ":", ",", ":", ":", "-", "1", "]", "im_orig", "=", "im_depth", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "True", ")", "im_orig", "-=", "cfg", ".", "PIXEL_MEANS", "im_depth", "=", "cv2", ".", "resize", "(", "im_orig", ",", "None", ",", "None", ",", "fx", "=", "im_scale", ",", "fy", "=", "im_scale", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ")", "processed_ims_depth", ".", "append", "(", "im_depth", ")", "# meta data", "meta_data", "=", "scipy", ".", "io", ".", "loadmat", "(", "roidb", "[", "i", "]", "[", "'meta_data'", "]", ")", "K", "=", "meta_data", "[", "'intrinsic_matrix'", "]", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "True", ")", "fx", "=", "K", "[", "0", ",", "0", "]", "fy", "=", "K", "[", "1", ",", "1", "]", "cx", "=", "K", "[", "0", ",", "2", "]", "cy", "=", "K", "[", "1", ",", "2", "]", "# normals", "depth", "=", "im_depth_raw", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "True", ")", "/", "float", "(", "meta_data", "[", "'factor_depth'", "]", ")", "nmap", "=", "gpu_normals", ".", "gpu_normals", "(", "depth", ",", "fx", ",", "fy", ",", "cx", ",", "cy", ",", "20.0", ",", "cfg", ".", "GPU_ID", ")", "im_normal", "=", "127.5", "*", "nmap", "+", "127.5", "im_normal", "=", "im_normal", ".", "astype", "(", "np", ".", "uint8", ")", "im_normal", "=", "im_normal", "[", ":", ",", ":", ",", "(", "2", ",", "1", ",", "0", ")", "]", "im_normal", "=", "cv2", ".", "bilateralFilter", "(", "im_normal", ",", "9", ",", "75", ",", "75", ")", "if", "roidb", "[", "i", "]", "[", "'flipped'", "]", ":", "im_normal", "=", "im_normal", "[", ":", ",", ":", ":", "-", "1", ",", ":", "]", "im_orig", "=", "im_normal", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "True", ")", "im_orig", "-=", "cfg", ".", "PIXEL_MEANS", "im_normal", "=", "cv2", ".", "resize", "(", "im_orig", ",", "None", ",", "None", ",", "fx", "=", "im_scale", ",", "fy", "=", "im_scale", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ")", "processed_ims_normal", ".", "append", "(", "im_normal", ")", "# Create a blob to hold the input images", "blob", "=", "im_list_to_blob", "(", "processed_ims", ",", "3", ")", "blob_depth", "=", "im_list_to_blob", "(", "processed_ims_depth", ",", "3", ")", "blob_normal", "=", "im_list_to_blob", "(", "processed_ims_normal", ",", "3", ")", "return", "blob", ",", "blob_depth", ",", "blob_normal", ",", "im_scales" ]
https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/gt_data_layer/minibatch.py#L65-L146
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/pyarrow/__init__.py
python
show_versions
()
Print various version information, to help with error reporting.
Print various version information, to help with error reporting.
[ "Print", "various", "version", "information", "to", "help", "with", "error", "reporting", "." ]
def show_versions(): """ Print various version information, to help with error reporting. """ def print_entry(label, value): print(f"{label: <26}: {value: <8}") print("pyarrow version info\n--------------------") print_entry("Package kind", cpp_build_info.package_kind if len(cpp_build_info.package_kind) > 0 else "not indicated") print_entry("Arrow C++ library version", cpp_build_info.version) print_entry("Arrow C++ compiler", f"{cpp_build_info.compiler_id} {cpp_build_info.compiler_version}") print_entry("Arrow C++ compiler flags", cpp_build_info.compiler_flags) print_entry("Arrow C++ git revision", cpp_build_info.git_id) print_entry("Arrow C++ git description", cpp_build_info.git_description) print_entry("Arrow C++ build type", cpp_build_info.build_type)
[ "def", "show_versions", "(", ")", ":", "def", "print_entry", "(", "label", ",", "value", ")", ":", "print", "(", "f\"{label: <26}: {value: <8}\"", ")", "print", "(", "\"pyarrow version info\\n--------------------\"", ")", "print_entry", "(", "\"Package kind\"", ",", "cpp_build_info", ".", "package_kind", "if", "len", "(", "cpp_build_info", ".", "package_kind", ")", ">", "0", "else", "\"not indicated\"", ")", "print_entry", "(", "\"Arrow C++ library version\"", ",", "cpp_build_info", ".", "version", ")", "print_entry", "(", "\"Arrow C++ compiler\"", ",", "f\"{cpp_build_info.compiler_id} {cpp_build_info.compiler_version}\"", ")", "print_entry", "(", "\"Arrow C++ compiler flags\"", ",", "cpp_build_info", ".", "compiler_flags", ")", "print_entry", "(", "\"Arrow C++ git revision\"", ",", "cpp_build_info", ".", "git_id", ")", "print_entry", "(", "\"Arrow C++ git description\"", ",", "cpp_build_info", ".", "git_description", ")", "print_entry", "(", "\"Arrow C++ build type\"", ",", "cpp_build_info", ".", "build_type", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/__init__.py#L76-L93
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/importers/CNTK/lib/cntk_layers.py
python
ElementTimesLayer.clone_cntk_layer
(self, feature)
return element_times(x, self.scale)
Returns a clone of the CNTK layer for per-layer forward prop validation
Returns a clone of the CNTK layer for per-layer forward prop validation
[ "Returns", "a", "clone", "of", "the", "CNTK", "layer", "for", "per", "-", "layer", "forward", "prop", "validation" ]
def clone_cntk_layer(self, feature): """Returns a clone of the CNTK layer for per-layer forward prop validation""" x = reshape(feature, (self.layer.ell_outputShape.channels,)) return element_times(x, self.scale)
[ "def", "clone_cntk_layer", "(", "self", ",", "feature", ")", ":", "x", "=", "reshape", "(", "feature", ",", "(", "self", ".", "layer", ".", "ell_outputShape", ".", "channels", ",", ")", ")", "return", "element_times", "(", "x", ",", "self", ".", "scale", ")" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/CNTK/lib/cntk_layers.py#L533-L537
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/datastore_hooks.py
python
InstallHooks
()
Installs datastore pre hook to add access checks to queries. This only needs to be called once, when doing config (currently in appengine_config.py).
Installs datastore pre hook to add access checks to queries.
[ "Installs", "datastore", "pre", "hook", "to", "add", "access", "checks", "to", "queries", "." ]
def InstallHooks(): """Installs datastore pre hook to add access checks to queries. This only needs to be called once, when doing config (currently in appengine_config.py). """ apiproxy_stub_map.apiproxy.GetPreCallHooks().Push( '_DatastorePreHook', _DatastorePreHook, 'datastore_v3')
[ "def", "InstallHooks", "(", ")", ":", "apiproxy_stub_map", ".", "apiproxy", ".", "GetPreCallHooks", "(", ")", ".", "Push", "(", "'_DatastorePreHook'", ",", "_DatastorePreHook", ",", "'datastore_v3'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/datastore_hooks.py#L37-L44
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TextAttr.SetListStyleName
(*args, **kwargs)
return _controls_.TextAttr_SetListStyleName(*args, **kwargs)
SetListStyleName(self, String name)
SetListStyleName(self, String name)
[ "SetListStyleName", "(", "self", "String", "name", ")" ]
def SetListStyleName(*args, **kwargs): """SetListStyleName(self, String name)""" return _controls_.TextAttr_SetListStyleName(*args, **kwargs)
[ "def", "SetListStyleName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_SetListStyleName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L1583-L1585
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/scripts/cpp_lint.py
python
_NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/scripts/cpp_lint.py#L1940-L1946
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
clang/tools/scan-build-py/lib/libscanbuild/compilation.py
python
compiler_language
(command)
return None
A predicate to decide the command is a compiler call or not. Returns 'c' or 'c++' when it match. None otherwise.
A predicate to decide the command is a compiler call or not.
[ "A", "predicate", "to", "decide", "the", "command", "is", "a", "compiler", "call", "or", "not", "." ]
def compiler_language(command): """ A predicate to decide the command is a compiler call or not. Returns 'c' or 'c++' when it match. None otherwise. """ cplusplus = re.compile(r'^(.+)(\+\+)(-.+|)$') if command: executable = os.path.basename(command[0]) if any(pattern.match(executable) for pattern in COMPILER_PATTERNS): return 'c++' if cplusplus.match(executable) else 'c' return None
[ "def", "compiler_language", "(", "command", ")", ":", "cplusplus", "=", "re", ".", "compile", "(", "r'^(.+)(\\+\\+)(-.+|)$'", ")", "if", "command", ":", "executable", "=", "os", ".", "path", ".", "basename", "(", "command", "[", "0", "]", ")", "if", "any", "(", "pattern", ".", "match", "(", "executable", ")", "for", "pattern", "in", "COMPILER_PATTERNS", ")", ":", "return", "'c++'", "if", "cplusplus", ".", "match", "(", "executable", ")", "else", "'c'", "return", "None" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/tools/scan-build-py/lib/libscanbuild/compilation.py#L129-L140
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/config/win/get_msvc_config_real.py
python
_CreateVersion
(name, path, sdk_based=False)
return versions[str(name)]
Sets up MSVS project generation. Setup is based off the GYP_MSVS_VERSION environment variable or whatever is autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is passed in that doesn't match a value in versions python will throw a error.
Sets up MSVS project generation.
[ "Sets", "up", "MSVS", "project", "generation", "." ]
def _CreateVersion(name, path, sdk_based=False): """Sets up MSVS project generation. Setup is based off the GYP_MSVS_VERSION environment variable or whatever is autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is passed in that doesn't match a value in versions python will throw a error. """ if path: path = os.path.normpath(path) versions = { '2013': VisualStudioVersion('2013', 'Visual Studio 2013', solution_version='13.00', project_version='4.0', flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset='v110'), '2013e': VisualStudioVersion('2013e', 'Visual Studio 2013', solution_version='13.00', project_version='4.0', flat_sln=True, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset='v110'), '2012': VisualStudioVersion('2012', 'Visual Studio 2012', solution_version='12.00', project_version='4.0', flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset='v110'), '2012e': VisualStudioVersion('2012e', 'Visual Studio 2012', solution_version='12.00', project_version='4.0', flat_sln=True, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset='v110'), '2010': VisualStudioVersion('2010', 'Visual Studio 2010', solution_version='11.00', project_version='4.0', flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based), '2010e': VisualStudioVersion('2010e', 'Visual Studio 2010', solution_version='11.00', project_version='4.0', flat_sln=True, uses_vcxproj=True, path=path, sdk_based=sdk_based), '2008': VisualStudioVersion('2008', 'Visual Studio 2008', solution_version='10.00', project_version='9.00', flat_sln=False, uses_vcxproj=False, path=path, sdk_based=sdk_based), '2008e': VisualStudioVersion('2008e', 'Visual Studio 2008', solution_version='10.00', project_version='9.00', flat_sln=True, uses_vcxproj=False, path=path, sdk_based=sdk_based), '2005': VisualStudioVersion('2005', 'Visual Studio 2005', solution_version='9.00', project_version='8.00', flat_sln=False, uses_vcxproj=False, path=path, sdk_based=sdk_based), '2005e': VisualStudioVersion('2005e', 'Visual Studio 2005', solution_version='9.00', project_version='8.00', flat_sln=True, uses_vcxproj=False, path=path, sdk_based=sdk_based), } return versions[str(name)]
[ "def", "_CreateVersion", "(", "name", ",", "path", ",", "sdk_based", "=", "False", ")", ":", "if", "path", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "versions", "=", "{", "'2013'", ":", "VisualStudioVersion", "(", "'2013'", ",", "'Visual Studio 2013'", ",", "solution_version", "=", "'13.00'", ",", "project_version", "=", "'4.0'", ",", "flat_sln", "=", "False", ",", "uses_vcxproj", "=", "True", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ",", "default_toolset", "=", "'v110'", ")", ",", "'2013e'", ":", "VisualStudioVersion", "(", "'2013e'", ",", "'Visual Studio 2013'", ",", "solution_version", "=", "'13.00'", ",", "project_version", "=", "'4.0'", ",", "flat_sln", "=", "True", ",", "uses_vcxproj", "=", "True", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ",", "default_toolset", "=", "'v110'", ")", ",", "'2012'", ":", "VisualStudioVersion", "(", "'2012'", ",", "'Visual Studio 2012'", ",", "solution_version", "=", "'12.00'", ",", "project_version", "=", "'4.0'", ",", "flat_sln", "=", "False", ",", "uses_vcxproj", "=", "True", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ",", "default_toolset", "=", "'v110'", ")", ",", "'2012e'", ":", "VisualStudioVersion", "(", "'2012e'", ",", "'Visual Studio 2012'", ",", "solution_version", "=", "'12.00'", ",", "project_version", "=", "'4.0'", ",", "flat_sln", "=", "True", ",", "uses_vcxproj", "=", "True", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ",", "default_toolset", "=", "'v110'", ")", ",", "'2010'", ":", "VisualStudioVersion", "(", "'2010'", ",", "'Visual Studio 2010'", ",", "solution_version", "=", "'11.00'", ",", "project_version", "=", "'4.0'", ",", "flat_sln", "=", "False", ",", "uses_vcxproj", "=", "True", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ")", ",", "'2010e'", ":", "VisualStudioVersion", "(", "'2010e'", ",", "'Visual Studio 2010'", ",", "solution_version", "=", "'11.00'", ",", "project_version", "=", "'4.0'", ",", "flat_sln", "=", "True", ",", "uses_vcxproj", "=", "True", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ")", ",", "'2008'", ":", "VisualStudioVersion", "(", "'2008'", ",", "'Visual Studio 2008'", ",", "solution_version", "=", "'10.00'", ",", "project_version", "=", "'9.00'", ",", "flat_sln", "=", "False", ",", "uses_vcxproj", "=", "False", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ")", ",", "'2008e'", ":", "VisualStudioVersion", "(", "'2008e'", ",", "'Visual Studio 2008'", ",", "solution_version", "=", "'10.00'", ",", "project_version", "=", "'9.00'", ",", "flat_sln", "=", "True", ",", "uses_vcxproj", "=", "False", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ")", ",", "'2005'", ":", "VisualStudioVersion", "(", "'2005'", ",", "'Visual Studio 2005'", ",", "solution_version", "=", "'9.00'", ",", "project_version", "=", "'8.00'", ",", "flat_sln", "=", "False", ",", "uses_vcxproj", "=", "False", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ")", ",", "'2005e'", ":", "VisualStudioVersion", "(", "'2005e'", ",", "'Visual Studio 2005'", ",", "solution_version", "=", "'9.00'", ",", "project_version", "=", "'8.00'", ",", "flat_sln", "=", "True", ",", "uses_vcxproj", "=", "False", ",", "path", "=", "path", ",", "sdk_based", "=", "sdk_based", ")", ",", "}", "return", "versions", "[", "str", "(", "name", ")", "]" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/config/win/get_msvc_config_real.py#L192-L287
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/timeline.py
python
_TensorTracker.create_time
(self)
return self._create_time
Timestamp when this tensor was created (long integer).
Timestamp when this tensor was created (long integer).
[ "Timestamp", "when", "this", "tensor", "was", "created", "(", "long", "integer", ")", "." ]
def create_time(self): """Timestamp when this tensor was created (long integer).""" return self._create_time
[ "def", "create_time", "(", "self", ")", ":", "return", "self", ".", "_create_time" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/timeline.py#L305-L307
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
Geometry3D.setTriangleMesh
(self, arg2)
return _robotsim.Geometry3D_setTriangleMesh(self, arg2)
setTriangleMesh(Geometry3D self, TriangleMesh arg2) Sets this Geometry3D to a TriangleMesh.
setTriangleMesh(Geometry3D self, TriangleMesh arg2)
[ "setTriangleMesh", "(", "Geometry3D", "self", "TriangleMesh", "arg2", ")" ]
def setTriangleMesh(self, arg2): """ setTriangleMesh(Geometry3D self, TriangleMesh arg2) Sets this Geometry3D to a TriangleMesh. """ return _robotsim.Geometry3D_setTriangleMesh(self, arg2)
[ "def", "setTriangleMesh", "(", "self", ",", "arg2", ")", ":", "return", "_robotsim", ".", "Geometry3D_setTriangleMesh", "(", "self", ",", "arg2", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L2021-L2030
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
PrintPreview.GetPrintout
(*args, **kwargs)
return _windows_.PrintPreview_GetPrintout(*args, **kwargs)
GetPrintout(self) -> Printout
GetPrintout(self) -> Printout
[ "GetPrintout", "(", "self", ")", "-", ">", "Printout" ]
def GetPrintout(*args, **kwargs): """GetPrintout(self) -> Printout""" return _windows_.PrintPreview_GetPrintout(*args, **kwargs)
[ "def", "GetPrintout", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintPreview_GetPrintout", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L5577-L5579
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py
python
_BaseV6._reverse_pointer
(self)
return '.'.join(reverse_chars) + '.ip6.arpa'
Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5.
Return the reverse DNS pointer name for the IPv6 address.
[ "Return", "the", "reverse", "DNS", "pointer", "name", "for", "the", "IPv6", "address", "." ]
def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa'
[ "def", "_reverse_pointer", "(", "self", ")", ":", "reverse_chars", "=", "self", ".", "exploded", "[", ":", ":", "-", "1", "]", ".", "replace", "(", "':'", ",", "''", ")", "return", "'.'", ".", "join", "(", "reverse_chars", ")", "+", "'.ip6.arpa'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py#L1853-L1860
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/llvm/examples/Kaleidoscope/MCJIT/complete/split-lib.py
python
TimingScriptGenerator.writeTimingCall
(self, irname, callname)
Echo some comments and invoke both versions of toy
Echo some comments and invoke both versions of toy
[ "Echo", "some", "comments", "and", "invoke", "both", "versions", "of", "toy" ]
def writeTimingCall(self, irname, callname): """Echo some comments and invoke both versions of toy""" rootname = irname if '.' in irname: rootname = irname[:irname.rfind('.')] self.shfile.write("echo \"%s: Calls %s\" >> %s\n" % (callname, irname, self.timeFile)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT again\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=false -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
[ "def", "writeTimingCall", "(", "self", ",", "irname", ",", "callname", ")", ":", "rootname", "=", "irname", "if", "'.'", "in", "irname", ":", "rootname", "=", "irname", "[", ":", "irname", ".", "rfind", "(", "'.'", ")", "]", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"%s: Calls %s\\\" >> %s\\n\"", "%", "(", "callname", ",", "irname", ",", "self", ".", "timeFile", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With MCJIT\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"", "%", "(", "irname", ",", "callname", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With MCJIT again\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"", "%", "(", "irname", ",", "callname", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With JIT\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=false -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"", "%", "(", "irname", ",", "callname", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/llvm/examples/Kaleidoscope/MCJIT/complete/split-lib.py#L10-L32
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
validateName
(value, space)
return ret
Check that a value conforms to the lexical space of Name
Check that a value conforms to the lexical space of Name
[ "Check", "that", "a", "value", "conforms", "to", "the", "lexical", "space", "of", "Name" ]
def validateName(value, space): """Check that a value conforms to the lexical space of Name """ ret = libxml2mod.xmlValidateName(value, space) return ret
[ "def", "validateName", "(", "value", ",", "space", ")", ":", "ret", "=", "libxml2mod", ".", "xmlValidateName", "(", "value", ",", "space", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L938-L941
15172658790/Blog
46e5036f5fbcad535af2255dc0e095cebcd8d710
计算机与信息类/数据结构/students/mbinary/trie.py
python
Trie.search
(self, word,matchAll='.')
return self._search(self.root,word)
support matchall function eg, 'p.d' matchs 'pad' , 'pid'
support matchall function eg, 'p.d' matchs 'pad' , 'pid'
[ "support", "matchall", "function", "eg", "p", ".", "d", "matchs", "pad", "pid" ]
def search(self, word,matchAll='.'): """support matchall function eg, 'p.d' matchs 'pad' , 'pid' """ self.matchAll = '.' return self._search(self.root,word)
[ "def", "search", "(", "self", ",", "word", ",", "matchAll", "=", "'.'", ")", ":", "self", ".", "matchAll", "=", "'.'", "return", "self", ".", "_search", "(", "self", ".", "root", ",", "word", ")" ]
https://github.com/15172658790/Blog/blob/46e5036f5fbcad535af2255dc0e095cebcd8d710/计算机与信息类/数据结构/students/mbinary/trie.py#L53-L57
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/xapian/xapian-maintainer-tools/buildbot/xapian_factories.py
python
gen_git_updated_factory
(repourl, usedocs=True, clean=False, configure_opts=None)
return core_factory(repourl=repourl, usedocs=usedocs, clean=clean, configure_opts=configure_opts)
Make a factory for doing build from git master, but without cleaning first. This build is intended to catch commonly made mistakes quickly.
Make a factory for doing build from git master, but without cleaning first. This build is intended to catch commonly made mistakes quickly.
[ "Make", "a", "factory", "for", "doing", "build", "from", "git", "master", "but", "without", "cleaning", "first", ".", "This", "build", "is", "intended", "to", "catch", "commonly", "made", "mistakes", "quickly", "." ]
def gen_git_updated_factory(repourl, usedocs=True, clean=False, configure_opts=None): """ Make a factory for doing build from git master, but without cleaning first. This build is intended to catch commonly made mistakes quickly. """ return core_factory(repourl=repourl, usedocs=usedocs, clean=clean, configure_opts=configure_opts)
[ "def", "gen_git_updated_factory", "(", "repourl", ",", "usedocs", "=", "True", ",", "clean", "=", "False", ",", "configure_opts", "=", "None", ")", ":", "return", "core_factory", "(", "repourl", "=", "repourl", ",", "usedocs", "=", "usedocs", ",", "clean", "=", "clean", ",", "configure_opts", "=", "configure_opts", ")" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/xapian/xapian-maintainer-tools/buildbot/xapian_factories.py#L84-L89
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_solver.py
python
substitute
(t, *m)
return z3_to_expr_ref(z3.Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to.
Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to.
[ "Apply", "substitution", "m", "on", "t", "m", "is", "a", "list", "of", "pairs", "of", "the", "form", "(", "from", "to", ")", ".", "Every", "occurrence", "in", "t", "of", "from", "is", "replaced", "with", "to", "." ]
def substitute(t, *m): """Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to. """ num = len(m) _from = (z3.Ast * num)() _to = (z3.Ast * num)() for i in range(num): _from[i] = m[i][0].as_ast() _to[i] = m[i][1].as_ast() return z3_to_expr_ref(z3.Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
[ "def", "substitute", "(", "t", ",", "*", "m", ")", ":", "num", "=", "len", "(", "m", ")", "_from", "=", "(", "z3", ".", "Ast", "*", "num", ")", "(", ")", "_to", "=", "(", "z3", ".", "Ast", "*", "num", ")", "(", ")", "for", "i", "in", "range", "(", "num", ")", ":", "_from", "[", "i", "]", "=", "m", "[", "i", "]", "[", "0", "]", ".", "as_ast", "(", ")", "_to", "[", "i", "]", "=", "m", "[", "i", "]", "[", "1", "]", ".", "as_ast", "(", ")", "return", "z3_to_expr_ref", "(", "z3", ".", "Z3_substitute", "(", "t", ".", "ctx", ".", "ref", "(", ")", ",", "t", ".", "as_ast", "(", ")", ",", "num", ",", "_from", ",", "_to", ")", ",", "t", ".", "ctx", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_solver.py#L1495-L1503
ukoethe/vigra
093d57d15c8c237adf1704d96daa6393158ce299
vigranumpy/lib/arraytypes.py
python
VigraArray.transposeToOrder
(self, order)
return self.transpose(permutation)
Get a transposed view onto this array according to the given 'order'. Possible orders are: 'A' or '' or None: return the array unchanged 'C': transpose to descending axis order (e.g. 'z y x c') 'F': transpose to ascending axis order (e.g. 'c x y z') 'V': transpose to VIGRA order, i.e. ascending spatial axes, but the channel axis is last (e.g. 'x y z c')
Get a transposed view onto this array according to the given 'order'. Possible orders are:
[ "Get", "a", "transposed", "view", "onto", "this", "array", "according", "to", "the", "given", "order", ".", "Possible", "orders", "are", ":" ]
def transposeToOrder(self, order): ''' Get a transposed view onto this array according to the given 'order'. Possible orders are: 'A' or '' or None: return the array unchanged 'C': transpose to descending axis order (e.g. 'z y x c') 'F': transpose to ascending axis order (e.g. 'c x y z') 'V': transpose to VIGRA order, i.e. ascending spatial axes, but the channel axis is last (e.g. 'x y z c') ''' if not order or order == 'A': return self permutation = self.permutationToOrder(order) return self.transpose(permutation)
[ "def", "transposeToOrder", "(", "self", ",", "order", ")", ":", "if", "not", "order", "or", "order", "==", "'A'", ":", "return", "self", "permutation", "=", "self", ".", "permutationToOrder", "(", "order", ")", "return", "self", ".", "transpose", "(", "permutation", ")" ]
https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/arraytypes.py#L1200-L1218
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/program_members/subroutine.py
python
Subroutine.index
(self)
return self._index
int: The index of the subroutine.
int: The index of the subroutine.
[ "int", ":", "The", "index", "of", "the", "subroutine", "." ]
def index(self) -> int: ''' int: The index of the subroutine. ''' return self._index
[ "def", "index", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_index" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/program_members/subroutine.py#L24-L29
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/run_perf.py
python
FlattenRunnables
(node, node_cb)
Generator that traverses the tree structure and iterates over all runnables.
Generator that traverses the tree structure and iterates over all runnables.
[ "Generator", "that", "traverses", "the", "tree", "structure", "and", "iterates", "over", "all", "runnables", "." ]
def FlattenRunnables(node, node_cb): """Generator that traverses the tree structure and iterates over all runnables. """ node_cb(node) if isinstance(node, RunnableConfig): yield node elif isinstance(node, Node): for child in node._children: for result in FlattenRunnables(child, node_cb): yield result else: # pragma: no cover raise Exception("Invalid suite configuration.")
[ "def", "FlattenRunnables", "(", "node", ",", "node_cb", ")", ":", "node_cb", "(", "node", ")", "if", "isinstance", "(", "node", ",", "RunnableConfig", ")", ":", "yield", "node", "elif", "isinstance", "(", "node", ",", "Node", ")", ":", "for", "child", "in", "node", ".", "_children", ":", "for", "result", "in", "FlattenRunnables", "(", "child", ",", "node_cb", ")", ":", "yield", "result", "else", ":", "# pragma: no cover", "raise", "Exception", "(", "\"Invalid suite configuration.\"", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/run_perf.py#L562-L574
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
CursorKind.is_preprocessing
(self)
return conf.lib.clang_isPreprocessing(self)
Test if this is a preprocessing kind.
Test if this is a preprocessing kind.
[ "Test", "if", "this", "is", "a", "preprocessing", "kind", "." ]
def is_preprocessing(self): """Test if this is a preprocessing kind.""" return conf.lib.clang_isPreprocessing(self)
[ "def", "is_preprocessing", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isPreprocessing", "(", "self", ")" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L547-L549
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/esptool/serial/urlhandler/protocol_alt.py
python
serial_class_for_url
(url)
return (''.join([parts.netloc, parts.path]), cls)
extract host and port from an URL string
extract host and port from an URL string
[ "extract", "host", "and", "port", "from", "an", "URL", "string" ]
def serial_class_for_url(url): """extract host and port from an URL string""" parts = urlparse.urlsplit(url) if parts.scheme != 'alt': raise serial.SerialException( 'expected a string in the form "alt://port[?option[=value][&option[=value]]]": ' 'not starting with alt:// ({!r})'.format(parts.scheme)) class_name = 'Serial' try: for option, values in urlparse.parse_qs(parts.query, True).items(): if option == 'class': class_name = values[0] else: raise ValueError('unknown option: {!r}'.format(option)) except ValueError as e: raise serial.SerialException( 'expected a string in the form ' '"alt://port[?option[=value][&option[=value]]]": {!r}'.format(e)) if not hasattr(serial, class_name): raise ValueError('unknown class: {!r}'.format(class_name)) cls = getattr(serial, class_name) if not issubclass(cls, serial.Serial): raise ValueError('class {!r} is not an instance of Serial'.format(class_name)) return (''.join([parts.netloc, parts.path]), cls)
[ "def", "serial_class_for_url", "(", "url", ")", ":", "parts", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "if", "parts", ".", "scheme", "!=", "'alt'", ":", "raise", "serial", ".", "SerialException", "(", "'expected a string in the form \"alt://port[?option[=value][&option[=value]]]\": '", "'not starting with alt:// ({!r})'", ".", "format", "(", "parts", ".", "scheme", ")", ")", "class_name", "=", "'Serial'", "try", ":", "for", "option", ",", "values", "in", "urlparse", ".", "parse_qs", "(", "parts", ".", "query", ",", "True", ")", ".", "items", "(", ")", ":", "if", "option", "==", "'class'", ":", "class_name", "=", "values", "[", "0", "]", "else", ":", "raise", "ValueError", "(", "'unknown option: {!r}'", ".", "format", "(", "option", ")", ")", "except", "ValueError", "as", "e", ":", "raise", "serial", ".", "SerialException", "(", "'expected a string in the form '", "'\"alt://port[?option[=value][&option[=value]]]\": {!r}'", ".", "format", "(", "e", ")", ")", "if", "not", "hasattr", "(", "serial", ",", "class_name", ")", ":", "raise", "ValueError", "(", "'unknown class: {!r}'", ".", "format", "(", "class_name", ")", ")", "cls", "=", "getattr", "(", "serial", ",", "class_name", ")", "if", "not", "issubclass", "(", "cls", ",", "serial", ".", "Serial", ")", ":", "raise", "ValueError", "(", "'class {!r} is not an instance of Serial'", ".", "format", "(", "class_name", ")", ")", "return", "(", "''", ".", "join", "(", "[", "parts", ".", "netloc", ",", "parts", ".", "path", "]", ")", ",", "cls", ")" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/urlhandler/protocol_alt.py#L27-L50
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/GYBUnicodeDataUtils.py
python
UnicodeTrieGenerator.create_tables
(self)
Compute derived parameter values and create internal data structures. Don't change parameter values after calling this method.
Compute derived parameter values and create internal data structures.
[ "Compute", "derived", "parameter", "values", "and", "create", "internal", "data", "structures", "." ]
def create_tables(self): """Compute derived parameter values and create internal data structures. Don't change parameter values after calling this method. """ self.bmp_data_offset_bits = 16 - self.bmp_first_level_index_bits self.supp_data_offset_bits = \ 21 - self.supp_first_level_index_bits - \ self.supp_second_level_index_bits # The maximum value of the first level index for supp tables. It is # not equal to ((1 << supp_first_level_index_bits) - 1), because # maximum Unicode code point value is not 2^21-1 (0x1fffff), it is # 0x10ffff. self.supp_first_level_index_max = \ 0x10ffff >> \ (self.supp_second_level_index_bits + self.supp_data_offset_bits) # A mapping from BMP first-level index to BMP data block index. self.bmp_lookup = \ [i for i in range(0, 1 << self.bmp_first_level_index_bits)] # An array of BMP data blocks. self.bmp_data = [ [-1 for i in range(0, 1 << self.bmp_data_offset_bits)] for i in range(0, 1 << self.bmp_first_level_index_bits) ] # A mapping from supp first-level index to an index of the second-level # lookup table. self.supp_lookup1 = \ [i for i in range(0, self.supp_first_level_index_max + 1)] # An array of second-level lookup tables. Each second-level lookup # table is a mapping from a supp second-level index to supp data block # index. self.supp_lookup2 = [ [j for j in range(i << self.supp_second_level_index_bits, (i + 1) << self.supp_second_level_index_bits)] for i in range(0, self.supp_first_level_index_max + 1) ] # An array of supp data blocks. self.supp_data = [ [-1 for i in range(0, 1 << self.supp_data_offset_bits)] for i in range(0, (self.supp_first_level_index_max + 1) * (1 << self.supp_second_level_index_bits)) ]
[ "def", "create_tables", "(", "self", ")", ":", "self", ".", "bmp_data_offset_bits", "=", "16", "-", "self", ".", "bmp_first_level_index_bits", "self", ".", "supp_data_offset_bits", "=", "21", "-", "self", ".", "supp_first_level_index_bits", "-", "self", ".", "supp_second_level_index_bits", "# The maximum value of the first level index for supp tables. It is", "# not equal to ((1 << supp_first_level_index_bits) - 1), because", "# maximum Unicode code point value is not 2^21-1 (0x1fffff), it is", "# 0x10ffff.", "self", ".", "supp_first_level_index_max", "=", "0x10ffff", ">>", "(", "self", ".", "supp_second_level_index_bits", "+", "self", ".", "supp_data_offset_bits", ")", "# A mapping from BMP first-level index to BMP data block index.", "self", ".", "bmp_lookup", "=", "[", "i", "for", "i", "in", "range", "(", "0", ",", "1", "<<", "self", ".", "bmp_first_level_index_bits", ")", "]", "# An array of BMP data blocks.", "self", ".", "bmp_data", "=", "[", "[", "-", "1", "for", "i", "in", "range", "(", "0", ",", "1", "<<", "self", ".", "bmp_data_offset_bits", ")", "]", "for", "i", "in", "range", "(", "0", ",", "1", "<<", "self", ".", "bmp_first_level_index_bits", ")", "]", "# A mapping from supp first-level index to an index of the second-level", "# lookup table.", "self", ".", "supp_lookup1", "=", "[", "i", "for", "i", "in", "range", "(", "0", ",", "self", ".", "supp_first_level_index_max", "+", "1", ")", "]", "# An array of second-level lookup tables. Each second-level lookup", "# table is a mapping from a supp second-level index to supp data block", "# index.", "self", ".", "supp_lookup2", "=", "[", "[", "j", "for", "j", "in", "range", "(", "i", "<<", "self", ".", "supp_second_level_index_bits", ",", "(", "i", "+", "1", ")", "<<", "self", ".", "supp_second_level_index_bits", ")", "]", "for", "i", "in", "range", "(", "0", ",", "self", ".", "supp_first_level_index_max", "+", "1", ")", "]", "# An array of supp data blocks.", "self", ".", "supp_data", "=", "[", "[", "-", "1", "for", "i", "in", "range", "(", "0", ",", "1", "<<", "self", ".", "supp_data_offset_bits", ")", "]", "for", "i", "in", "range", "(", "0", ",", "(", "self", ".", "supp_first_level_index_max", "+", "1", ")", "*", "(", "1", "<<", "self", ".", "supp_second_level_index_bits", ")", ")", "]" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/GYBUnicodeDataUtils.py#L245-L294
stitchEm/stitchEm
0f399501d41ab77933677f2907f41f80ceb704d7
lib/bindings/samples/server/glfw.py
python
set_gamma_ramp
(monitor, ramp)
Sets the current gamma ramp for the specified monitor. Wrapper for: void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp);
Sets the current gamma ramp for the specified monitor.
[ "Sets", "the", "current", "gamma", "ramp", "for", "the", "specified", "monitor", "." ]
def set_gamma_ramp(monitor, ramp): """ Sets the current gamma ramp for the specified monitor. Wrapper for: void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); """ gammaramp = _GLFWgammaramp() gammaramp.wrap(ramp) _glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp))
[ "def", "set_gamma_ramp", "(", "monitor", ",", "ramp", ")", ":", "gammaramp", "=", "_GLFWgammaramp", "(", ")", "gammaramp", ".", "wrap", "(", "ramp", ")", "_glfw", ".", "glfwSetGammaRamp", "(", "monitor", ",", "ctypes", ".", "pointer", "(", "gammaramp", ")", ")" ]
https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/glfw.py#L928-L937
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
FileDirPickerEvent.GetPath
(*args, **kwargs)
return _controls_.FileDirPickerEvent_GetPath(*args, **kwargs)
GetPath(self) -> String
GetPath(self) -> String
[ "GetPath", "(", "self", ")", "-", ">", "String" ]
def GetPath(*args, **kwargs): """GetPath(self) -> String""" return _controls_.FileDirPickerEvent_GetPath(*args, **kwargs)
[ "def", "GetPath", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "FileDirPickerEvent_GetPath", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L7128-L7130
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/samplelogs/presenter.py
python
SampleLogs.plot_clicked
(self, event)
Check if figure is doubleClicked, then create new plot
Check if figure is doubleClicked, then create new plot
[ "Check", "if", "figure", "is", "doubleClicked", "then", "create", "new", "plot" ]
def plot_clicked(self, event): """Check if figure is doubleClicked, then create new plot""" if event.dblclick: self.new_plot_logs()
[ "def", "plot_clicked", "(", "self", ",", "event", ")", ":", "if", "event", ".", "dblclick", ":", "self", ".", "new_plot_logs", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/samplelogs/presenter.py#L63-L66
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
TerrainModel.getName
(self)
return _robotsim.TerrainModel_getName(self)
r"""
r"""
[ "r" ]
def getName(self) ->str: r""" """ return _robotsim.TerrainModel_getName(self)
[ "def", "getName", "(", "self", ")", "->", "str", ":", "return", "_robotsim", ".", "TerrainModel_getName", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L5528-L5531
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/inspect.py
python
findsource
(object)
Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.
Return the entire source file and starting line number for an object.
[ "Return", "the", "entire", "source", "file", "and", "starting", "line", "number", "for", "an", "object", "." ]
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getfile(object) sourcefile = getsourcefile(object) if not sourcefile and file[:1] + file[-1:] != '<>': raise IOError('source code not available') file = sourcefile if sourcefile else file module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^(\s*)class\s*' + name + r'\b') # make some effort to find the best matching class definition: # use the one with the least indentation, which is the one # that's most probably not inside a function definition. candidates = [] for i in range(len(lines)): match = pat.match(lines[i]) if match: # if it's at toplevel, it's already the best one if lines[i][0] == 'c': return lines, i # else add whitespace to candidate list candidates.append((match.group(1), i)) if candidates: # this will sort by whitespace, and by line number, # less whitespace first candidates.sort() return lines, candidates[0][1] else: raise IOError('could not find class definition') if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object')
[ "def", "findsource", "(", "object", ")", ":", "file", "=", "getfile", "(", "object", ")", "sourcefile", "=", "getsourcefile", "(", "object", ")", "if", "not", "sourcefile", "and", "file", "[", ":", "1", "]", "+", "file", "[", "-", "1", ":", "]", "!=", "'<>'", ":", "raise", "IOError", "(", "'source code not available'", ")", "file", "=", "sourcefile", "if", "sourcefile", "else", "file", "module", "=", "getmodule", "(", "object", ",", "file", ")", "if", "module", ":", "lines", "=", "linecache", ".", "getlines", "(", "file", ",", "module", ".", "__dict__", ")", "else", ":", "lines", "=", "linecache", ".", "getlines", "(", "file", ")", "if", "not", "lines", ":", "raise", "IOError", "(", "'could not get source code'", ")", "if", "ismodule", "(", "object", ")", ":", "return", "lines", ",", "0", "if", "isclass", "(", "object", ")", ":", "name", "=", "object", ".", "__name__", "pat", "=", "re", ".", "compile", "(", "r'^(\\s*)class\\s*'", "+", "name", "+", "r'\\b'", ")", "# make some effort to find the best matching class definition:", "# use the one with the least indentation, which is the one", "# that's most probably not inside a function definition.", "candidates", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "match", "=", "pat", ".", "match", "(", "lines", "[", "i", "]", ")", "if", "match", ":", "# if it's at toplevel, it's already the best one", "if", "lines", "[", "i", "]", "[", "0", "]", "==", "'c'", ":", "return", "lines", ",", "i", "# else add whitespace to candidate list", "candidates", ".", "append", "(", "(", "match", ".", "group", "(", "1", ")", ",", "i", ")", ")", "if", "candidates", ":", "# this will sort by whitespace, and by line number,", "# less whitespace first", "candidates", ".", "sort", "(", ")", "return", "lines", ",", "candidates", "[", "0", "]", "[", "1", "]", "else", ":", "raise", "IOError", "(", "'could not find class definition'", ")", "if", "ismethod", "(", "object", ")", ":", "object", "=", "object", ".", "im_func", "if", "isfunction", "(", "object", ")", ":", "object", "=", "object", ".", "func_code", "if", "istraceback", "(", "object", ")", ":", "object", "=", "object", ".", "tb_frame", "if", "isframe", "(", "object", ")", ":", "object", "=", "object", ".", "f_code", "if", "iscode", "(", "object", ")", ":", "if", "not", "hasattr", "(", "object", ",", "'co_firstlineno'", ")", ":", "raise", "IOError", "(", "'could not find function definition'", ")", "lnum", "=", "object", ".", "co_firstlineno", "-", "1", "pat", "=", "re", ".", "compile", "(", "r'^(\\s*def\\s)|(.*(?<!\\w)lambda(:|\\s))|^(\\s*@)'", ")", "while", "lnum", ">", "0", ":", "if", "pat", ".", "match", "(", "lines", "[", "lnum", "]", ")", ":", "break", "lnum", "=", "lnum", "-", "1", "return", "lines", ",", "lnum", "raise", "IOError", "(", "'could not find code object'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/inspect.py#L517-L582
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/generic.py
python
NDFrame._consolidate
(self)
return self._constructor(cons_data).__finalize__(self)
Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Returns ------- consolidated : same type as caller
Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray).
[ "Compute", "NDFrame", "with", "consolidated", "internals", "(", "data", "of", "each", "dtype", "grouped", "together", "in", "a", "single", "ndarray", ")", "." ]
def _consolidate(self): """ Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Returns ------- consolidated : same type as caller """ f = lambda: self._mgr.consolidate() cons_data = self._protect_consolidate(f) return self._constructor(cons_data).__finalize__(self)
[ "def", "_consolidate", "(", "self", ")", ":", "f", "=", "lambda", ":", "self", ".", "_mgr", ".", "consolidate", "(", ")", "cons_data", "=", "self", ".", "_protect_consolidate", "(", "f", ")", "return", "self", ".", "_constructor", "(", "cons_data", ")", ".", "__finalize__", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L5568-L5579
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/untyped_passes.py
python
fallback_context
(state, msg)
Wraps code that would signal a fallback to object mode
Wraps code that would signal a fallback to object mode
[ "Wraps", "code", "that", "would", "signal", "a", "fallback", "to", "object", "mode" ]
def fallback_context(state, msg): """ Wraps code that would signal a fallback to object mode """ try: yield except Exception as e: if not state.status.can_fallback: raise else: if utils.PYVERSION >= (3,): # Clear all references attached to the traceback e = e.with_traceback(None) # this emits a warning containing the error message body in the # case of fallback from npm to objmode loop_lift = '' if state.flags.enable_looplift else 'OUT' msg_rewrite = ("\nCompilation is falling back to object mode " "WITH%s looplifting enabled because %s" % (loop_lift, msg)) warnings.warn_explicit('%s due to: %s' % (msg_rewrite, e), errors.NumbaWarning, state.func_id.filename, state.func_id.firstlineno) raise
[ "def", "fallback_context", "(", "state", ",", "msg", ")", ":", "try", ":", "yield", "except", "Exception", "as", "e", ":", "if", "not", "state", ".", "status", ".", "can_fallback", ":", "raise", "else", ":", "if", "utils", ".", "PYVERSION", ">=", "(", "3", ",", ")", ":", "# Clear all references attached to the traceback", "e", "=", "e", ".", "with_traceback", "(", "None", ")", "# this emits a warning containing the error message body in the", "# case of fallback from npm to objmode", "loop_lift", "=", "''", "if", "state", ".", "flags", ".", "enable_looplift", "else", "'OUT'", "msg_rewrite", "=", "(", "\"\\nCompilation is falling back to object mode \"", "\"WITH%s looplifting enabled because %s\"", "%", "(", "loop_lift", ",", "msg", ")", ")", "warnings", ".", "warn_explicit", "(", "'%s due to: %s'", "%", "(", "msg_rewrite", ",", "e", ")", ",", "errors", ".", "NumbaWarning", ",", "state", ".", "func_id", ".", "filename", ",", "state", ".", "func_id", ".", "firstlineno", ")", "raise" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/untyped_passes.py#L29-L52
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowserplotinteraction.py
python
FitPropertyBrowserPlotInteraction.plot_guess_all
(self)
Plot the guess workspace for the full function
Plot the guess workspace for the full function
[ "Plot", "the", "guess", "workspace", "for", "the", "full", "function" ]
def plot_guess_all(self): """ Plot the guess workspace for the full function """ fun = self.fit_browser.getFittingFunction() ws_name = self.fit_browser.workspaceName() if fun == '' or ws_name == '': return out_ws_name = f'{ws_name}_guess' line = self._plot_guess_workspace(ws_name, fun, out_ws_name) if line: self.guess_all_line = line self.fit_browser.setTextPlotGuess('Remove Guess')
[ "def", "plot_guess_all", "(", "self", ")", ":", "fun", "=", "self", ".", "fit_browser", ".", "getFittingFunction", "(", ")", "ws_name", "=", "self", ".", "fit_browser", ".", "workspaceName", "(", ")", "if", "fun", "==", "''", "or", "ws_name", "==", "''", ":", "return", "out_ws_name", "=", "f'{ws_name}_guess'", "line", "=", "self", ".", "_plot_guess_workspace", "(", "ws_name", ",", "fun", ",", "out_ws_name", ")", "if", "line", ":", "self", ".", "guess_all_line", "=", "line", "self", ".", "fit_browser", ".", "setTextPlotGuess", "(", "'Remove Guess'", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowserplotinteraction.py#L143-L157
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/joblib/joblib/_parallel_backends.py
python
AutoBatchingMixin.compute_batch_size
(self)
return batch_size
Determine the optimal batch size
Determine the optimal batch size
[ "Determine", "the", "optimal", "batch", "size" ]
def compute_batch_size(self): """Determine the optimal batch size""" old_batch_size = self._effective_batch_size batch_duration = self._smoothed_batch_duration if (batch_duration > 0 and batch_duration < self.MIN_IDEAL_BATCH_DURATION): # The current batch size is too small: the duration of the # processing of a batch of task is not large enough to hide # the scheduling overhead. ideal_batch_size = int(old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration) # Multiply by two to limit oscilations between min and max. ideal_batch_size *= 2 # dont increase the batch size too fast to limit huge batch sizes # potentially leading to starving worker batch_size = min(2 * old_batch_size, ideal_batch_size) batch_size = max(batch_size, 1) self._effective_batch_size = batch_size if self.parallel.verbose >= 10: self.parallel._print( "Batch computation too fast (%.4fs.) " "Setting batch_size=%d.", (batch_duration, batch_size)) elif (batch_duration > self.MAX_IDEAL_BATCH_DURATION and old_batch_size >= 2): # The current batch size is too big. If we schedule overly long # running batches some CPUs might wait with nothing left to do # while a couple of CPUs a left processing a few long running # batches. Better reduce the batch size a bit to limit the # likelihood of scheduling such stragglers. # decrease the batch size quickly to limit potential starving ideal_batch_size = int( old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration ) # Multiply by two to limit oscilations between min and max. batch_size = max(2 * ideal_batch_size, 1) self._effective_batch_size = batch_size if self.parallel.verbose >= 10: self.parallel._print( "Batch computation too slow (%.4fs.) " "Setting batch_size=%d.", (batch_duration, batch_size)) else: # No batch size adjustment batch_size = old_batch_size if batch_size != old_batch_size: # Reset estimation of the smoothed mean batch duration: this # estimate is updated in the multiprocessing apply_async # CallBack as long as the batch_size is constant. Therefore # we need to reset the estimate whenever we re-tune the batch # size. self._smoothed_batch_duration = \ self._DEFAULT_SMOOTHED_BATCH_DURATION return batch_size
[ "def", "compute_batch_size", "(", "self", ")", ":", "old_batch_size", "=", "self", ".", "_effective_batch_size", "batch_duration", "=", "self", ".", "_smoothed_batch_duration", "if", "(", "batch_duration", ">", "0", "and", "batch_duration", "<", "self", ".", "MIN_IDEAL_BATCH_DURATION", ")", ":", "# The current batch size is too small: the duration of the", "# processing of a batch of task is not large enough to hide", "# the scheduling overhead.", "ideal_batch_size", "=", "int", "(", "old_batch_size", "*", "self", ".", "MIN_IDEAL_BATCH_DURATION", "/", "batch_duration", ")", "# Multiply by two to limit oscilations between min and max.", "ideal_batch_size", "*=", "2", "# dont increase the batch size too fast to limit huge batch sizes", "# potentially leading to starving worker", "batch_size", "=", "min", "(", "2", "*", "old_batch_size", ",", "ideal_batch_size", ")", "batch_size", "=", "max", "(", "batch_size", ",", "1", ")", "self", ".", "_effective_batch_size", "=", "batch_size", "if", "self", ".", "parallel", ".", "verbose", ">=", "10", ":", "self", ".", "parallel", ".", "_print", "(", "\"Batch computation too fast (%.4fs.) \"", "\"Setting batch_size=%d.\"", ",", "(", "batch_duration", ",", "batch_size", ")", ")", "elif", "(", "batch_duration", ">", "self", ".", "MAX_IDEAL_BATCH_DURATION", "and", "old_batch_size", ">=", "2", ")", ":", "# The current batch size is too big. If we schedule overly long", "# running batches some CPUs might wait with nothing left to do", "# while a couple of CPUs a left processing a few long running", "# batches. Better reduce the batch size a bit to limit the", "# likelihood of scheduling such stragglers.", "# decrease the batch size quickly to limit potential starving", "ideal_batch_size", "=", "int", "(", "old_batch_size", "*", "self", ".", "MIN_IDEAL_BATCH_DURATION", "/", "batch_duration", ")", "# Multiply by two to limit oscilations between min and max.", "batch_size", "=", "max", "(", "2", "*", "ideal_batch_size", ",", "1", ")", "self", ".", "_effective_batch_size", "=", "batch_size", "if", "self", ".", "parallel", ".", "verbose", ">=", "10", ":", "self", ".", "parallel", ".", "_print", "(", "\"Batch computation too slow (%.4fs.) \"", "\"Setting batch_size=%d.\"", ",", "(", "batch_duration", ",", "batch_size", ")", ")", "else", ":", "# No batch size adjustment", "batch_size", "=", "old_batch_size", "if", "batch_size", "!=", "old_batch_size", ":", "# Reset estimation of the smoothed mean batch duration: this", "# estimate is updated in the multiprocessing apply_async", "# CallBack as long as the batch_size is constant. Therefore", "# we need to reset the estimate whenever we re-tune the batch", "# size.", "self", ".", "_smoothed_batch_duration", "=", "self", ".", "_DEFAULT_SMOOTHED_BATCH_DURATION", "return", "batch_size" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/_parallel_backends.py#L285-L343
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
lib/roi_data_layer/layer.py
python
RoIDataLayer.backward
(self, top, propagate_down, bottom)
This layer does not propagate gradients.
This layer does not propagate gradients.
[ "This", "layer", "does", "not", "propagate", "gradients", "." ]
def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass
[ "def", "backward", "(", "self", ",", "top", ",", "propagate_down", ",", "bottom", ")", ":", "pass" ]
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/lib/roi_data_layer/layer.py#L154-L156
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/crash_server.py
python
CrashHTTPRequestHandler.do_HEAD
(self)
Default empty implementation for handling HEAD requests.
Default empty implementation for handling HEAD requests.
[ "Default", "empty", "implementation", "for", "handling", "HEAD", "requests", "." ]
def do_HEAD(self): """ Default empty implementation for handling HEAD requests. """ self._send_default_response_headers()
[ "def", "do_HEAD", "(", "self", ")", ":", "self", ".", "_send_default_response_headers", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/crash_server.py#L205-L207
OpenNebula/one
982e09706fc444ae60a8ad2f818d6a795cbbdab4
share/websockify/websockify/websocket.py
python
WebSocketRequestHandler.do_GET
(self)
Handle GET request. Calls handle_websocket(). If unsuccessful, and web server is enabled, SimpleHTTPRequestHandler.do_GET will be called.
Handle GET request. Calls handle_websocket(). If unsuccessful, and web server is enabled, SimpleHTTPRequestHandler.do_GET will be called.
[ "Handle", "GET", "request", ".", "Calls", "handle_websocket", "()", ".", "If", "unsuccessful", "and", "web", "server", "is", "enabled", "SimpleHTTPRequestHandler", ".", "do_GET", "will", "be", "called", "." ]
def do_GET(self): """Handle GET request. Calls handle_websocket(). If unsuccessful, and web server is enabled, SimpleHTTPRequestHandler.do_GET will be called.""" if not self.handle_websocket(): if self.only_upgrade: self.send_error(405, "Method Not Allowed") else: SimpleHTTPRequestHandler.do_GET(self)
[ "def", "do_GET", "(", "self", ")", ":", "if", "not", "self", ".", "handle_websocket", "(", ")", ":", "if", "self", ".", "only_upgrade", ":", "self", ".", "send_error", "(", "405", ",", "\"Method Not Allowed\"", ")", "else", ":", "SimpleHTTPRequestHandler", ".", "do_GET", "(", "self", ")" ]
https://github.com/OpenNebula/one/blob/982e09706fc444ae60a8ad2f818d6a795cbbdab4/share/websockify/websockify/websocket.py#L540-L547
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Misc.tk_focusPrev
(self)
return self._nametowidget(name)
Return previous widget in the focus order. See tk_focusNext for details.
Return previous widget in the focus order. See tk_focusNext for details.
[ "Return", "previous", "widget", "in", "the", "focus", "order", ".", "See", "tk_focusNext", "for", "details", "." ]
def tk_focusPrev(self): """Return previous widget in the focus order. See tk_focusNext for details.""" name = self.tk.call('tk_focusPrev', self._w) if not name: return None return self._nametowidget(name)
[ "def", "tk_focusPrev", "(", "self", ")", ":", "name", "=", "self", ".", "tk", ".", "call", "(", "'tk_focusPrev'", ",", "self", ".", "_w", ")", "if", "not", "name", ":", "return", "None", "return", "self", ".", "_nametowidget", "(", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L730-L734
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/profiler/pprof_profiler.py
python
PprofProfiler._get_profile_data_generator
(self)
return profile_data_generator
Get function that generates `ProfileDatum` objects. Returns: A function that generates `ProfileDatum` objects.
Get function that generates `ProfileDatum` objects.
[ "Get", "function", "that", "generates", "ProfileDatum", "objects", "." ]
def _get_profile_data_generator(self): """Get function that generates `ProfileDatum` objects. Returns: A function that generates `ProfileDatum` objects. """ node_to_traceback = defaultdict(list) node_to_op_type = defaultdict(str) for op in self._graph.get_operations(): node_to_traceback[op.name] = op.traceback_with_start_lines node_to_op_type[op.name] = op.type def profile_data_generator(device_step_stats): for node_stats in device_step_stats.node_stats: if node_stats.node_name == '_SOURCE' or node_stats.node_name == '_SINK': continue yield ProfileDatum( node_stats, node_to_op_type[node_stats.node_name], node_to_traceback[node_stats.node_name]) return profile_data_generator
[ "def", "_get_profile_data_generator", "(", "self", ")", ":", "node_to_traceback", "=", "defaultdict", "(", "list", ")", "node_to_op_type", "=", "defaultdict", "(", "str", ")", "for", "op", "in", "self", ".", "_graph", ".", "get_operations", "(", ")", ":", "node_to_traceback", "[", "op", ".", "name", "]", "=", "op", ".", "traceback_with_start_lines", "node_to_op_type", "[", "op", ".", "name", "]", "=", "op", ".", "type", "def", "profile_data_generator", "(", "device_step_stats", ")", ":", "for", "node_stats", "in", "device_step_stats", ".", "node_stats", ":", "if", "node_stats", ".", "node_name", "==", "'_SOURCE'", "or", "node_stats", ".", "node_name", "==", "'_SINK'", ":", "continue", "yield", "ProfileDatum", "(", "node_stats", ",", "node_to_op_type", "[", "node_stats", ".", "node_name", "]", ",", "node_to_traceback", "[", "node_stats", ".", "node_name", "]", ")", "return", "profile_data_generator" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/profiler/pprof_profiler.py#L365-L386
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
InputStream.read
(*args, **kwargs)
return _core_.InputStream_read(*args, **kwargs)
read(self, int size=-1) -> PyObject
read(self, int size=-1) -> PyObject
[ "read", "(", "self", "int", "size", "=", "-", "1", ")", "-", ">", "PyObject" ]
def read(*args, **kwargs): """read(self, int size=-1) -> PyObject""" return _core_.InputStream_read(*args, **kwargs)
[ "def", "read", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "InputStream_read", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2170-L2172
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/lib2to3/fixer_util.py
python
Dot
()
return Leaf(token.DOT, u".")
A period (.) leaf
A period (.) leaf
[ "A", "period", "(", ".", ")", "leaf" ]
def Dot(): """A period (.) leaf""" return Leaf(token.DOT, u".")
[ "def", "Dot", "(", ")", ":", "return", "Leaf", "(", "token", ".", "DOT", ",", "u\".\"", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/fixer_util.py#L48-L50
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/init_ops.py
python
Initializer.from_config
(cls, config)
return cls(**config)
Instantiates an initializer from a configuration dictionary. Example: ```python initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config) ``` Args: config: A Python dictionary. It will typically be the output of `get_config`. Returns: An Initializer instance.
Instantiates an initializer from a configuration dictionary.
[ "Instantiates", "an", "initializer", "from", "a", "configuration", "dictionary", "." ]
def from_config(cls, config): """Instantiates an initializer from a configuration dictionary. Example: ```python initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config) ``` Args: config: A Python dictionary. It will typically be the output of `get_config`. Returns: An Initializer instance. """ return cls(**config)
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "return", "cls", "(", "*", "*", "config", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/init_ops.py#L75-L93
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/calendar.py
python
CalendarCtrlBase.EnableMonthChange
(*args, **kwargs)
return _calendar.CalendarCtrlBase_EnableMonthChange(*args, **kwargs)
EnableMonthChange(self, bool enable=True) This function should be used instead of changing CAL_NO_MONTH_CHANGE style bit. It allows or disallows the user to change the month interactively. Note that if the month can not be changed, the year can not be changed either.
EnableMonthChange(self, bool enable=True)
[ "EnableMonthChange", "(", "self", "bool", "enable", "=", "True", ")" ]
def EnableMonthChange(*args, **kwargs): """ EnableMonthChange(self, bool enable=True) This function should be used instead of changing CAL_NO_MONTH_CHANGE style bit. It allows or disallows the user to change the month interactively. Note that if the month can not be changed, the year can not be changed either. """ return _calendar.CalendarCtrlBase_EnableMonthChange(*args, **kwargs)
[ "def", "EnableMonthChange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_calendar", ".", "CalendarCtrlBase_EnableMonthChange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/calendar.py#L307-L316
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Image.ResampleBox
(*args, **kwargs)
return _core_.Image_ResampleBox(*args, **kwargs)
ResampleBox(self, int width, int height) -> Image
ResampleBox(self, int width, int height) -> Image
[ "ResampleBox", "(", "self", "int", "width", "int", "height", ")", "-", ">", "Image" ]
def ResampleBox(*args, **kwargs): """ResampleBox(self, int width, int height) -> Image""" return _core_.Image_ResampleBox(*args, **kwargs)
[ "def", "ResampleBox", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_ResampleBox", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L2922-L2924
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ebmlib/backupmgr.py
python
FileBackupMgr.SetBackupFileTemplate
(self, tstr)
Set the filename template for generating the backupfile name @param tstr: template string i.e) %s~
Set the filename template for generating the backupfile name @param tstr: template string i.e) %s~
[ "Set", "the", "filename", "template", "for", "generating", "the", "backupfile", "name", "@param", "tstr", ":", "template", "string", "i", ".", "e", ")", "%s~" ]
def SetBackupFileTemplate(self, tstr): """Set the filename template for generating the backupfile name @param tstr: template string i.e) %s~ """ assert tstr.count("%s") == 1, "Format statment must only have one arg" self.template = tstr
[ "def", "SetBackupFileTemplate", "(", "self", ",", "tstr", ")", ":", "assert", "tstr", ".", "count", "(", "\"%s\"", ")", "==", "1", ",", "\"Format statment must only have one arg\"", "self", ".", "template", "=", "tstr" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/backupmgr.py#L165-L171
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/sparse_grad.py
python
_SparseTensorDenseMatMulGrad
(op, grad)
return (None, array_ops.squeeze(a_values_grad, axis=[-2, -1]), None, b_grad)
Gradients for the dense tensor in the SparseTensorDenseMatMul op. Args: op: the SparseTensorDenseMatMul op grad: the incoming gradient Returns: Gradient for each of the 4 input tensors: (sparse_indices, sparse_values, sparse_shape, dense_tensor) The gradients for indices and shape are None. Raises: TypeError: When the two operands don't have the same type.
Gradients for the dense tensor in the SparseTensorDenseMatMul op.
[ "Gradients", "for", "the", "dense", "tensor", "in", "the", "SparseTensorDenseMatMul", "op", "." ]
def _SparseTensorDenseMatMulGrad(op, grad): """Gradients for the dense tensor in the SparseTensorDenseMatMul op. Args: op: the SparseTensorDenseMatMul op grad: the incoming gradient Returns: Gradient for each of the 4 input tensors: (sparse_indices, sparse_values, sparse_shape, dense_tensor) The gradients for indices and shape are None. Raises: TypeError: When the two operands don't have the same type. """ a_indices, a_values, a_shape = op.inputs[:3] b = op.inputs[3] adj_a = op.get_attr("adjoint_a") adj_b = op.get_attr("adjoint_b") a_type = a_values.dtype.base_dtype b_type = b.dtype.base_dtype if a_type != b_type: raise TypeError( f"SparseTensorDenseMatMul op received operands with different types: " f"`{a_type}` and `{b_type}`.") # gradient w.r.t. dense b_grad = gen_sparse_ops.sparse_tensor_dense_mat_mul( a_indices, a_values, a_shape, grad, adjoint_a=not adj_a) if adj_b: b_grad = array_ops.matrix_transpose(b_grad, conjugate=True) # gradient w.r.t. sparse values # TODO(zongheng): these gather calls could potentially duplicate rows/cols in # memory. If there is a need, we should look into implementing this more # intelligently to avoid duplicating data. # With no adjoints, a_grad is matmul(grad, adjoint(b)). Since a is sparse, we # just want to compute that matmul at the rows/columns of non-zero values. The # (r, c) value is sum(grad[r, :] * adjoint(b)[:, c]), where the latter term is # more conveniently written as conj(b)[c, :]. That expression is more # efficient to calculate as a matmul, after expanding the two terms to be 2D # (i.e. a row vector and a column vector). # # If adj_b then we replace conj(b) by transpose(b); if adj_a we need to # adjoint the result, which is equivalent to swapping r and c and taking # conjugates. # Get grad[r, :] and b[c, :] (or with r and c swapped if adj_a, or with # transpose(b) if adj_b), as batches of vectors (with the batch dimension # corresponding to the non-zero indices of a). rows = a_indices[:, 0] cols = a_indices[:, 1] parts_a = array_ops.gather(grad, rows if not adj_a else cols) parts_b = array_ops.gather( b if not adj_b else array_ops.transpose(b), cols if not adj_a else rows) if not adj_a and not adj_b: # grad[r, :] * conj(b[c, :]) = row(grad[r, :]) @ adjoint(row(b[c, :])) a_values_grad = math_ops.matmul( array_ops.expand_dims(parts_a, -2), array_ops.expand_dims(parts_b, -2), adjoint_b=True) elif adj_a and not adj_b: # conj(grad[c, :] * conj(b[r, :])) = adjoint(col(grad[c, :])) @ col(b[r, :]) a_values_grad = math_ops.matmul( array_ops.expand_dims(parts_a, -1), array_ops.expand_dims(parts_b, -1), adjoint_a=True) elif not adj_a and adj_b: # grad[r, :] * transpose(b)[c, :] = # row(grad[r, :]) @ col(transpose(b)[c, :]) a_values_grad = math_ops.matmul( array_ops.expand_dims(parts_a, -2), array_ops.expand_dims(parts_b, -1)) elif adj_a and adj_b: # conj(grad[c, :] * transpose(b)[r, :]) = # adjoint(col(grad[c, :])) @ adjoint(row(transpose(b)[r, :]) a_values_grad = math_ops.matmul( array_ops.expand_dims(parts_a, -1), array_ops.expand_dims(parts_b, -2), adjoint_a=True, adjoint_b=True) # gradients w.r.t. (a_indices, a_values, a_shape, b) return (None, array_ops.squeeze(a_values_grad, axis=[-2, -1]), None, b_grad)
[ "def", "_SparseTensorDenseMatMulGrad", "(", "op", ",", "grad", ")", ":", "a_indices", ",", "a_values", ",", "a_shape", "=", "op", ".", "inputs", "[", ":", "3", "]", "b", "=", "op", ".", "inputs", "[", "3", "]", "adj_a", "=", "op", ".", "get_attr", "(", "\"adjoint_a\"", ")", "adj_b", "=", "op", ".", "get_attr", "(", "\"adjoint_b\"", ")", "a_type", "=", "a_values", ".", "dtype", ".", "base_dtype", "b_type", "=", "b", ".", "dtype", ".", "base_dtype", "if", "a_type", "!=", "b_type", ":", "raise", "TypeError", "(", "f\"SparseTensorDenseMatMul op received operands with different types: \"", "f\"`{a_type}` and `{b_type}`.\"", ")", "# gradient w.r.t. dense", "b_grad", "=", "gen_sparse_ops", ".", "sparse_tensor_dense_mat_mul", "(", "a_indices", ",", "a_values", ",", "a_shape", ",", "grad", ",", "adjoint_a", "=", "not", "adj_a", ")", "if", "adj_b", ":", "b_grad", "=", "array_ops", ".", "matrix_transpose", "(", "b_grad", ",", "conjugate", "=", "True", ")", "# gradient w.r.t. sparse values", "# TODO(zongheng): these gather calls could potentially duplicate rows/cols in", "# memory. If there is a need, we should look into implementing this more", "# intelligently to avoid duplicating data.", "# With no adjoints, a_grad is matmul(grad, adjoint(b)). Since a is sparse, we", "# just want to compute that matmul at the rows/columns of non-zero values. The", "# (r, c) value is sum(grad[r, :] * adjoint(b)[:, c]), where the latter term is", "# more conveniently written as conj(b)[c, :]. That expression is more", "# efficient to calculate as a matmul, after expanding the two terms to be 2D", "# (i.e. a row vector and a column vector).", "#", "# If adj_b then we replace conj(b) by transpose(b); if adj_a we need to", "# adjoint the result, which is equivalent to swapping r and c and taking", "# conjugates.", "# Get grad[r, :] and b[c, :] (or with r and c swapped if adj_a, or with", "# transpose(b) if adj_b), as batches of vectors (with the batch dimension", "# corresponding to the non-zero indices of a).", "rows", "=", "a_indices", "[", ":", ",", "0", "]", "cols", "=", "a_indices", "[", ":", ",", "1", "]", "parts_a", "=", "array_ops", ".", "gather", "(", "grad", ",", "rows", "if", "not", "adj_a", "else", "cols", ")", "parts_b", "=", "array_ops", ".", "gather", "(", "b", "if", "not", "adj_b", "else", "array_ops", ".", "transpose", "(", "b", ")", ",", "cols", "if", "not", "adj_a", "else", "rows", ")", "if", "not", "adj_a", "and", "not", "adj_b", ":", "# grad[r, :] * conj(b[c, :]) = row(grad[r, :]) @ adjoint(row(b[c, :]))", "a_values_grad", "=", "math_ops", ".", "matmul", "(", "array_ops", ".", "expand_dims", "(", "parts_a", ",", "-", "2", ")", ",", "array_ops", ".", "expand_dims", "(", "parts_b", ",", "-", "2", ")", ",", "adjoint_b", "=", "True", ")", "elif", "adj_a", "and", "not", "adj_b", ":", "# conj(grad[c, :] * conj(b[r, :])) = adjoint(col(grad[c, :])) @ col(b[r, :])", "a_values_grad", "=", "math_ops", ".", "matmul", "(", "array_ops", ".", "expand_dims", "(", "parts_a", ",", "-", "1", ")", ",", "array_ops", ".", "expand_dims", "(", "parts_b", ",", "-", "1", ")", ",", "adjoint_a", "=", "True", ")", "elif", "not", "adj_a", "and", "adj_b", ":", "# grad[r, :] * transpose(b)[c, :] =", "# row(grad[r, :]) @ col(transpose(b)[c, :])", "a_values_grad", "=", "math_ops", ".", "matmul", "(", "array_ops", ".", "expand_dims", "(", "parts_a", ",", "-", "2", ")", ",", "array_ops", ".", "expand_dims", "(", "parts_b", ",", "-", "1", ")", ")", "elif", "adj_a", "and", "adj_b", ":", "# conj(grad[c, :] * transpose(b)[r, :]) =", "# adjoint(col(grad[c, :])) @ adjoint(row(transpose(b)[r, :])", "a_values_grad", "=", "math_ops", ".", "matmul", "(", "array_ops", ".", "expand_dims", "(", "parts_a", ",", "-", "1", ")", ",", "array_ops", ".", "expand_dims", "(", "parts_b", ",", "-", "2", ")", ",", "adjoint_a", "=", "True", ",", "adjoint_b", "=", "True", ")", "# gradients w.r.t. (a_indices, a_values, a_shape, b)", "return", "(", "None", ",", "array_ops", ".", "squeeze", "(", "a_values_grad", ",", "axis", "=", "[", "-", "2", ",", "-", "1", "]", ")", ",", "None", ",", "b_grad", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/sparse_grad.py#L142-L228
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py
python
spawn.eof
(self)
return self.flag_eof
This returns True if the EOF exception was ever raised.
This returns True if the EOF exception was ever raised.
[ "This", "returns", "True", "if", "the", "EOF", "exception", "was", "ever", "raised", "." ]
def eof(self): '''This returns True if the EOF exception was ever raised. ''' return self.flag_eof
[ "def", "eof", "(", "self", ")", ":", "return", "self", ".", "flag_eof" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py#L604-L607
kevinlin311tw/cvpr16-deepbit
c60fb3233d7d534cfcee9d3ed47d77af437ee32a
scripts/cpp_lint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "r'\\\"'", ")", "-", "line", ".", "count", "(", "\"'\\\"'\"", ")", ")", "&", "1", ")", "==", "1" ]
https://github.com/kevinlin311tw/cvpr16-deepbit/blob/c60fb3233d7d534cfcee9d3ed47d77af437ee32a/scripts/cpp_lint.py#L1045-L1059