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
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/zipfile.py
python
ZipFile._extract_member
(self, member, targetpath, pwd)
return targetpath
Extract the ZipInfo object 'member' to a physical file on the path targetpath.
Extract the ZipInfo object 'member' to a physical file on the path targetpath.
[ "Extract", "the", "ZipInfo", "object", "member", "to", "a", "physical", "file", "on", "the", "path", "targetpath", "." ]
def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. # Strip trailing path separator, unless it represents the root. if (targetpath[-1:] in (os.path.sep, os.path.altsep) and len(os.path.splitdrive(targetpath)[1]) > 1): targetpath = targetpath[:-1] # don't include leading "/" from file name if present if member.filename[0] == '/': targetpath = os.path.join(targetpath, member.filename[1:]) else: targetpath = os.path.join(targetpath, member.filename) targetpath = os.path.normpath(targetpath) # Create all upper directories if necessary. upperdirs = os.path.dirname(targetpath) if upperdirs and not os.path.exists(upperdirs): os.makedirs(upperdirs) if member.filename[-1] == '/': if not os.path.isdir(targetpath): os.mkdir(targetpath) return targetpath source = self.open(member, pwd=pwd) target = file(targetpath, "wb") shutil.copyfileobj(source, target) source.close() target.close() return targetpath
[ "def", "_extract_member", "(", "self", ",", "member", ",", "targetpath", ",", "pwd", ")", ":", "# build the destination pathname, replacing", "# forward slashes to platform specific separators.", "# Strip trailing path separator, unless it represents the root.", "if", "(", "targetpath", "[", "-", "1", ":", "]", "in", "(", "os", ".", "path", ".", "sep", ",", "os", ".", "path", ".", "altsep", ")", "and", "len", "(", "os", ".", "path", ".", "splitdrive", "(", "targetpath", ")", "[", "1", "]", ")", ">", "1", ")", ":", "targetpath", "=", "targetpath", "[", ":", "-", "1", "]", "# don't include leading \"/\" from file name if present", "if", "member", ".", "filename", "[", "0", "]", "==", "'/'", ":", "targetpath", "=", "os", ".", "path", ".", "join", "(", "targetpath", ",", "member", ".", "filename", "[", "1", ":", "]", ")", "else", ":", "targetpath", "=", "os", ".", "path", ".", "join", "(", "targetpath", ",", "member", ".", "filename", ")", "targetpath", "=", "os", ".", "path", ".", "normpath", "(", "targetpath", ")", "# Create all upper directories if necessary.", "upperdirs", "=", "os", ".", "path", ".", "dirname", "(", "targetpath", ")", "if", "upperdirs", "and", "not", "os", ".", "path", ".", "exists", "(", "upperdirs", ")", ":", "os", ".", "makedirs", "(", "upperdirs", ")", "if", "member", ".", "filename", "[", "-", "1", "]", "==", "'/'", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "targetpath", ")", ":", "os", ".", "mkdir", "(", "targetpath", ")", "return", "targetpath", "source", "=", "self", ".", "open", "(", "member", ",", "pwd", "=", "pwd", ")", "target", "=", "file", "(", "targetpath", ",", "\"wb\"", ")", "shutil", ".", "copyfileobj", "(", "source", ",", "target", ")", "source", ".", "close", "(", ")", "target", ".", "close", "(", ")", "return", "targetpath" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/zipfile.py#L940-L975
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/third_party/examples/eager/spinn/spinn.py
python
Tracker.__init__
(self, tracker_size, predict)
Constructor of Tracker. Args: tracker_size: Number of dimensions of the underlying `LSTMCell`. predict: (`bool`) Whether prediction mode is enabled.
Constructor of Tracker.
[ "Constructor", "of", "Tracker", "." ]
def __init__(self, tracker_size, predict): """Constructor of Tracker. Args: tracker_size: Number of dimensions of the underlying `LSTMCell`. predict: (`bool`) Whether prediction mode is enabled. """ super(Tracker, self).__init__() self._rnn = tf.nn.rnn_cell.LSTMCell(tracker_size) self._state_size = tracker_size if predict: self._transition = layers.Dense(4) else: self._transition = None
[ "def", "__init__", "(", "self", ",", "tracker_size", ",", "predict", ")", ":", "super", "(", "Tracker", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_rnn", "=", "tf", ".", "nn", ".", "rnn_cell", ".", "LSTMCell", "(", "tracker_size", ")", "self", ".", "_state_size", "=", "tracker_size", "if", "predict", ":", "self", ".", "_transition", "=", "layers", ".", "Dense", "(", "4", ")", "else", ":", "self", ".", "_transition", "=", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/third_party/examples/eager/spinn/spinn.py#L131-L144
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_helper.py
python
get_fuzz_build_info
(job_content)
return fuzz_build_info
Get fuzz build info from job content info :param job_content: job content info :return: fuzz build info
Get fuzz build info from job content info :param job_content: job content info :return: fuzz build info
[ "Get", "fuzz", "build", "info", "from", "job", "content", "info", ":", "param", "job_content", ":", "job", "content", "info", ":", "return", ":", "fuzz", "build", "info" ]
def get_fuzz_build_info(job_content): """ Get fuzz build info from job content info :param job_content: job content info :return: fuzz build info """ op_compute_info = get_compute_op_list(job_content)[0] fuzz_build_info = dict() fuzz_build_info["compile_type"] = "fuzzily_build" if op_compute_info["build_type"] == BuildType.FUZZILY.value \ else "accurately_build" fuzz_build_info["miss_support_info"] = op_compute_info["miss_support_info"] fuzz_build_info["max_kernel_id"] = op_compute_info["max_kernel_id"] fuzz_build_info["incremental_link"] = os.path.realpath( job_content["SocInfo"]["op_debug_dir"] + "/kernel_meta/" + op_compute_info["name"] + ".json") if \ op_compute_info["build_type"] == BuildType.FUZZILY.value else "" return fuzz_build_info
[ "def", "get_fuzz_build_info", "(", "job_content", ")", ":", "op_compute_info", "=", "get_compute_op_list", "(", "job_content", ")", "[", "0", "]", "fuzz_build_info", "=", "dict", "(", ")", "fuzz_build_info", "[", "\"compile_type\"", "]", "=", "\"fuzzily_build\"", "if", "op_compute_info", "[", "\"build_type\"", "]", "==", "BuildType", ".", "FUZZILY", ".", "value", "else", "\"accurately_build\"", "fuzz_build_info", "[", "\"miss_support_info\"", "]", "=", "op_compute_info", "[", "\"miss_support_info\"", "]", "fuzz_build_info", "[", "\"max_kernel_id\"", "]", "=", "op_compute_info", "[", "\"max_kernel_id\"", "]", "fuzz_build_info", "[", "\"incremental_link\"", "]", "=", "os", ".", "path", ".", "realpath", "(", "job_content", "[", "\"SocInfo\"", "]", "[", "\"op_debug_dir\"", "]", "+", "\"/kernel_meta/\"", "+", "op_compute_info", "[", "\"name\"", "]", "+", "\".json\"", ")", "if", "op_compute_info", "[", "\"build_type\"", "]", "==", "BuildType", ".", "FUZZILY", ".", "value", "else", "\"\"", "return", "fuzz_build_info" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_helper.py#L216-L231
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py
python
_ShardName
(name, number)
return '#'.join(parts)
Add a shard number to the end of a target. Arguments: name: name of the target (foo#target) number: shard number Returns: Target name with shard added (foo_1#target)
Add a shard number to the end of a target.
[ "Add", "a", "shard", "number", "to", "the", "end", "of", "a", "target", "." ]
def _ShardName(name, number): """Add a shard number to the end of a target. Arguments: name: name of the target (foo#target) number: shard number Returns: Target name with shard added (foo_1#target) """ parts = name.rsplit('#', 1) parts[0] = '%s_%d' % (parts[0], number) return '#'.join(parts)
[ "def", "_ShardName", "(", "name", ",", "number", ")", ":", "parts", "=", "name", ".", "rsplit", "(", "'#'", ",", "1", ")", "parts", "[", "0", "]", "=", "'%s_%d'", "%", "(", "parts", "[", "0", "]", ",", "number", ")", "return", "'#'", ".", "join", "(", "parts", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L1721-L1732
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/core_encoder.py
python
Encoder._commuting_structure_impl
(self, previous)
return commuting_structure
Implementation for the `commuting_structure` property.
Implementation for the `commuting_structure` property.
[ "Implementation", "for", "the", "commuting_structure", "property", "." ]
def _commuting_structure_impl(self, previous): """Implementation for the `commuting_structure` property.""" current = previous & self.stage.commutes_with_sum commuting_structure = { EncoderKeys.COMMUTE: current, EncoderKeys.CHILDREN: {} } for key, encoder in six.iteritems(self.children): commuting_structure[EncoderKeys.CHILDREN][key] = ( encoder._commuting_structure_impl(current)) # pylint: disable=protected-access return commuting_structure
[ "def", "_commuting_structure_impl", "(", "self", ",", "previous", ")", ":", "current", "=", "previous", "&", "self", ".", "stage", ".", "commutes_with_sum", "commuting_structure", "=", "{", "EncoderKeys", ".", "COMMUTE", ":", "current", ",", "EncoderKeys", ".", "CHILDREN", ":", "{", "}", "}", "for", "key", ",", "encoder", "in", "six", ".", "iteritems", "(", "self", ".", "children", ")", ":", "commuting_structure", "[", "EncoderKeys", ".", "CHILDREN", "]", "[", "key", "]", "=", "(", "encoder", ".", "_commuting_structure_impl", "(", "current", ")", ")", "# pylint: disable=protected-access", "return", "commuting_structure" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/core_encoder.py#L110-L120
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/data.py
python
Documentation.flatten
(self, installer)
return Data.flatten(self, installer)
Check if docs should be installed at all
Check if docs should be installed at all
[ "Check", "if", "docs", "should", "be", "installed", "at", "all" ]
def flatten(self, installer): """ Check if docs should be installed at all """ if installer.without_docs: return [] return Data.flatten(self, installer)
[ "def", "flatten", "(", "self", ",", "installer", ")", ":", "if", "installer", ".", "without_docs", ":", "return", "[", "]", "return", "Data", ".", "flatten", "(", "self", ",", "installer", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py2/data.py#L137-L141
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_CertifyX509_REQUEST.toTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def toTpm(self, buf): """ TpmMarshaller method """ buf.writeSizedByteBuf(self.reserved) buf.writeShort(self.inScheme.GetUnionSelector()) self.inScheme.toTpm(buf) buf.writeSizedByteBuf(self.partialCertificate)
[ "def", "toTpm", "(", "self", ",", "buf", ")", ":", "buf", ".", "writeSizedByteBuf", "(", "self", ".", "reserved", ")", "buf", ".", "writeShort", "(", "self", ".", "inScheme", ".", "GetUnionSelector", "(", ")", ")", "self", ".", "inScheme", ".", "toTpm", "(", "buf", ")", "buf", ".", "writeSizedByteBuf", "(", "self", ".", "partialCertificate", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L13149-L13154
CGRU/cgru
1881a4128530e3d31ac6c25314c18314fc50c2c7
afanasy/python/parsers/parser.py
python
parser.tagHTML
(self, i_line)
return i_line
Convert line to HTML. Designed for GUIs for escape sequences, errors highlighting. Function designed to be implemented in child classes, if special highlinghting needed. :param i_line: input line :return: converted line
Convert line to HTML. Designed for GUIs for escape sequences, errors highlighting. Function designed to be implemented in child classes, if special highlinghting needed. :param i_line: input line :return: converted line
[ "Convert", "line", "to", "HTML", ".", "Designed", "for", "GUIs", "for", "escape", "sequences", "errors", "highlighting", ".", "Function", "designed", "to", "be", "implemented", "in", "child", "classes", "if", "special", "highlinghting", "needed", ".", ":", "param", "i_line", ":", "input", "line", ":", "return", ":", "converted", "line" ]
def tagHTML(self, i_line): """ Convert line to HTML. Designed for GUIs for escape sequences, errors highlighting. Function designed to be implemented in child classes, if special highlinghting needed. :param i_line: input line :return: converted line """ return i_line
[ "def", "tagHTML", "(", "self", ",", "i_line", ")", ":", "return", "i_line" ]
https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/parsers/parser.py#L279-L286
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/symbol/random.py
python
multinomial
(data, shape=_Null, get_prob=True, dtype='int32', **kwargs)
return _internal._sample_multinomial(data, shape, get_prob, dtype=dtype, **kwargs)
Concurrent sampling from multiple multinomial distributions. .. note:: The input distribution must be normalized, i.e. `data` must sum to 1 along its last dimension. Parameters ---------- data : Symbol An *n* dimensional array whose last dimension has length `k`, where `k` is the number of possible outcomes of each multinomial distribution. For example, data with shape `(m, n, k)` specifies `m*n` multinomial distributions each with `k` possible outcomes. shape : int or tuple of ints, optional The number of samples to draw from each distribution. If shape is empty one sample will be drawn from each distribution. get_prob : bool, optional If true, a second array containing log likelihood of the drawn samples will also be returned. This is usually used for reinforcement learning, where you can provide reward as head gradient w.r.t. this array to estimate gradient. dtype : str or numpy.dtype, optional Data type of the sample output array. The default is int32. Note that the data type of the log likelihood array is the same with that of `data`. Returns ------- Symbol For input `data` with `n` dimensions and shape `(d1, d2, ..., dn-1, k)`, and input `shape` with shape `(s1, s2, ..., sx)`, returns a Symbol that resovles to shape `(d1, d2, ... dn-1, s1, s2, ..., sx)`. The `s1, s2, ... sx` dimensions of the returned Symbol's resolved value will consist of 0-indexed values sampled from each respective multinomial distribution provided in the `k` dimension of `data`. For the case `n`=1, and `x`=1 (one shape dimension), returned Symbol will resolve to shape `(s1,)`. If `get_prob` is set to True, this function returns a Symbol that will resolve to a list of outputs: `[ndarray_output, log_likelihood_output]`, where `log_likelihood_output` will resolve to the same shape as the sampled outputs in ndarray_output.
Concurrent sampling from multiple multinomial distributions.
[ "Concurrent", "sampling", "from", "multiple", "multinomial", "distributions", "." ]
def multinomial(data, shape=_Null, get_prob=True, dtype='int32', **kwargs): """Concurrent sampling from multiple multinomial distributions. .. note:: The input distribution must be normalized, i.e. `data` must sum to 1 along its last dimension. Parameters ---------- data : Symbol An *n* dimensional array whose last dimension has length `k`, where `k` is the number of possible outcomes of each multinomial distribution. For example, data with shape `(m, n, k)` specifies `m*n` multinomial distributions each with `k` possible outcomes. shape : int or tuple of ints, optional The number of samples to draw from each distribution. If shape is empty one sample will be drawn from each distribution. get_prob : bool, optional If true, a second array containing log likelihood of the drawn samples will also be returned. This is usually used for reinforcement learning, where you can provide reward as head gradient w.r.t. this array to estimate gradient. dtype : str or numpy.dtype, optional Data type of the sample output array. The default is int32. Note that the data type of the log likelihood array is the same with that of `data`. Returns ------- Symbol For input `data` with `n` dimensions and shape `(d1, d2, ..., dn-1, k)`, and input `shape` with shape `(s1, s2, ..., sx)`, returns a Symbol that resovles to shape `(d1, d2, ... dn-1, s1, s2, ..., sx)`. The `s1, s2, ... sx` dimensions of the returned Symbol's resolved value will consist of 0-indexed values sampled from each respective multinomial distribution provided in the `k` dimension of `data`. For the case `n`=1, and `x`=1 (one shape dimension), returned Symbol will resolve to shape `(s1,)`. If `get_prob` is set to True, this function returns a Symbol that will resolve to a list of outputs: `[ndarray_output, log_likelihood_output]`, where `log_likelihood_output` will resolve to the same shape as the sampled outputs in ndarray_output. """ return _internal._sample_multinomial(data, shape, get_prob, dtype=dtype, **kwargs)
[ "def", "multinomial", "(", "data", ",", "shape", "=", "_Null", ",", "get_prob", "=", "True", ",", "dtype", "=", "'int32'", ",", "*", "*", "kwargs", ")", ":", "return", "_internal", ".", "_sample_multinomial", "(", "data", ",", "shape", ",", "get_prob", ",", "dtype", "=", "dtype", ",", "*", "*", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/symbol/random.py#L284-L325
ideawu/ssdb
f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4
deps/cpy/antlr3/tree.py
python
TreeNodeStream.setUniqueNavigationNodes
(self, uniqueNavigationNodes)
As we flatten the tree, we use UP, DOWN nodes to represent the tree structure. When debugging we need unique nodes so we have to instantiate new ones. When doing normal tree parsing, it's slow and a waste of memory to create unique navigation nodes. Default should be false;
As we flatten the tree, we use UP, DOWN nodes to represent the tree structure. When debugging we need unique nodes so we have to instantiate new ones. When doing normal tree parsing, it's slow and a waste of memory to create unique navigation nodes. Default should be false;
[ "As", "we", "flatten", "the", "tree", "we", "use", "UP", "DOWN", "nodes", "to", "represent", "the", "tree", "structure", ".", "When", "debugging", "we", "need", "unique", "nodes", "so", "we", "have", "to", "instantiate", "new", "ones", ".", "When", "doing", "normal", "tree", "parsing", "it", "s", "slow", "and", "a", "waste", "of", "memory", "to", "create", "unique", "navigation", "nodes", ".", "Default", "should", "be", "false", ";" ]
def setUniqueNavigationNodes(self, uniqueNavigationNodes): """ As we flatten the tree, we use UP, DOWN nodes to represent the tree structure. When debugging we need unique nodes so we have to instantiate new ones. When doing normal tree parsing, it's slow and a waste of memory to create unique navigation nodes. Default should be false; """ raise NotImplementedError
[ "def", "setUniqueNavigationNodes", "(", "self", ",", "uniqueNavigationNodes", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/tree.py#L1613-L1622
facebook/watchman
0917460c71b000b96be9b9575d77f06f2f6053bb
watchman/python/pywatchman_aio/__init__.py
python
AIOClient.pop_log
(self)
return res
Get one log from the log queue.
Get one log from the log queue.
[ "Get", "one", "log", "from", "the", "log", "queue", "." ]
async def pop_log(self): """Get one log from the log queue.""" self._check_receive_loop() res = self.log_queue.get() self._check_error(res) return res
[ "async", "def", "pop_log", "(", "self", ")", ":", "self", ".", "_check_receive_loop", "(", ")", "res", "=", "self", ".", "log_queue", ".", "get", "(", ")", "self", ".", "_check_error", "(", "res", ")", "return", "res" ]
https://github.com/facebook/watchman/blob/0917460c71b000b96be9b9575d77f06f2f6053bb/watchman/python/pywatchman_aio/__init__.py#L261-L266
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeItemId.__init__
(self, *args, **kwargs)
__init__(self) -> TreeItemId
__init__(self) -> TreeItemId
[ "__init__", "(", "self", ")", "-", ">", "TreeItemId" ]
def __init__(self, *args, **kwargs): """__init__(self) -> TreeItemId""" _controls_.TreeItemId_swiginit(self,_controls_.new_TreeItemId(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "TreeItemId_swiginit", "(", "self", ",", "_controls_", ".", "new_TreeItemId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5003-L5005
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/combo.py
python
ComboCtrl.UseAltPopupWindow
(*args, **kwargs)
return _combo.ComboCtrl_UseAltPopupWindow(*args, **kwargs)
UseAltPopupWindow(self, bool enable=True) Enable or disable usage of an alternative popup window, which guarantees ability to focus the popup control, and allows common native controls to function normally. This alternative popup window is usually a wxDialog, and as such, when it is shown, its parent top-level window will appear as if the focus has been lost from it.
UseAltPopupWindow(self, bool enable=True)
[ "UseAltPopupWindow", "(", "self", "bool", "enable", "=", "True", ")" ]
def UseAltPopupWindow(*args, **kwargs): """ UseAltPopupWindow(self, bool enable=True) Enable or disable usage of an alternative popup window, which guarantees ability to focus the popup control, and allows common native controls to function normally. This alternative popup window is usually a wxDialog, and as such, when it is shown, its parent top-level window will appear as if the focus has been lost from it. """ return _combo.ComboCtrl_UseAltPopupWindow(*args, **kwargs)
[ "def", "UseAltPopupWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboCtrl_UseAltPopupWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/combo.py#L386-L396
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_to_struct/struct_generator.py
python
GenerateField
(field_info)
Generate a string defining a field of the type specified by field_info['type'] in a C structure.
Generate a string defining a field of the type specified by field_info['type'] in a C structure.
[ "Generate", "a", "string", "defining", "a", "field", "of", "the", "type", "specified", "by", "field_info", "[", "type", "]", "in", "a", "C", "structure", "." ]
def GenerateField(field_info): """Generate a string defining a field of the type specified by field_info['type'] in a C structure. """ field = field_info['field'] type = field_info['type'] if type == 'int': return 'const int %s' % field elif type == 'string': return 'const char* const %s' % field elif type == 'string16': return 'const wchar_t* const %s' % field elif type == 'enum': return 'const %s %s' % (field_info['ctype'], field) elif type == 'array': return _GenerateArrayField(field_info) elif type == 'struct': return 'const %s %s' % (field_info['type_name'], field) else: raise RuntimeError('Unknown field type "%s"' % type)
[ "def", "GenerateField", "(", "field_info", ")", ":", "field", "=", "field_info", "[", "'field'", "]", "type", "=", "field_info", "[", "'type'", "]", "if", "type", "==", "'int'", ":", "return", "'const int %s'", "%", "field", "elif", "type", "==", "'string'", ":", "return", "'const char* const %s'", "%", "field", "elif", "type", "==", "'string16'", ":", "return", "'const wchar_t* const %s'", "%", "field", "elif", "type", "==", "'enum'", ":", "return", "'const %s %s'", "%", "(", "field_info", "[", "'ctype'", "]", ",", "field", ")", "elif", "type", "==", "'array'", ":", "return", "_GenerateArrayField", "(", "field_info", ")", "elif", "type", "==", "'struct'", ":", "return", "'const %s %s'", "%", "(", "field_info", "[", "'type_name'", "]", ",", "field", ")", "else", ":", "raise", "RuntimeError", "(", "'Unknown field type \"%s\"'", "%", "type", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_to_struct/struct_generator.py#L15-L34
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
llvm/bindings/python/llvm/object.py
python
Symbol.section
(self)
return Section(sections)
The Section to which this Symbol belongs. The returned Section instance does not expire, unlike Sections that are commonly obtained through iteration. Because this obtains a new section iterator each time it is accessed, calling this on a number of Symbol instances could be expensive.
The Section to which this Symbol belongs.
[ "The", "Section", "to", "which", "this", "Symbol", "belongs", "." ]
def section(self): """The Section to which this Symbol belongs. The returned Section instance does not expire, unlike Sections that are commonly obtained through iteration. Because this obtains a new section iterator each time it is accessed, calling this on a number of Symbol instances could be expensive. """ sections = lib.LLVMGetSections(self._object_file) lib.LLVMMoveToContainingSection(sections, self) return Section(sections)
[ "def", "section", "(", "self", ")", ":", "sections", "=", "lib", ".", "LLVMGetSections", "(", "self", ".", "_object_file", ")", "lib", ".", "LLVMMoveToContainingSection", "(", "sections", ",", "self", ")", "return", "Section", "(", "sections", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/bindings/python/llvm/object.py#L329-L341
shedskin/shedskin
ae88dbca7b1d9671cd8be448cb0b497122758936
examples/sha.py
python
_rotateLeft
(x, n)
return (x << n) | (x >> (32-n))
Rotate x (32 bit) left n bits circularly.
Rotate x (32 bit) left n bits circularly.
[ "Rotate", "x", "(", "32", "bit", ")", "left", "n", "bits", "circularly", "." ]
def _rotateLeft(x, n): "Rotate x (32 bit) left n bits circularly." return (x << n) | (x >> (32-n))
[ "def", "_rotateLeft", "(", "x", ",", "n", ")", ":", "return", "(", "x", "<<", "n", ")", "|", "(", "x", ">>", "(", "32", "-", "n", ")", ")" ]
https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/sha.py#L93-L96
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Appearance.setTexture2D_b
(self, format: str, np_array2: "ndarray", topdown: bool=True)
return _robotsim.Appearance_setTexture2D_b(self, format, np_array2, topdown)
r""" Sets a 2D texture of the given width/height. See :func:`setTexture1D_b` for valid format strings. Args: format (str) np_array2 (:obj:`unsigned char *`) topdown (bool, optional): default value True The array is given in top to bottom order if `topdown==True`. Otherwise, it is given in order bottom to top.
r""" Sets a 2D texture of the given width/height. See :func:`setTexture1D_b` for valid format strings.
[ "r", "Sets", "a", "2D", "texture", "of", "the", "given", "width", "/", "height", ".", "See", ":", "func", ":", "setTexture1D_b", "for", "valid", "format", "strings", "." ]
def setTexture2D_b(self, format: str, np_array2: "ndarray", topdown: bool=True) ->None: r""" Sets a 2D texture of the given width/height. See :func:`setTexture1D_b` for valid format strings. Args: format (str) np_array2 (:obj:`unsigned char *`) topdown (bool, optional): default value True The array is given in top to bottom order if `topdown==True`. Otherwise, it is given in order bottom to top. """ return _robotsim.Appearance_setTexture2D_b(self, format, np_array2, topdown)
[ "def", "setTexture2D_b", "(", "self", ",", "format", ":", "str", ",", "np_array2", ":", "\"ndarray\"", ",", "topdown", ":", "bool", "=", "True", ")", "->", "None", ":", "return", "_robotsim", ".", "Appearance_setTexture2D_b", "(", "self", ",", "format", ",", "np_array2", ",", "topdown", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2975-L2989
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/gdal-utils/osgeo_utils/gdal2tiles.py
python
GDAL2Tiles.open_input
(self)
Initialization of the input raster, reprojection if necessary
Initialization of the input raster, reprojection if necessary
[ "Initialization", "of", "the", "input", "raster", "reprojection", "if", "necessary" ]
def open_input(self) -> None: """Initialization of the input raster, reprojection if necessary""" gdal.AllRegister() self.out_drv = gdal.GetDriverByName(self.tiledriver) self.mem_drv = gdal.GetDriverByName('MEM') if not self.out_drv: raise Exception("The '%s' driver was not found, is it available in this GDAL build?" % self.tiledriver) if not self.mem_drv: raise Exception("The 'MEM' driver was not found, is it available in this GDAL build?") # Open the input file if self.input_file: input_dataset: gdal.Dataset = gdal.Open(self.input_file, gdal.GA_ReadOnly) else: raise Exception("No input file was specified") if self.options.verbose: print("Input file:", "( %sP x %sL - %s bands)" % (input_dataset.RasterXSize, input_dataset.RasterYSize, input_dataset.RasterCount)) if not input_dataset: # Note: GDAL prints the ERROR message too exit_with_error("It is not possible to open the input file '%s'." % self.input_file) # Read metadata from the input file if input_dataset.RasterCount == 0: exit_with_error("Input file '%s' has no raster band" % self.input_file) if input_dataset.GetRasterBand(1).GetRasterColorTable(): exit_with_error( "Please convert this file to RGB/RGBA and run gdal2tiles on the result.", "From paletted file you can create RGBA file (temp.vrt) by:\n" "gdal_translate -of vrt -expand rgba %s temp.vrt\n" "then run:\n" "gdal2tiles temp.vrt" % self.input_file ) if input_dataset.GetRasterBand(1).DataType != gdal.GDT_Byte: exit_with_error( "Please convert this file to 8-bit and run gdal2tiles on the result.", "To scale pixel values you can use:\n" "gdal_translate -of VRT -ot Byte -scale %s temp.vrt\n" "then run:\n" "gdal2tiles temp.vrt" % self.input_file ) in_nodata = setup_no_data_values(input_dataset, self.options) if self.options.verbose: print("Preprocessed file:", "( %sP x %sL - %s bands)" % (input_dataset.RasterXSize, input_dataset.RasterYSize, input_dataset.RasterCount)) self.in_srs, self.in_srs_wkt = setup_input_srs(input_dataset, self.options) self.out_srs = setup_output_srs(self.in_srs, self.options) # If input and output reference systems are different, we reproject the input dataset into # the output reference system for easier manipulation self.warped_input_dataset = None if self.options.profile != 'raster': if not self.in_srs: exit_with_error( "Input file has unknown SRS.", "Use --s_srs EPSG:xyz (or similar) to provide source reference system.") if not has_georeference(input_dataset): exit_with_error( "There is no georeference - neither affine transformation (worldfile) " "nor GCPs. You can generate only 'raster' profile tiles.", "Either gdal2tiles with parameter -p 'raster' or use another GIS " "software for georeference e.g. gdal_transform -gcp / -a_ullr / -a_srs" ) if ((self.in_srs.ExportToProj4() != self.out_srs.ExportToProj4()) or (input_dataset.GetGCPCount() != 0)): self.warped_input_dataset = reproject_dataset( input_dataset, self.in_srs, self.out_srs) if in_nodata: self.warped_input_dataset = update_no_data_values( self.warped_input_dataset, in_nodata, options=self.options) else: self.warped_input_dataset = update_alpha_value_for_non_alpha_inputs( self.warped_input_dataset, options=self.options) if self.warped_input_dataset and self.options.verbose: print("Projected file:", "tiles.vrt", "( %sP x %sL - %s bands)" % ( self.warped_input_dataset.RasterXSize, self.warped_input_dataset.RasterYSize, self.warped_input_dataset.RasterCount)) if not self.warped_input_dataset: self.warped_input_dataset = input_dataset gdal.GetDriverByName('VRT').CreateCopy(self.tmp_vrt_filename, self.warped_input_dataset) # Get alpha band (either directly or from NODATA value) self.alphaband = self.warped_input_dataset.GetRasterBand(1).GetMaskBand() self.dataBandsCount = nb_data_bands(self.warped_input_dataset) # KML test self.isepsg4326 = False srs4326 = osr.SpatialReference() srs4326.ImportFromEPSG(4326) srs4326.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) if self.out_srs and srs4326.ExportToProj4() == self.out_srs.ExportToProj4(): self.isepsg4326 = True if self.kml is None: self.kml = True if self.kml and self.options.verbose: print("KML autotest OK!") if self.kml is None: self.kml = False # Read the georeference self.out_gt = self.warped_input_dataset.GetGeoTransform() # Test the size of the pixel # Report error in case rotation/skew is in geotransform (possible only in 'raster' profile) if (self.out_gt[2], self.out_gt[4]) != (0, 0): exit_with_error("Georeference of the raster contains rotation or skew. " "Such raster is not supported. Please use gdalwarp first.") # Here we expect: pixel is square, no rotation on the raster # Output Bounds - coordinates in the output SRS self.ominx = self.out_gt[0] self.omaxx = self.out_gt[0] + self.warped_input_dataset.RasterXSize * self.out_gt[1] self.omaxy = self.out_gt[3] self.ominy = self.out_gt[3] - self.warped_input_dataset.RasterYSize * self.out_gt[1] # Note: maybe round(x, 14) to avoid the gdal_translate behavior, when 0 becomes -1e-15 if self.options.verbose: print("Bounds (output srs):", round(self.ominx, 13), self.ominy, self.omaxx, self.omaxy) # Calculating ranges for tiles in different zoom levels if self.options.profile == 'mercator': self.mercator = GlobalMercator(tile_size=self.tile_size) # Function which generates SWNE in LatLong for given tile self.tileswne = self.mercator.TileLatLonBounds # Generate table with min max tile coordinates for all zoomlevels self.tminmax = list(range(0, MAXZOOMLEVEL)) for tz in range(0, MAXZOOMLEVEL): tminx, tminy = self.mercator.MetersToTile(self.ominx, self.ominy, tz) tmaxx, tmaxy = self.mercator.MetersToTile(self.omaxx, self.omaxy, tz) # crop tiles extending world limits (+-180,+-90) tminx, tminy = max(0, tminx), max(0, tminy) tmaxx, tmaxy = min(2**tz - 1, tmaxx), min(2**tz - 1, tmaxy) self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy) # TODO: Maps crossing 180E (Alaska?) # Get the minimal zoom level (map covers area equivalent to one tile) if self.tminz is None: self.tminz = self.mercator.ZoomForPixelSize( self.out_gt[1] * max(self.warped_input_dataset.RasterXSize, self.warped_input_dataset.RasterYSize) / float(self.tile_size)) # Get the maximal zoom level # (closest possible zoom level up on the resolution of raster) if self.tmaxz is None: self.tmaxz = self.mercator.ZoomForPixelSize(self.out_gt[1]) self.tmaxz = max(self.tminz, self.tmaxz) self.tminz = min(self.tminz, self.tmaxz) if self.options.verbose: print("Bounds (latlong):", self.mercator.MetersToLatLon(self.ominx, self.ominy), self.mercator.MetersToLatLon(self.omaxx, self.omaxy)) print('MinZoomLevel:', self.tminz) print("MaxZoomLevel:", self.tmaxz, "(", self.mercator.Resolution(self.tmaxz), ")") elif self.options.profile == 'geodetic': self.geodetic = GlobalGeodetic(self.options.tmscompatible, tile_size=self.tile_size) # Function which generates SWNE in LatLong for given tile self.tileswne = self.geodetic.TileLatLonBounds # Generate table with min max tile coordinates for all zoomlevels self.tminmax = list(range(0, MAXZOOMLEVEL)) for tz in range(0, MAXZOOMLEVEL): tminx, tminy = self.geodetic.LonLatToTile(self.ominx, self.ominy, tz) tmaxx, tmaxy = self.geodetic.LonLatToTile(self.omaxx, self.omaxy, tz) # crop tiles extending world limits (+-180,+-90) tminx, tminy = max(0, tminx), max(0, tminy) tmaxx, tmaxy = min(2**(tz + 1) - 1, tmaxx), min(2**tz - 1, tmaxy) self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy) # TODO: Maps crossing 180E (Alaska?) # Get the maximal zoom level # (closest possible zoom level up on the resolution of raster) if self.tminz is None: self.tminz = self.geodetic.ZoomForPixelSize( self.out_gt[1] * max(self.warped_input_dataset.RasterXSize, self.warped_input_dataset.RasterYSize) / float(self.tile_size)) # Get the maximal zoom level # (closest possible zoom level up on the resolution of raster) if self.tmaxz is None: self.tmaxz = self.geodetic.ZoomForPixelSize(self.out_gt[1]) self.tmaxz = max(self.tminz, self.tmaxz) self.tminz = min(self.tminz, self.tmaxz) if self.options.verbose: print("Bounds (latlong):", self.ominx, self.ominy, self.omaxx, self.omaxy) elif self.options.profile == 'raster': def log2(x): return math.log10(x) / math.log10(2) self.nativezoom = max(0, int( max(math.ceil(log2(self.warped_input_dataset.RasterXSize / float(self.tile_size))), math.ceil(log2(self.warped_input_dataset.RasterYSize / float(self.tile_size)))))) if self.options.verbose: print("Native zoom of the raster:", self.nativezoom) # Get the minimal zoom level (whole raster in one tile) if self.tminz is None: self.tminz = 0 # Get the maximal zoom level (native resolution of the raster) if self.tmaxz is None: self.tmaxz = self.nativezoom self.tmaxz = max(self.tminz, self.tmaxz) elif self.tmaxz > self.nativezoom: print('Clamping max zoom level to %d' % self.nativezoom) self.tmaxz = self.nativezoom # Generate table with min max tile coordinates for all zoomlevels self.tminmax = list(range(0, self.tmaxz + 1)) self.tsize = list(range(0, self.tmaxz + 1)) for tz in range(0, self.tmaxz + 1): tsize = 2.0**(self.nativezoom - tz) * self.tile_size tminx, tminy = 0, 0 tmaxx = int(math.ceil(self.warped_input_dataset.RasterXSize / tsize)) - 1 tmaxy = int(math.ceil(self.warped_input_dataset.RasterYSize / tsize)) - 1 self.tsize[tz] = math.ceil(tsize) self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy) # Function which generates SWNE in LatLong for given tile if self.kml and self.in_srs_wkt: ct = osr.CoordinateTransformation(self.in_srs, srs4326) def rastertileswne(x, y, z): pixelsizex = (2**(self.tmaxz - z) * self.out_gt[1]) # X-pixel size in level west = self.out_gt[0] + x * self.tile_size * pixelsizex east = west + self.tile_size * pixelsizex if self.options.xyz: north = self.omaxy - y * self.tile_size * pixelsizex south = north - self.tile_size * pixelsizex else: south = self.ominy + y * self.tile_size * pixelsizex north = south + self.tile_size * pixelsizex if not self.isepsg4326: # Transformation to EPSG:4326 (WGS84 datum) west, south = ct.TransformPoint(west, south)[:2] east, north = ct.TransformPoint(east, north)[:2] return south, west, north, east self.tileswne = rastertileswne else: self.tileswne = lambda x, y, z: (0, 0, 0, 0) # noqa else: tms = tmsMap[self.options.profile] # Function which generates SWNE in LatLong for given tile self.tileswne = None # not implemented # Generate table with min max tile coordinates for all zoomlevels self.tminmax = list(range(0, tms.level_count+1)) for tz in range(0, tms.level_count+1): tminx, tminy = tms.GeorefCoordToTileCoord(self.ominx, self.ominy, tz, self.tile_size) tmaxx, tmaxy = tms.GeorefCoordToTileCoord(self.omaxx, self.omaxy, tz, self.tile_size) tminx, tminy = max(0, tminx), max(0, tminy) tmaxx, tmaxy = min(tms.matrix_width * 2**tz - 1, tmaxx), min(tms.matrix_height * 2**tz - 1, tmaxy) self.tminmax[tz] = (tminx, tminy, tmaxx, tmaxy) # Get the minimal zoom level (map covers area equivalent to one tile) if self.tminz is None: self.tminz = tms.ZoomForPixelSize( self.out_gt[1] * max(self.warped_input_dataset.RasterXSize, self.warped_input_dataset.RasterYSize) / float(self.tile_size), self.tile_size) # Get the maximal zoom level # (closest possible zoom level up on the resolution of raster) if self.tmaxz is None: self.tmaxz = tms.ZoomForPixelSize(self.out_gt[1], self.tile_size) self.tmaxz = max(self.tminz, self.tmaxz) self.tminz = min(self.tminz, self.tmaxz) if self.options.verbose: print("Bounds (georef):", self.ominx, self.ominy, self.omaxx, self.omaxy) print('MinZoomLevel:', self.tminz) print("MaxZoomLevel:", self.tmaxz)
[ "def", "open_input", "(", "self", ")", "->", "None", ":", "gdal", ".", "AllRegister", "(", ")", "self", ".", "out_drv", "=", "gdal", ".", "GetDriverByName", "(", "self", ".", "tiledriver", ")", "self", ".", "mem_drv", "=", "gdal", ".", "GetDriverByName", "(", "'MEM'", ")", "if", "not", "self", ".", "out_drv", ":", "raise", "Exception", "(", "\"The '%s' driver was not found, is it available in this GDAL build?\"", "%", "self", ".", "tiledriver", ")", "if", "not", "self", ".", "mem_drv", ":", "raise", "Exception", "(", "\"The 'MEM' driver was not found, is it available in this GDAL build?\"", ")", "# Open the input file", "if", "self", ".", "input_file", ":", "input_dataset", ":", "gdal", ".", "Dataset", "=", "gdal", ".", "Open", "(", "self", ".", "input_file", ",", "gdal", ".", "GA_ReadOnly", ")", "else", ":", "raise", "Exception", "(", "\"No input file was specified\"", ")", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Input file:\"", ",", "\"( %sP x %sL - %s bands)\"", "%", "(", "input_dataset", ".", "RasterXSize", ",", "input_dataset", ".", "RasterYSize", ",", "input_dataset", ".", "RasterCount", ")", ")", "if", "not", "input_dataset", ":", "# Note: GDAL prints the ERROR message too", "exit_with_error", "(", "\"It is not possible to open the input file '%s'.\"", "%", "self", ".", "input_file", ")", "# Read metadata from the input file", "if", "input_dataset", ".", "RasterCount", "==", "0", ":", "exit_with_error", "(", "\"Input file '%s' has no raster band\"", "%", "self", ".", "input_file", ")", "if", "input_dataset", ".", "GetRasterBand", "(", "1", ")", ".", "GetRasterColorTable", "(", ")", ":", "exit_with_error", "(", "\"Please convert this file to RGB/RGBA and run gdal2tiles on the result.\"", ",", "\"From paletted file you can create RGBA file (temp.vrt) by:\\n\"", "\"gdal_translate -of vrt -expand rgba %s temp.vrt\\n\"", "\"then run:\\n\"", "\"gdal2tiles temp.vrt\"", "%", "self", ".", "input_file", ")", "if", "input_dataset", ".", "GetRasterBand", "(", "1", ")", ".", "DataType", "!=", "gdal", ".", "GDT_Byte", ":", "exit_with_error", "(", "\"Please convert this file to 8-bit and run gdal2tiles on the result.\"", ",", "\"To scale pixel values you can use:\\n\"", "\"gdal_translate -of VRT -ot Byte -scale %s temp.vrt\\n\"", "\"then run:\\n\"", "\"gdal2tiles temp.vrt\"", "%", "self", ".", "input_file", ")", "in_nodata", "=", "setup_no_data_values", "(", "input_dataset", ",", "self", ".", "options", ")", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Preprocessed file:\"", ",", "\"( %sP x %sL - %s bands)\"", "%", "(", "input_dataset", ".", "RasterXSize", ",", "input_dataset", ".", "RasterYSize", ",", "input_dataset", ".", "RasterCount", ")", ")", "self", ".", "in_srs", ",", "self", ".", "in_srs_wkt", "=", "setup_input_srs", "(", "input_dataset", ",", "self", ".", "options", ")", "self", ".", "out_srs", "=", "setup_output_srs", "(", "self", ".", "in_srs", ",", "self", ".", "options", ")", "# If input and output reference systems are different, we reproject the input dataset into", "# the output reference system for easier manipulation", "self", ".", "warped_input_dataset", "=", "None", "if", "self", ".", "options", ".", "profile", "!=", "'raster'", ":", "if", "not", "self", ".", "in_srs", ":", "exit_with_error", "(", "\"Input file has unknown SRS.\"", ",", "\"Use --s_srs EPSG:xyz (or similar) to provide source reference system.\"", ")", "if", "not", "has_georeference", "(", "input_dataset", ")", ":", "exit_with_error", "(", "\"There is no georeference - neither affine transformation (worldfile) \"", "\"nor GCPs. You can generate only 'raster' profile tiles.\"", ",", "\"Either gdal2tiles with parameter -p 'raster' or use another GIS \"", "\"software for georeference e.g. gdal_transform -gcp / -a_ullr / -a_srs\"", ")", "if", "(", "(", "self", ".", "in_srs", ".", "ExportToProj4", "(", ")", "!=", "self", ".", "out_srs", ".", "ExportToProj4", "(", ")", ")", "or", "(", "input_dataset", ".", "GetGCPCount", "(", ")", "!=", "0", ")", ")", ":", "self", ".", "warped_input_dataset", "=", "reproject_dataset", "(", "input_dataset", ",", "self", ".", "in_srs", ",", "self", ".", "out_srs", ")", "if", "in_nodata", ":", "self", ".", "warped_input_dataset", "=", "update_no_data_values", "(", "self", ".", "warped_input_dataset", ",", "in_nodata", ",", "options", "=", "self", ".", "options", ")", "else", ":", "self", ".", "warped_input_dataset", "=", "update_alpha_value_for_non_alpha_inputs", "(", "self", ".", "warped_input_dataset", ",", "options", "=", "self", ".", "options", ")", "if", "self", ".", "warped_input_dataset", "and", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Projected file:\"", ",", "\"tiles.vrt\"", ",", "\"( %sP x %sL - %s bands)\"", "%", "(", "self", ".", "warped_input_dataset", ".", "RasterXSize", ",", "self", ".", "warped_input_dataset", ".", "RasterYSize", ",", "self", ".", "warped_input_dataset", ".", "RasterCount", ")", ")", "if", "not", "self", ".", "warped_input_dataset", ":", "self", ".", "warped_input_dataset", "=", "input_dataset", "gdal", ".", "GetDriverByName", "(", "'VRT'", ")", ".", "CreateCopy", "(", "self", ".", "tmp_vrt_filename", ",", "self", ".", "warped_input_dataset", ")", "# Get alpha band (either directly or from NODATA value)", "self", ".", "alphaband", "=", "self", ".", "warped_input_dataset", ".", "GetRasterBand", "(", "1", ")", ".", "GetMaskBand", "(", ")", "self", ".", "dataBandsCount", "=", "nb_data_bands", "(", "self", ".", "warped_input_dataset", ")", "# KML test", "self", ".", "isepsg4326", "=", "False", "srs4326", "=", "osr", ".", "SpatialReference", "(", ")", "srs4326", ".", "ImportFromEPSG", "(", "4326", ")", "srs4326", ".", "SetAxisMappingStrategy", "(", "osr", ".", "OAMS_TRADITIONAL_GIS_ORDER", ")", "if", "self", ".", "out_srs", "and", "srs4326", ".", "ExportToProj4", "(", ")", "==", "self", ".", "out_srs", ".", "ExportToProj4", "(", ")", ":", "self", ".", "isepsg4326", "=", "True", "if", "self", ".", "kml", "is", "None", ":", "self", ".", "kml", "=", "True", "if", "self", ".", "kml", "and", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"KML autotest OK!\"", ")", "if", "self", ".", "kml", "is", "None", ":", "self", ".", "kml", "=", "False", "# Read the georeference", "self", ".", "out_gt", "=", "self", ".", "warped_input_dataset", ".", "GetGeoTransform", "(", ")", "# Test the size of the pixel", "# Report error in case rotation/skew is in geotransform (possible only in 'raster' profile)", "if", "(", "self", ".", "out_gt", "[", "2", "]", ",", "self", ".", "out_gt", "[", "4", "]", ")", "!=", "(", "0", ",", "0", ")", ":", "exit_with_error", "(", "\"Georeference of the raster contains rotation or skew. \"", "\"Such raster is not supported. Please use gdalwarp first.\"", ")", "# Here we expect: pixel is square, no rotation on the raster", "# Output Bounds - coordinates in the output SRS", "self", ".", "ominx", "=", "self", ".", "out_gt", "[", "0", "]", "self", ".", "omaxx", "=", "self", ".", "out_gt", "[", "0", "]", "+", "self", ".", "warped_input_dataset", ".", "RasterXSize", "*", "self", ".", "out_gt", "[", "1", "]", "self", ".", "omaxy", "=", "self", ".", "out_gt", "[", "3", "]", "self", ".", "ominy", "=", "self", ".", "out_gt", "[", "3", "]", "-", "self", ".", "warped_input_dataset", ".", "RasterYSize", "*", "self", ".", "out_gt", "[", "1", "]", "# Note: maybe round(x, 14) to avoid the gdal_translate behavior, when 0 becomes -1e-15", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Bounds (output srs):\"", ",", "round", "(", "self", ".", "ominx", ",", "13", ")", ",", "self", ".", "ominy", ",", "self", ".", "omaxx", ",", "self", ".", "omaxy", ")", "# Calculating ranges for tiles in different zoom levels", "if", "self", ".", "options", ".", "profile", "==", "'mercator'", ":", "self", ".", "mercator", "=", "GlobalMercator", "(", "tile_size", "=", "self", ".", "tile_size", ")", "# Function which generates SWNE in LatLong for given tile", "self", ".", "tileswne", "=", "self", ".", "mercator", ".", "TileLatLonBounds", "# Generate table with min max tile coordinates for all zoomlevels", "self", ".", "tminmax", "=", "list", "(", "range", "(", "0", ",", "MAXZOOMLEVEL", ")", ")", "for", "tz", "in", "range", "(", "0", ",", "MAXZOOMLEVEL", ")", ":", "tminx", ",", "tminy", "=", "self", ".", "mercator", ".", "MetersToTile", "(", "self", ".", "ominx", ",", "self", ".", "ominy", ",", "tz", ")", "tmaxx", ",", "tmaxy", "=", "self", ".", "mercator", ".", "MetersToTile", "(", "self", ".", "omaxx", ",", "self", ".", "omaxy", ",", "tz", ")", "# crop tiles extending world limits (+-180,+-90)", "tminx", ",", "tminy", "=", "max", "(", "0", ",", "tminx", ")", ",", "max", "(", "0", ",", "tminy", ")", "tmaxx", ",", "tmaxy", "=", "min", "(", "2", "**", "tz", "-", "1", ",", "tmaxx", ")", ",", "min", "(", "2", "**", "tz", "-", "1", ",", "tmaxy", ")", "self", ".", "tminmax", "[", "tz", "]", "=", "(", "tminx", ",", "tminy", ",", "tmaxx", ",", "tmaxy", ")", "# TODO: Maps crossing 180E (Alaska?)", "# Get the minimal zoom level (map covers area equivalent to one tile)", "if", "self", ".", "tminz", "is", "None", ":", "self", ".", "tminz", "=", "self", ".", "mercator", ".", "ZoomForPixelSize", "(", "self", ".", "out_gt", "[", "1", "]", "*", "max", "(", "self", ".", "warped_input_dataset", ".", "RasterXSize", ",", "self", ".", "warped_input_dataset", ".", "RasterYSize", ")", "/", "float", "(", "self", ".", "tile_size", ")", ")", "# Get the maximal zoom level", "# (closest possible zoom level up on the resolution of raster)", "if", "self", ".", "tmaxz", "is", "None", ":", "self", ".", "tmaxz", "=", "self", ".", "mercator", ".", "ZoomForPixelSize", "(", "self", ".", "out_gt", "[", "1", "]", ")", "self", ".", "tmaxz", "=", "max", "(", "self", ".", "tminz", ",", "self", ".", "tmaxz", ")", "self", ".", "tminz", "=", "min", "(", "self", ".", "tminz", ",", "self", ".", "tmaxz", ")", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Bounds (latlong):\"", ",", "self", ".", "mercator", ".", "MetersToLatLon", "(", "self", ".", "ominx", ",", "self", ".", "ominy", ")", ",", "self", ".", "mercator", ".", "MetersToLatLon", "(", "self", ".", "omaxx", ",", "self", ".", "omaxy", ")", ")", "print", "(", "'MinZoomLevel:'", ",", "self", ".", "tminz", ")", "print", "(", "\"MaxZoomLevel:\"", ",", "self", ".", "tmaxz", ",", "\"(\"", ",", "self", ".", "mercator", ".", "Resolution", "(", "self", ".", "tmaxz", ")", ",", "\")\"", ")", "elif", "self", ".", "options", ".", "profile", "==", "'geodetic'", ":", "self", ".", "geodetic", "=", "GlobalGeodetic", "(", "self", ".", "options", ".", "tmscompatible", ",", "tile_size", "=", "self", ".", "tile_size", ")", "# Function which generates SWNE in LatLong for given tile", "self", ".", "tileswne", "=", "self", ".", "geodetic", ".", "TileLatLonBounds", "# Generate table with min max tile coordinates for all zoomlevels", "self", ".", "tminmax", "=", "list", "(", "range", "(", "0", ",", "MAXZOOMLEVEL", ")", ")", "for", "tz", "in", "range", "(", "0", ",", "MAXZOOMLEVEL", ")", ":", "tminx", ",", "tminy", "=", "self", ".", "geodetic", ".", "LonLatToTile", "(", "self", ".", "ominx", ",", "self", ".", "ominy", ",", "tz", ")", "tmaxx", ",", "tmaxy", "=", "self", ".", "geodetic", ".", "LonLatToTile", "(", "self", ".", "omaxx", ",", "self", ".", "omaxy", ",", "tz", ")", "# crop tiles extending world limits (+-180,+-90)", "tminx", ",", "tminy", "=", "max", "(", "0", ",", "tminx", ")", ",", "max", "(", "0", ",", "tminy", ")", "tmaxx", ",", "tmaxy", "=", "min", "(", "2", "**", "(", "tz", "+", "1", ")", "-", "1", ",", "tmaxx", ")", ",", "min", "(", "2", "**", "tz", "-", "1", ",", "tmaxy", ")", "self", ".", "tminmax", "[", "tz", "]", "=", "(", "tminx", ",", "tminy", ",", "tmaxx", ",", "tmaxy", ")", "# TODO: Maps crossing 180E (Alaska?)", "# Get the maximal zoom level", "# (closest possible zoom level up on the resolution of raster)", "if", "self", ".", "tminz", "is", "None", ":", "self", ".", "tminz", "=", "self", ".", "geodetic", ".", "ZoomForPixelSize", "(", "self", ".", "out_gt", "[", "1", "]", "*", "max", "(", "self", ".", "warped_input_dataset", ".", "RasterXSize", ",", "self", ".", "warped_input_dataset", ".", "RasterYSize", ")", "/", "float", "(", "self", ".", "tile_size", ")", ")", "# Get the maximal zoom level", "# (closest possible zoom level up on the resolution of raster)", "if", "self", ".", "tmaxz", "is", "None", ":", "self", ".", "tmaxz", "=", "self", ".", "geodetic", ".", "ZoomForPixelSize", "(", "self", ".", "out_gt", "[", "1", "]", ")", "self", ".", "tmaxz", "=", "max", "(", "self", ".", "tminz", ",", "self", ".", "tmaxz", ")", "self", ".", "tminz", "=", "min", "(", "self", ".", "tminz", ",", "self", ".", "tmaxz", ")", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Bounds (latlong):\"", ",", "self", ".", "ominx", ",", "self", ".", "ominy", ",", "self", ".", "omaxx", ",", "self", ".", "omaxy", ")", "elif", "self", ".", "options", ".", "profile", "==", "'raster'", ":", "def", "log2", "(", "x", ")", ":", "return", "math", ".", "log10", "(", "x", ")", "/", "math", ".", "log10", "(", "2", ")", "self", ".", "nativezoom", "=", "max", "(", "0", ",", "int", "(", "max", "(", "math", ".", "ceil", "(", "log2", "(", "self", ".", "warped_input_dataset", ".", "RasterXSize", "/", "float", "(", "self", ".", "tile_size", ")", ")", ")", ",", "math", ".", "ceil", "(", "log2", "(", "self", ".", "warped_input_dataset", ".", "RasterYSize", "/", "float", "(", "self", ".", "tile_size", ")", ")", ")", ")", ")", ")", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Native zoom of the raster:\"", ",", "self", ".", "nativezoom", ")", "# Get the minimal zoom level (whole raster in one tile)", "if", "self", ".", "tminz", "is", "None", ":", "self", ".", "tminz", "=", "0", "# Get the maximal zoom level (native resolution of the raster)", "if", "self", ".", "tmaxz", "is", "None", ":", "self", ".", "tmaxz", "=", "self", ".", "nativezoom", "self", ".", "tmaxz", "=", "max", "(", "self", ".", "tminz", ",", "self", ".", "tmaxz", ")", "elif", "self", ".", "tmaxz", ">", "self", ".", "nativezoom", ":", "print", "(", "'Clamping max zoom level to %d'", "%", "self", ".", "nativezoom", ")", "self", ".", "tmaxz", "=", "self", ".", "nativezoom", "# Generate table with min max tile coordinates for all zoomlevels", "self", ".", "tminmax", "=", "list", "(", "range", "(", "0", ",", "self", ".", "tmaxz", "+", "1", ")", ")", "self", ".", "tsize", "=", "list", "(", "range", "(", "0", ",", "self", ".", "tmaxz", "+", "1", ")", ")", "for", "tz", "in", "range", "(", "0", ",", "self", ".", "tmaxz", "+", "1", ")", ":", "tsize", "=", "2.0", "**", "(", "self", ".", "nativezoom", "-", "tz", ")", "*", "self", ".", "tile_size", "tminx", ",", "tminy", "=", "0", ",", "0", "tmaxx", "=", "int", "(", "math", ".", "ceil", "(", "self", ".", "warped_input_dataset", ".", "RasterXSize", "/", "tsize", ")", ")", "-", "1", "tmaxy", "=", "int", "(", "math", ".", "ceil", "(", "self", ".", "warped_input_dataset", ".", "RasterYSize", "/", "tsize", ")", ")", "-", "1", "self", ".", "tsize", "[", "tz", "]", "=", "math", ".", "ceil", "(", "tsize", ")", "self", ".", "tminmax", "[", "tz", "]", "=", "(", "tminx", ",", "tminy", ",", "tmaxx", ",", "tmaxy", ")", "# Function which generates SWNE in LatLong for given tile", "if", "self", ".", "kml", "and", "self", ".", "in_srs_wkt", ":", "ct", "=", "osr", ".", "CoordinateTransformation", "(", "self", ".", "in_srs", ",", "srs4326", ")", "def", "rastertileswne", "(", "x", ",", "y", ",", "z", ")", ":", "pixelsizex", "=", "(", "2", "**", "(", "self", ".", "tmaxz", "-", "z", ")", "*", "self", ".", "out_gt", "[", "1", "]", ")", "# X-pixel size in level", "west", "=", "self", ".", "out_gt", "[", "0", "]", "+", "x", "*", "self", ".", "tile_size", "*", "pixelsizex", "east", "=", "west", "+", "self", ".", "tile_size", "*", "pixelsizex", "if", "self", ".", "options", ".", "xyz", ":", "north", "=", "self", ".", "omaxy", "-", "y", "*", "self", ".", "tile_size", "*", "pixelsizex", "south", "=", "north", "-", "self", ".", "tile_size", "*", "pixelsizex", "else", ":", "south", "=", "self", ".", "ominy", "+", "y", "*", "self", ".", "tile_size", "*", "pixelsizex", "north", "=", "south", "+", "self", ".", "tile_size", "*", "pixelsizex", "if", "not", "self", ".", "isepsg4326", ":", "# Transformation to EPSG:4326 (WGS84 datum)", "west", ",", "south", "=", "ct", ".", "TransformPoint", "(", "west", ",", "south", ")", "[", ":", "2", "]", "east", ",", "north", "=", "ct", ".", "TransformPoint", "(", "east", ",", "north", ")", "[", ":", "2", "]", "return", "south", ",", "west", ",", "north", ",", "east", "self", ".", "tileswne", "=", "rastertileswne", "else", ":", "self", ".", "tileswne", "=", "lambda", "x", ",", "y", ",", "z", ":", "(", "0", ",", "0", ",", "0", ",", "0", ")", "# noqa", "else", ":", "tms", "=", "tmsMap", "[", "self", ".", "options", ".", "profile", "]", "# Function which generates SWNE in LatLong for given tile", "self", ".", "tileswne", "=", "None", "# not implemented", "# Generate table with min max tile coordinates for all zoomlevels", "self", ".", "tminmax", "=", "list", "(", "range", "(", "0", ",", "tms", ".", "level_count", "+", "1", ")", ")", "for", "tz", "in", "range", "(", "0", ",", "tms", ".", "level_count", "+", "1", ")", ":", "tminx", ",", "tminy", "=", "tms", ".", "GeorefCoordToTileCoord", "(", "self", ".", "ominx", ",", "self", ".", "ominy", ",", "tz", ",", "self", ".", "tile_size", ")", "tmaxx", ",", "tmaxy", "=", "tms", ".", "GeorefCoordToTileCoord", "(", "self", ".", "omaxx", ",", "self", ".", "omaxy", ",", "tz", ",", "self", ".", "tile_size", ")", "tminx", ",", "tminy", "=", "max", "(", "0", ",", "tminx", ")", ",", "max", "(", "0", ",", "tminy", ")", "tmaxx", ",", "tmaxy", "=", "min", "(", "tms", ".", "matrix_width", "*", "2", "**", "tz", "-", "1", ",", "tmaxx", ")", ",", "min", "(", "tms", ".", "matrix_height", "*", "2", "**", "tz", "-", "1", ",", "tmaxy", ")", "self", ".", "tminmax", "[", "tz", "]", "=", "(", "tminx", ",", "tminy", ",", "tmaxx", ",", "tmaxy", ")", "# Get the minimal zoom level (map covers area equivalent to one tile)", "if", "self", ".", "tminz", "is", "None", ":", "self", ".", "tminz", "=", "tms", ".", "ZoomForPixelSize", "(", "self", ".", "out_gt", "[", "1", "]", "*", "max", "(", "self", ".", "warped_input_dataset", ".", "RasterXSize", ",", "self", ".", "warped_input_dataset", ".", "RasterYSize", ")", "/", "float", "(", "self", ".", "tile_size", ")", ",", "self", ".", "tile_size", ")", "# Get the maximal zoom level", "# (closest possible zoom level up on the resolution of raster)", "if", "self", ".", "tmaxz", "is", "None", ":", "self", ".", "tmaxz", "=", "tms", ".", "ZoomForPixelSize", "(", "self", ".", "out_gt", "[", "1", "]", ",", "self", ".", "tile_size", ")", "self", ".", "tmaxz", "=", "max", "(", "self", ".", "tminz", ",", "self", ".", "tmaxz", ")", "self", ".", "tminz", "=", "min", "(", "self", ".", "tminz", ",", "self", ".", "tmaxz", ")", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Bounds (georef):\"", ",", "self", ".", "ominx", ",", "self", ".", "ominy", ",", "self", ".", "omaxx", ",", "self", ".", "omaxy", ")", "print", "(", "'MinZoomLevel:'", ",", "self", ".", "tminz", ")", "print", "(", "\"MaxZoomLevel:\"", ",", "self", ".", "tmaxz", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/gdal-utils/osgeo_utils/gdal2tiles.py#L1650-L1979
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
Geometry3D.withinDistance
(self, other, tol)
return _robotsim.Geometry3D_withinDistance(self, other, tol)
withinDistance(Geometry3D self, Geometry3D other, double tol) -> bool Returns true if this geometry is within distance tol to other.
withinDistance(Geometry3D self, Geometry3D other, double tol) -> bool
[ "withinDistance", "(", "Geometry3D", "self", "Geometry3D", "other", "double", "tol", ")", "-", ">", "bool" ]
def withinDistance(self, other, tol): """ withinDistance(Geometry3D self, Geometry3D other, double tol) -> bool Returns true if this geometry is within distance tol to other. """ return _robotsim.Geometry3D_withinDistance(self, other, tol)
[ "def", "withinDistance", "(", "self", ",", "other", ",", "tol", ")", ":", "return", "_robotsim", ".", "Geometry3D_withinDistance", "(", "self", ",", "other", ",", "tol", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L2322-L2331
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Node/__init__.py
python
Node.reset_executor
(self)
Remove cached executor; forces recompute when needed.
Remove cached executor; forces recompute when needed.
[ "Remove", "cached", "executor", ";", "forces", "recompute", "when", "needed", "." ]
def reset_executor(self): "Remove cached executor; forces recompute when needed." try: delattr(self, 'executor') except AttributeError: pass
[ "def", "reset_executor", "(", "self", ")", ":", "try", ":", "delattr", "(", "self", ",", "'executor'", ")", "except", "AttributeError", ":", "pass" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/__init__.py#L667-L672
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
RasterAttributeTable.GetLinearBinning
(self, *args)
return _gdal.RasterAttributeTable_GetLinearBinning(self, *args)
r"""GetLinearBinning(RasterAttributeTable self) -> bool
r"""GetLinearBinning(RasterAttributeTable self) -> bool
[ "r", "GetLinearBinning", "(", "RasterAttributeTable", "self", ")", "-", ">", "bool" ]
def GetLinearBinning(self, *args): r"""GetLinearBinning(RasterAttributeTable self) -> bool""" return _gdal.RasterAttributeTable_GetLinearBinning(self, *args)
[ "def", "GetLinearBinning", "(", "self", ",", "*", "args", ")", ":", "return", "_gdal", ".", "RasterAttributeTable_GetLinearBinning", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3870-L3872
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/image/image.py
python
ImageIter.postprocess_data
(self, datum)
return nd.transpose(datum, axes=(2, 0, 1))
Final postprocessing step before image is loaded into the batch.
Final postprocessing step before image is loaded into the batch.
[ "Final", "postprocessing", "step", "before", "image", "is", "loaded", "into", "the", "batch", "." ]
def postprocess_data(self, datum): """Final postprocessing step before image is loaded into the batch.""" return nd.transpose(datum, axes=(2, 0, 1))
[ "def", "postprocess_data", "(", "self", ",", "datum", ")", ":", "return", "nd", ".", "transpose", "(", "datum", ",", "axes", "=", "(", "2", ",", "0", ",", "1", ")", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/image/image.py#L1242-L1244
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py
python
splitattr
(url)
return words[0], words[1:]
splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].
splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].
[ "splitattr", "(", "/", "path", ";", "attr1", "=", "value1", ";", "attr2", "=", "value2", ";", "...", ")", "-", ">", "/", "path", "[", "attr1", "=", "value1", "attr2", "=", "value2", "...", "]", "." ]
def splitattr(url): """splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].""" words = url.split(';') return words[0], words[1:]
[ "def", "splitattr", "(", "url", ")", ":", "words", "=", "url", ".", "split", "(", "';'", ")", "return", "words", "[", "0", "]", ",", "words", "[", "1", ":", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py#L1177-L1181
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
Duration.ToTimedelta
(self)
return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND))
Converts Duration to timedelta.
Converts Duration to timedelta.
[ "Converts", "Duration", "to", "timedelta", "." ]
def ToTimedelta(self): """Converts Duration to timedelta.""" return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND))
[ "def", "ToTimedelta", "(", "self", ")", ":", "return", "timedelta", "(", "seconds", "=", "self", ".", "seconds", ",", "microseconds", "=", "_RoundTowardZero", "(", "self", ".", "nanos", ",", "_NANOS_PER_MICROSECOND", ")", ")" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L346-L350
Manu343726/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
reference/cindex.py
python
SourceRange.__contains__
(self, other)
return False
Useful to detect the Token/Lexer bug
Useful to detect the Token/Lexer bug
[ "Useful", "to", "detect", "the", "Token", "/", "Lexer", "bug" ]
def __contains__(self, other): """Useful to detect the Token/Lexer bug""" if not isinstance(other, SourceLocation): return False if other.file is None and self.start.file is None: pass elif ( self.start.file.name != other.file.name or other.file.name != self.end.file.name): # same file name return False # same file, in between lines if self.start.line < other.line < self.end.line: return True elif self.start.line == other.line: # same file first line if self.start.column <= other.column: return True elif other.line == self.end.line: # same file last line if other.column <= self.end.column: return True return False
[ "def", "__contains__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "SourceLocation", ")", ":", "return", "False", "if", "other", ".", "file", "is", "None", "and", "self", ".", "start", ".", "file", "is", "None", ":", "pass", "elif", "(", "self", ".", "start", ".", "file", ".", "name", "!=", "other", ".", "file", ".", "name", "or", "other", ".", "file", ".", "name", "!=", "self", ".", "end", ".", "file", ".", "name", ")", ":", "# same file name", "return", "False", "# same file, in between lines", "if", "self", ".", "start", ".", "line", "<", "other", ".", "line", "<", "self", ".", "end", ".", "line", ":", "return", "True", "elif", "self", ".", "start", ".", "line", "==", "other", ".", "line", ":", "# same file first line", "if", "self", ".", "start", ".", "column", "<=", "other", ".", "column", ":", "return", "True", "elif", "other", ".", "line", "==", "self", ".", "end", ".", "line", ":", "# same file last line", "if", "other", ".", "column", "<=", "self", ".", "end", ".", "column", ":", "return", "True", "return", "False" ]
https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L269-L290
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.SetFoldExpanded
(*args, **kwargs)
return _stc.StyledTextCtrl_SetFoldExpanded(*args, **kwargs)
SetFoldExpanded(self, int line, bool expanded) Show the children of a header line.
SetFoldExpanded(self, int line, bool expanded)
[ "SetFoldExpanded", "(", "self", "int", "line", "bool", "expanded", ")" ]
def SetFoldExpanded(*args, **kwargs): """ SetFoldExpanded(self, int line, bool expanded) Show the children of a header line. """ return _stc.StyledTextCtrl_SetFoldExpanded(*args, **kwargs)
[ "def", "SetFoldExpanded", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetFoldExpanded", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L3958-L3964
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/pytables.py
python
Table.get_attrs
(self)
retrieve our attributes
retrieve our attributes
[ "retrieve", "our", "attributes" ]
def get_attrs(self): """ retrieve our attributes """ self.non_index_axes = getattr( self.attrs, 'non_index_axes', None) or [] self.data_columns = getattr( self.attrs, 'data_columns', None) or [] self.info = getattr( self.attrs, 'info', None) or dict() self.nan_rep = getattr(self.attrs, 'nan_rep', None) self.encoding = _ensure_encoding( getattr(self.attrs, 'encoding', None)) self.errors = _ensure_decoded(getattr(self.attrs, 'errors', 'strict')) self.levels = getattr( self.attrs, 'levels', None) or [] self.index_axes = [ a.infer(self) for a in self.indexables if a.is_an_indexable ] self.values_axes = [ a.infer(self) for a in self.indexables if not a.is_an_indexable ] self.metadata = getattr( self.attrs, 'metadata', None) or []
[ "def", "get_attrs", "(", "self", ")", ":", "self", ".", "non_index_axes", "=", "getattr", "(", "self", ".", "attrs", ",", "'non_index_axes'", ",", "None", ")", "or", "[", "]", "self", ".", "data_columns", "=", "getattr", "(", "self", ".", "attrs", ",", "'data_columns'", ",", "None", ")", "or", "[", "]", "self", ".", "info", "=", "getattr", "(", "self", ".", "attrs", ",", "'info'", ",", "None", ")", "or", "dict", "(", ")", "self", ".", "nan_rep", "=", "getattr", "(", "self", ".", "attrs", ",", "'nan_rep'", ",", "None", ")", "self", ".", "encoding", "=", "_ensure_encoding", "(", "getattr", "(", "self", ".", "attrs", ",", "'encoding'", ",", "None", ")", ")", "self", ".", "errors", "=", "_ensure_decoded", "(", "getattr", "(", "self", ".", "attrs", ",", "'errors'", ",", "'strict'", ")", ")", "self", ".", "levels", "=", "getattr", "(", "self", ".", "attrs", ",", "'levels'", ",", "None", ")", "or", "[", "]", "self", ".", "index_axes", "=", "[", "a", ".", "infer", "(", "self", ")", "for", "a", "in", "self", ".", "indexables", "if", "a", ".", "is_an_indexable", "]", "self", ".", "values_axes", "=", "[", "a", ".", "infer", "(", "self", ")", "for", "a", "in", "self", ".", "indexables", "if", "not", "a", ".", "is_an_indexable", "]", "self", ".", "metadata", "=", "getattr", "(", "self", ".", "attrs", ",", "'metadata'", ",", "None", ")", "or", "[", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L3280-L3301
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/ops.py
python
reset_default_graph
()
Clears the default graph stack and resets the global default graph. NOTE: The default graph is a property of the current thread. This function applies only to the current thread. Calling this function while a `tf.Session` or `tf.InteractiveSession` is active will result in undefined behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects after calling this function will result in undefined behavior.
Clears the default graph stack and resets the global default graph.
[ "Clears", "the", "default", "graph", "stack", "and", "resets", "the", "global", "default", "graph", "." ]
def reset_default_graph(): """Clears the default graph stack and resets the global default graph. NOTE: The default graph is a property of the current thread. This function applies only to the current thread. Calling this function while a `tf.Session` or `tf.InteractiveSession` is active will result in undefined behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects after calling this function will result in undefined behavior. """ _default_graph_stack.reset()
[ "def", "reset_default_graph", "(", ")", ":", "_default_graph_stack", ".", "reset", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L3724-L3733
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/tensor_shape.py
python
TensorShape.assert_is_compatible_with
(self, other)
Raises exception if `self` and `other` do not represent the same shape. This method can be used to assert that there exists a shape that both `self` and `other` represent. Args: other: Another TensorShape. Raises: ValueError: If `self` and `other` do not represent the same shape.
Raises exception if `self` and `other` do not represent the same shape.
[ "Raises", "exception", "if", "self", "and", "other", "do", "not", "represent", "the", "same", "shape", "." ]
def assert_is_compatible_with(self, other): """Raises exception if `self` and `other` do not represent the same shape. This method can be used to assert that there exists a shape that both `self` and `other` represent. Args: other: Another TensorShape. Raises: ValueError: If `self` and `other` do not represent the same shape. """ if not self.is_compatible_with(other): raise ValueError("Shapes %s and %s are incompatible" % (self, other))
[ "def", "assert_is_compatible_with", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_compatible_with", "(", "other", ")", ":", "raise", "ValueError", "(", "\"Shapes %s and %s are incompatible\"", "%", "(", "self", ",", "other", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L728-L741
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/Chem/MolStandardize/standardize.py
python
enumerate_tautomers_smiles
(smiles)
return {Chem.MolToSmiles(m, isomericSmiles=True) for m in tautomers}
Return a set of tautomers as SMILES strings, given a SMILES string. :param smiles: A SMILES string. :returns: A set containing SMILES strings for every possible tautomer. :rtype: set of strings.
Return a set of tautomers as SMILES strings, given a SMILES string.
[ "Return", "a", "set", "of", "tautomers", "as", "SMILES", "strings", "given", "a", "SMILES", "string", "." ]
def enumerate_tautomers_smiles(smiles): """Return a set of tautomers as SMILES strings, given a SMILES string. :param smiles: A SMILES string. :returns: A set containing SMILES strings for every possible tautomer. :rtype: set of strings. """ # Skip sanitize as standardize does this anyway mol = Chem.MolFromSmiles(smiles, sanitize=False) mol = Standardizer().standardize(mol) tautomers = TautomerEnumerator().enumerate(mol) return {Chem.MolToSmiles(m, isomericSmiles=True) for m in tautomers}
[ "def", "enumerate_tautomers_smiles", "(", "smiles", ")", ":", "# Skip sanitize as standardize does this anyway", "mol", "=", "Chem", ".", "MolFromSmiles", "(", "smiles", ",", "sanitize", "=", "False", ")", "mol", "=", "Standardizer", "(", ")", ".", "standardize", "(", "mol", ")", "tautomers", "=", "TautomerEnumerator", "(", ")", ".", "enumerate", "(", "mol", ")", "return", "{", "Chem", ".", "MolToSmiles", "(", "m", ",", "isomericSmiles", "=", "True", ")", "for", "m", "in", "tautomers", "}" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/MolStandardize/standardize.py#L310-L321
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
FileSystemHandler.GetProtocol
(*args, **kwargs)
return _core_.FileSystemHandler_GetProtocol(*args, **kwargs)
GetProtocol(String location) -> String
GetProtocol(String location) -> String
[ "GetProtocol", "(", "String", "location", ")", "-", ">", "String" ]
def GetProtocol(*args, **kwargs): """GetProtocol(String location) -> String""" return _core_.FileSystemHandler_GetProtocol(*args, **kwargs)
[ "def", "GetProtocol", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "FileSystemHandler_GetProtocol", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L2360-L2362
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/misc.py
python
dist_in_usersite
(dist)
return dist_location(dist).startswith(normalize_path(user_site))
Return True if given Distribution is installed in user site.
[]
def dist_in_usersite(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in user site. """ return dist_location(dist).startswith(normalize_path(user_site))
[ "def", "dist_in_usersite", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "return", "dist_location", "(", "dist", ")", ".", "startswith", "(", "normalize_path", "(", "user_site", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/misc.py#L767-L777
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py
python
_AppendFiltersForMSBuild
(parent_filter_name, sources, extension_to_rule_name, filter_group, source_group)
Creates the list of filters and sources to be added in the filter file. Args: parent_filter_name: The name of the filter under which the sources are found. sources: The hierarchy of filters and sources to process. extension_to_rule_name: A dictionary mapping file extensions to rules. filter_group: The list to which filter entries will be appended. source_group: The list to which source entries will be appeneded.
Creates the list of filters and sources to be added in the filter file.
[ "Creates", "the", "list", "of", "filters", "and", "sources", "to", "be", "added", "in", "the", "filter", "file", "." ]
def _AppendFiltersForMSBuild(parent_filter_name, sources, extension_to_rule_name, filter_group, source_group): """Creates the list of filters and sources to be added in the filter file. Args: parent_filter_name: The name of the filter under which the sources are found. sources: The hierarchy of filters and sources to process. extension_to_rule_name: A dictionary mapping file extensions to rules. filter_group: The list to which filter entries will be appended. source_group: The list to which source entries will be appeneded. """ for source in sources: if isinstance(source, MSVSProject.Filter): # We have a sub-filter. Create the name of that sub-filter. if not parent_filter_name: filter_name = source.name else: filter_name = '%s\\%s' % (parent_filter_name, source.name) # Add the filter to the group. filter_group.append( ['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]]) # Recurse and add its dependents. _AppendFiltersForMSBuild(filter_name, source.contents, extension_to_rule_name, filter_group, source_group) else: # It's a source. Create a source entry. _, element = _MapFileToMsBuildSourceType(source, extension_to_rule_name) source_entry = [element, {'Include': source}] # Specify the filter it is part of, if any. if parent_filter_name: source_entry.append(['Filter', parent_filter_name]) source_group.append(source_entry)
[ "def", "_AppendFiltersForMSBuild", "(", "parent_filter_name", ",", "sources", ",", "extension_to_rule_name", ",", "filter_group", ",", "source_group", ")", ":", "for", "source", "in", "sources", ":", "if", "isinstance", "(", "source", ",", "MSVSProject", ".", "Filter", ")", ":", "# We have a sub-filter. Create the name of that sub-filter.", "if", "not", "parent_filter_name", ":", "filter_name", "=", "source", ".", "name", "else", ":", "filter_name", "=", "'%s\\\\%s'", "%", "(", "parent_filter_name", ",", "source", ".", "name", ")", "# Add the filter to the group.", "filter_group", ".", "append", "(", "[", "'Filter'", ",", "{", "'Include'", ":", "filter_name", "}", ",", "[", "'UniqueIdentifier'", ",", "MSVSNew", ".", "MakeGuid", "(", "source", ".", "name", ")", "]", "]", ")", "# Recurse and add its dependents.", "_AppendFiltersForMSBuild", "(", "filter_name", ",", "source", ".", "contents", ",", "extension_to_rule_name", ",", "filter_group", ",", "source_group", ")", "else", ":", "# It's a source. Create a source entry.", "_", ",", "element", "=", "_MapFileToMsBuildSourceType", "(", "source", ",", "extension_to_rule_name", ")", "source_entry", "=", "[", "element", ",", "{", "'Include'", ":", "source", "}", "]", "# Specify the filter it is part of, if any.", "if", "parent_filter_name", ":", "source_entry", ".", "append", "(", "[", "'Filter'", ",", "parent_filter_name", "]", ")", "source_group", ".", "append", "(", "source_entry", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L1910-L1945
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/util.py
python
Substituter._SubFragment
(self, fragment)
return fragment
Utility function for Substitute. Performs a simple substitution if the fragment is exactly of the form [message_name]. Args: fragment: A simple string. Returns: A string with the substitution done.
Utility function for Substitute.
[ "Utility", "function", "for", "Substitute", "." ]
def _SubFragment(self, fragment): '''Utility function for Substitute. Performs a simple substitution if the fragment is exactly of the form [message_name]. Args: fragment: A simple string. Returns: A string with the substitution done. ''' if len(fragment) > 2 and fragment[0] == '[' and fragment[-1] == ']': sub = self.substitutions_.get(fragment[1:-1], None) if sub is not None: return sub return fragment
[ "def", "_SubFragment", "(", "self", ",", "fragment", ")", ":", "if", "len", "(", "fragment", ")", ">", "2", "and", "fragment", "[", "0", "]", "==", "'['", "and", "fragment", "[", "-", "1", "]", "==", "']'", ":", "sub", "=", "self", ".", "substitutions_", ".", "get", "(", "fragment", "[", "1", ":", "-", "1", "]", ",", "None", ")", "if", "sub", "is", "not", "None", ":", "return", "sub", "return", "fragment" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/util.py#L568-L584
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/tools/quantization/calibrate.py
python
PercentileCalibrater.__init__
(self, model, op_types_to_calibrate=[], augmented_model_path='augmented_model.onnx', method='percentile', num_bins=2048, percentile=99.999)
:param model: ONNX model to calibrate. It can be a ModelProto or a model path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param method: A string. One of ['entropy', 'percentile']. :param num_quantized_bins: number of quantized bins. Default 128. :param percentile: A float number between [0, 100]. Default 99.99.
:param model: ONNX model to calibrate. It can be a ModelProto or a model path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param method: A string. One of ['entropy', 'percentile']. :param num_quantized_bins: number of quantized bins. Default 128. :param percentile: A float number between [0, 100]. Default 99.99.
[ ":", "param", "model", ":", "ONNX", "model", "to", "calibrate", ".", "It", "can", "be", "a", "ModelProto", "or", "a", "model", "path", ":", "param", "op_types_to_calibrate", ":", "operator", "types", "to", "calibrate", ".", "By", "default", "calibrate", "all", "the", "float32", "/", "float16", "tensors", ".", ":", "param", "augmented_model_path", ":", "save", "augmented", "model", "to", "this", "path", ".", ":", "param", "method", ":", "A", "string", ".", "One", "of", "[", "entropy", "percentile", "]", ".", ":", "param", "num_quantized_bins", ":", "number", "of", "quantized", "bins", ".", "Default", "128", ".", ":", "param", "percentile", ":", "A", "float", "number", "between", "[", "0", "100", "]", ".", "Default", "99", ".", "99", "." ]
def __init__(self, model, op_types_to_calibrate=[], augmented_model_path='augmented_model.onnx', method='percentile', num_bins=2048, percentile=99.999): ''' :param model: ONNX model to calibrate. It can be a ModelProto or a model path :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors. :param augmented_model_path: save augmented model to this path. :param method: A string. One of ['entropy', 'percentile']. :param num_quantized_bins: number of quantized bins. Default 128. :param percentile: A float number between [0, 100]. Default 99.99. ''' super(PercentileCalibrater, self).__init__(model, op_types_to_calibrate, augmented_model_path, method=method, num_bins=num_bins, percentile=percentile)
[ "def", "__init__", "(", "self", ",", "model", ",", "op_types_to_calibrate", "=", "[", "]", ",", "augmented_model_path", "=", "'augmented_model.onnx'", ",", "method", "=", "'percentile'", ",", "num_bins", "=", "2048", ",", "percentile", "=", "99.999", ")", ":", "super", "(", "PercentileCalibrater", ",", "self", ")", ".", "__init__", "(", "model", ",", "op_types_to_calibrate", ",", "augmented_model_path", ",", "method", "=", "method", ",", "num_bins", "=", "num_bins", ",", "percentile", "=", "percentile", ")" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/quantization/calibrate.py#L389-L406
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
samples/networking/05-small-chat/message.py
python
Message.b_sendText
(self, messageText)
Function which combines the local and distributed functionality, so the sendText and d_sendText functions are called. The b_ suffix stands for both
Function which combines the local and distributed functionality, so the sendText and d_sendText functions are called. The b_ suffix stands for both
[ "Function", "which", "combines", "the", "local", "and", "distributed", "functionality", "so", "the", "sendText", "and", "d_sendText", "functions", "are", "called", ".", "The", "b_", "suffix", "stands", "for", "both" ]
def b_sendText(self, messageText): """Function which combines the local and distributed functionality, so the sendText and d_sendText functions are called. The b_ suffix stands for both""" self.sendText(messageText) self.d_sendText(messageText)
[ "def", "b_sendText", "(", "self", ",", "messageText", ")", ":", "self", ".", "sendText", "(", "messageText", ")", "self", ".", "d_sendText", "(", "messageText", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/samples/networking/05-small-chat/message.py#L20-L25
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/CoSimulationApplication/python_scripts/factories/coupling_operation_factory.py
python
CreateCouplingOperation
(coupling_operation_settings, *args)
return base_factory.Create(coupling_operation_settings, [*args], "KratosMultiphysics.CoSimulationApplication.coupling_operations")
This function creates and returns the Coupling Operation used for CoSimulation
This function creates and returns the Coupling Operation used for CoSimulation
[ "This", "function", "creates", "and", "returns", "the", "Coupling", "Operation", "used", "for", "CoSimulation" ]
def CreateCouplingOperation(coupling_operation_settings, *args): """This function creates and returns the Coupling Operation used for CoSimulation""" return base_factory.Create(coupling_operation_settings, [*args], "KratosMultiphysics.CoSimulationApplication.coupling_operations")
[ "def", "CreateCouplingOperation", "(", "coupling_operation_settings", ",", "*", "args", ")", ":", "return", "base_factory", ".", "Create", "(", "coupling_operation_settings", ",", "[", "*", "args", "]", ",", "\"KratosMultiphysics.CoSimulationApplication.coupling_operations\"", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/CoSimulationApplication/python_scripts/factories/coupling_operation_factory.py#L3-L5
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/server/dispatcher.py
python
DispatcherWin32dbg._HandleException_
(self)
Invoke the debugger post mortem capability
Invoke the debugger post mortem capability
[ "Invoke", "the", "debugger", "post", "mortem", "capability" ]
def _HandleException_(self): """ Invoke the debugger post mortem capability """ # Save details away. typ, val, tb = exc_info() #import pywin.debugger, pywin.debugger.dbgcon debug = 0 try: raise typ(val) except Exception: # AARG - What is this Exception??? # Use some inside knowledge to borrow a Debugger option which dictates if we # stop at "expected" exceptions. debug = pywin.debugger.GetDebugger().get_option(pywin.debugger.dbgcon.OPT_STOP_EXCEPTIONS) except: debug = 1 if debug: try: pywin.debugger.post_mortem(tb, typ, val) # The original exception except: traceback.print_exc() # But still raise it. del tb raise
[ "def", "_HandleException_", "(", "self", ")", ":", "# Save details away.", "typ", ",", "val", ",", "tb", "=", "exc_info", "(", ")", "#import pywin.debugger, pywin.debugger.dbgcon", "debug", "=", "0", "try", ":", "raise", "typ", "(", "val", ")", "except", "Exception", ":", "# AARG - What is this Exception???", "# Use some inside knowledge to borrow a Debugger option which dictates if we", "# stop at \"expected\" exceptions.", "debug", "=", "pywin", ".", "debugger", ".", "GetDebugger", "(", ")", ".", "get_option", "(", "pywin", ".", "debugger", ".", "dbgcon", ".", "OPT_STOP_EXCEPTIONS", ")", "except", ":", "debug", "=", "1", "if", "debug", ":", "try", ":", "pywin", ".", "debugger", ".", "post_mortem", "(", "tb", ",", "typ", ",", "val", ")", "# The original exception", "except", ":", "traceback", ".", "print_exc", "(", ")", "# But still raise it.", "del", "tb", "raise" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/server/dispatcher.py#L242-L264
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/pypack/modulegraph/pkg_resources.py
python
EntryPoint.parse_map
(cls, data, dist=None)
return maps
Parse a map of entry point groups
Parse a map of entry point groups
[ "Parse", "a", "map", "of", "entry", "point", "groups" ]
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data,dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps
[ "def", "parse_map", "(", "cls", ",", "data", ",", "dist", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "data", ".", "items", "(", ")", "else", ":", "data", "=", "split_sections", "(", "data", ")", "maps", "=", "{", "}", "for", "group", ",", "lines", "in", "data", ":", "if", "group", "is", "None", ":", "if", "not", "lines", ":", "continue", "raise", "ValueError", "(", "\"Entry points must be listed in groups\"", ")", "group", "=", "group", ".", "strip", "(", ")", "if", "group", "in", "maps", ":", "raise", "ValueError", "(", "\"Duplicate group name\"", ",", "group", ")", "maps", "[", "group", "]", "=", "cls", ".", "parse_group", "(", "group", ",", "lines", ",", "dist", ")", "return", "maps" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/modulegraph/pkg_resources.py#L1749-L1765
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/compat/__init__.py
python
is_platform_little_endian
()
return sys.byteorder == "little"
Checking if the running platform is little endian. Returns ------- bool True if the running platform is little endian.
Checking if the running platform is little endian.
[ "Checking", "if", "the", "running", "platform", "is", "little", "endian", "." ]
def is_platform_little_endian() -> bool: """ Checking if the running platform is little endian. Returns ------- bool True if the running platform is little endian. """ return sys.byteorder == "little"
[ "def", "is_platform_little_endian", "(", ")", "->", "bool", ":", "return", "sys", ".", "byteorder", "==", "\"little\"" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/compat/__init__.py#L39-L48
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
SizerItemList.__iter__
(*args, **kwargs)
return _core_.SizerItemList___iter__(*args, **kwargs)
__iter__(self) -> SizerItemList_iterator
__iter__(self) -> SizerItemList_iterator
[ "__iter__", "(", "self", ")", "-", ">", "SizerItemList_iterator" ]
def __iter__(*args, **kwargs): """__iter__(self) -> SizerItemList_iterator""" return _core_.SizerItemList___iter__(*args, **kwargs)
[ "def", "__iter__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SizerItemList___iter__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L13999-L14001
gwaldron/osgearth
4c521857d59a69743e4a9cedba00afe570f984e8
src/third_party/tinygltf/deps/cpplint.py
python
CleanseRawStrings
(raw_lines)
return lines_without_raw_strings
Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings.
Removes C++11 raw strings from lines.
[ "Removes", "C", "++", "11", "raw", "strings", "from", "lines", "." ]
def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '""' # Look for beginning of a raw string, and replace them with # empty strings. This is done in a loop to handle multiple raw # strings on the same line. while delimiter is None: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if matched: delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' else: break lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings
[ "def", "CleanseRawStrings", "(", "raw_lines", ")", ":", "delimiter", "=", "None", "lines_without_raw_strings", "=", "[", "]", "for", "line", "in", "raw_lines", ":", "if", "delimiter", ":", "# Inside a raw string, look for the end", "end", "=", "line", ".", "find", "(", "delimiter", ")", "if", "end", ">=", "0", ":", "# Found the end of the string, match leading space for this", "# line and resume copying the original lines, and also insert", "# a \"\" on the last line.", "leading_space", "=", "Match", "(", "r'^(\\s*)\\S'", ",", "line", ")", "line", "=", "leading_space", ".", "group", "(", "1", ")", "+", "'\"\"'", "+", "line", "[", "end", "+", "len", "(", "delimiter", ")", ":", "]", "delimiter", "=", "None", "else", ":", "# Haven't found the end yet, append a blank line.", "line", "=", "'\"\"'", "# Look for beginning of a raw string, and replace them with", "# empty strings. This is done in a loop to handle multiple raw", "# strings on the same line.", "while", "delimiter", "is", "None", ":", "# Look for beginning of a raw string.", "# See 2.14.15 [lex.string] for syntax.", "matched", "=", "Match", "(", "r'^(.*)\\b(?:R|u8R|uR|UR|LR)\"([^\\s\\\\()]*)\\((.*)$'", ",", "line", ")", "if", "matched", ":", "delimiter", "=", "')'", "+", "matched", ".", "group", "(", "2", ")", "+", "'\"'", "end", "=", "matched", ".", "group", "(", "3", ")", ".", "find", "(", "delimiter", ")", "if", "end", ">=", "0", ":", "# Raw string ended on same line", "line", "=", "(", "matched", ".", "group", "(", "1", ")", "+", "'\"\"'", "+", "matched", ".", "group", "(", "3", ")", "[", "end", "+", "len", "(", "delimiter", ")", ":", "]", ")", "delimiter", "=", "None", "else", ":", "# Start of a multi-line raw string", "line", "=", "matched", ".", "group", "(", "1", ")", "+", "'\"\"'", "else", ":", "break", "lines_without_raw_strings", ".", "append", "(", "line", ")", "# TODO(unknown): if delimiter is not None here, we might want to", "# emit a warning for unterminated string.", "return", "lines_without_raw_strings" ]
https://github.com/gwaldron/osgearth/blob/4c521857d59a69743e4a9cedba00afe570f984e8/src/third_party/tinygltf/deps/cpplint.py#L1164-L1227
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py
python
buildTagMap
(default, *args)
return built
Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.
Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.
[ "Turns", "a", "list", "of", "maps", "lists", "or", "scalars", "into", "a", "single", "map", ".", "Used", "to", "build", "the", "SELF_CLOSING_TAGS", "NESTABLE_TAGS", "and", "NESTING_RESET_TAGS", "maps", "out", "of", "lists", "and", "partial", "maps", "." ]
def buildTagMap(default, *args): """Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.""" built = {} for portion in args: if hasattr(portion, 'items'): #It's a map. Merge it. for k,v in portion.items(): built[k] = v elif hasattr(portion, '__iter__'): # is a list #It's a list. Map each item to the default. for k in portion: built[k] = default else: #It's a scalar. Map it to the default. built[portion] = default return built
[ "def", "buildTagMap", "(", "default", ",", "*", "args", ")", ":", "built", "=", "{", "}", "for", "portion", "in", "args", ":", "if", "hasattr", "(", "portion", ",", "'items'", ")", ":", "#It's a map. Merge it.", "for", "k", ",", "v", "in", "portion", ".", "items", "(", ")", ":", "built", "[", "k", "]", "=", "v", "elif", "hasattr", "(", "portion", ",", "'__iter__'", ")", ":", "# is a list", "#It's a list. Map each item to the default.", "for", "k", "in", "portion", ":", "built", "[", "k", "]", "=", "default", "else", ":", "#It's a scalar. Map it to the default.", "built", "[", "portion", "]", "=", "default", "return", "built" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L1015-L1032
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/cross_device_ops.py
python
AllReduceCrossDeviceOps._batch_all_reduce
(self, reduce_op, per_replica_values)
return cross_device_utils.stitch_values(((dense_results, dense_indices), (sparse_results, sparse_indices)))
All-reduce algorithm in a batch.
All-reduce algorithm in a batch.
[ "All", "-", "reduce", "algorithm", "in", "a", "batch", "." ]
def _batch_all_reduce(self, reduce_op, per_replica_values): """All-reduce algorithm in a batch.""" dense_values, dense_indices, sparse_values, sparse_indices = ( cross_device_utils.split_by_sparsity(per_replica_values)) if dense_values: dense_results = self._do_batch_all_reduce(reduce_op, dense_values) else: dense_results = [] if sparse_values: sparse_results = self._do_batch_all_reduce_sparse(reduce_op, sparse_values) else: sparse_results = [] return cross_device_utils.stitch_values(((dense_results, dense_indices), (sparse_results, sparse_indices)))
[ "def", "_batch_all_reduce", "(", "self", ",", "reduce_op", ",", "per_replica_values", ")", ":", "dense_values", ",", "dense_indices", ",", "sparse_values", ",", "sparse_indices", "=", "(", "cross_device_utils", ".", "split_by_sparsity", "(", "per_replica_values", ")", ")", "if", "dense_values", ":", "dense_results", "=", "self", ".", "_do_batch_all_reduce", "(", "reduce_op", ",", "dense_values", ")", "else", ":", "dense_results", "=", "[", "]", "if", "sparse_values", ":", "sparse_results", "=", "self", ".", "_do_batch_all_reduce_sparse", "(", "reduce_op", ",", "sparse_values", ")", "else", ":", "sparse_results", "=", "[", "]", "return", "cross_device_utils", ".", "stitch_values", "(", "(", "(", "dense_results", ",", "dense_indices", ")", ",", "(", "sparse_results", ",", "sparse_indices", ")", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/cross_device_ops.py#L879-L893
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/email/_encoded_words.py
python
decode
(ew)
return string, charset, lang, defects
Decode encoded word and return (string, charset, lang, defects) tuple. An RFC 2047/2243 encoded word has the form: =?charset*lang?cte?encoded_string?= where '*lang' may be omitted but the other parts may not be. This function expects exactly such a string (that is, it does not check the syntax and may raise errors if the string is not well formed), and returns the encoded_string decoded first from its Content Transfer Encoding and then from the resulting bytes into unicode using the specified charset. If the cte-decoded string does not successfully decode using the specified character set, a defect is added to the defects list and the unknown octets are replaced by the unicode 'unknown' character \\uFDFF. The specified charset and language are returned. The default for language, which is rarely if ever encountered, is the empty string.
Decode encoded word and return (string, charset, lang, defects) tuple.
[ "Decode", "encoded", "word", "and", "return", "(", "string", "charset", "lang", "defects", ")", "tuple", "." ]
def decode(ew): """Decode encoded word and return (string, charset, lang, defects) tuple. An RFC 2047/2243 encoded word has the form: =?charset*lang?cte?encoded_string?= where '*lang' may be omitted but the other parts may not be. This function expects exactly such a string (that is, it does not check the syntax and may raise errors if the string is not well formed), and returns the encoded_string decoded first from its Content Transfer Encoding and then from the resulting bytes into unicode using the specified charset. If the cte-decoded string does not successfully decode using the specified character set, a defect is added to the defects list and the unknown octets are replaced by the unicode 'unknown' character \\uFDFF. The specified charset and language are returned. The default for language, which is rarely if ever encountered, is the empty string. """ _, charset, cte, cte_string, _ = ew.split('?') charset, _, lang = charset.partition('*') cte = cte.lower() # Recover the original bytes and do CTE decoding. bstring = cte_string.encode('ascii', 'surrogateescape') bstring, defects = _cte_decoders[cte](bstring) # Turn the CTE decoded bytes into unicode. try: string = bstring.decode(charset) except UnicodeError: defects.append(errors.UndecodableBytesDefect("Encoded word " "contains bytes not decodable using {} charset".format(charset))) string = bstring.decode(charset, 'surrogateescape') except LookupError: string = bstring.decode('ascii', 'surrogateescape') if charset.lower() != 'unknown-8bit': defects.append(errors.CharsetError("Unknown charset {} " "in encoded word; decoded as unknown bytes".format(charset))) return string, charset, lang, defects
[ "def", "decode", "(", "ew", ")", ":", "_", ",", "charset", ",", "cte", ",", "cte_string", ",", "_", "=", "ew", ".", "split", "(", "'?'", ")", "charset", ",", "_", ",", "lang", "=", "charset", ".", "partition", "(", "'*'", ")", "cte", "=", "cte", ".", "lower", "(", ")", "# Recover the original bytes and do CTE decoding.", "bstring", "=", "cte_string", ".", "encode", "(", "'ascii'", ",", "'surrogateescape'", ")", "bstring", ",", "defects", "=", "_cte_decoders", "[", "cte", "]", "(", "bstring", ")", "# Turn the CTE decoded bytes into unicode.", "try", ":", "string", "=", "bstring", ".", "decode", "(", "charset", ")", "except", "UnicodeError", ":", "defects", ".", "append", "(", "errors", ".", "UndecodableBytesDefect", "(", "\"Encoded word \"", "\"contains bytes not decodable using {} charset\"", ".", "format", "(", "charset", ")", ")", ")", "string", "=", "bstring", ".", "decode", "(", "charset", ",", "'surrogateescape'", ")", "except", "LookupError", ":", "string", "=", "bstring", ".", "decode", "(", "'ascii'", ",", "'surrogateescape'", ")", "if", "charset", ".", "lower", "(", ")", "!=", "'unknown-8bit'", ":", "defects", ".", "append", "(", "errors", ".", "CharsetError", "(", "\"Unknown charset {} \"", "\"in encoded word; decoded as unknown bytes\"", ".", "format", "(", "charset", ")", ")", ")", "return", "string", ",", "charset", ",", "lang", ",", "defects" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/_encoded_words.py#L152-L191
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBUnixSignals.SetShouldNotify
(self, signo, value)
return _lldb.SBUnixSignals_SetShouldNotify(self, signo, value)
SetShouldNotify(SBUnixSignals self, int32_t signo, bool value) -> bool
SetShouldNotify(SBUnixSignals self, int32_t signo, bool value) -> bool
[ "SetShouldNotify", "(", "SBUnixSignals", "self", "int32_t", "signo", "bool", "value", ")", "-", ">", "bool" ]
def SetShouldNotify(self, signo, value): """SetShouldNotify(SBUnixSignals self, int32_t signo, bool value) -> bool""" return _lldb.SBUnixSignals_SetShouldNotify(self, signo, value)
[ "def", "SetShouldNotify", "(", "self", ",", "signo", ",", "value", ")", ":", "return", "_lldb", ".", "SBUnixSignals_SetShouldNotify", "(", "self", ",", "signo", ",", "value", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15361-L15363
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/tools/visualize.py
python
CamelCaseToSnakeCase
(camel_case_input)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
Converts an identifier in CamelCase to snake_case.
Converts an identifier in CamelCase to snake_case.
[ "Converts", "an", "identifier", "in", "CamelCase", "to", "snake_case", "." ]
def CamelCaseToSnakeCase(camel_case_input): """Converts an identifier in CamelCase to snake_case.""" s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_case_input) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
[ "def", "CamelCaseToSnakeCase", "(", "camel_case_input", ")", ":", "s1", "=", "re", ".", "sub", "(", "\"(.)([A-Z][a-z]+)\"", ",", "r\"\\1_\\2\"", ",", "camel_case_input", ")", "return", "re", ".", "sub", "(", "\"([a-z0-9])([A-Z])\"", ",", "r\"\\1_\\2\"", ",", "s1", ")", ".", "lower", "(", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/tools/visualize.py#L385-L388
vesoft-inc/nebula
25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35
.linters/cpp/cpplint.py
python
CheckPrintf
(filename, clean_lines, linenum, error)
Check for printf related issues. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check for printf related issues.
[ "Check", "for", "printf", "related", "issues", "." ]
def CheckPrintf(filename, clean_lines, linenum, error): """Check for printf related issues. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # When snprintf is used, the second argument shouldn't be a literal. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) if match and match.group(2) != '0': # If 2nd arg is zero, snprintf is used to calculate size. error(filename, linenum, 'runtime/printf', 3, 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' 'to snprintf.' % (match.group(1), match.group(2))) # Check if some verboten C functions are being used. if Search(r'\bsprintf\s*\(', line): error(filename, linenum, 'runtime/printf', 5, 'Never use sprintf. Use snprintf instead.') match = Search(r'\b(strcpy|strcat)\s*\(', line) if match: error(filename, linenum, 'runtime/printf', 4, 'Almost always, snprintf is better than %s' % match.group(1))
[ "def", "CheckPrintf", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# When snprintf is used, the second argument shouldn't be a literal.", "match", "=", "Search", "(", "r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,'", ",", "line", ")", "if", "match", "and", "match", ".", "group", "(", "2", ")", "!=", "'0'", ":", "# If 2nd arg is zero, snprintf is used to calculate size.", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "3", ",", "'If you can, use sizeof(%s) instead of %s as the 2nd arg '", "'to snprintf.'", "%", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ")", ")", "# Check if some verboten C functions are being used.", "if", "Search", "(", "r'\\bsprintf\\s*\\('", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "5", ",", "'Never use sprintf. Use snprintf instead.'", ")", "match", "=", "Search", "(", "r'\\b(strcpy|strcat)\\s*\\('", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "4", ",", "'Almost always, snprintf is better than %s'", "%", "match", ".", "group", "(", "1", ")", ")" ]
https://github.com/vesoft-inc/nebula/blob/25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35/.linters/cpp/cpplint.py#L5177-L5203
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/distutils/cygwinccompiler.py
python
get_msvcr
()
Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later.
Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later.
[ "Include", "the", "appropriate", "MSVC", "runtime", "library", "if", "Python", "was", "built", "with", "MSVC", "7", ".", "0", "or", "later", "." ]
def get_msvcr(): """Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later. """ msc_pos = sys.version.find('MSC v.') if msc_pos != -1: msc_ver = sys.version[msc_pos+6:msc_pos+10] if msc_ver == '1300': # MSVC 7.0 return ['msvcr70'] elif msc_ver == '1310': # MSVC 7.1 return ['msvcr71'] elif msc_ver == '1400': # VS2005 / MSVC 8.0 return ['msvcr80'] elif msc_ver == '1500': # VS2008 / MSVC 9.0 return ['msvcr90'] else: raise ValueError("Unknown MS Compiler version %s " % msc_ver)
[ "def", "get_msvcr", "(", ")", ":", "msc_pos", "=", "sys", ".", "version", ".", "find", "(", "'MSC v.'", ")", "if", "msc_pos", "!=", "-", "1", ":", "msc_ver", "=", "sys", ".", "version", "[", "msc_pos", "+", "6", ":", "msc_pos", "+", "10", "]", "if", "msc_ver", "==", "'1300'", ":", "# MSVC 7.0", "return", "[", "'msvcr70'", "]", "elif", "msc_ver", "==", "'1310'", ":", "# MSVC 7.1", "return", "[", "'msvcr71'", "]", "elif", "msc_ver", "==", "'1400'", ":", "# VS2005 / MSVC 8.0", "return", "[", "'msvcr80'", "]", "elif", "msc_ver", "==", "'1500'", ":", "# VS2008 / MSVC 9.0", "return", "[", "'msvcr90'", "]", "else", ":", "raise", "ValueError", "(", "\"Unknown MS Compiler version %s \"", "%", "msc_ver", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/cygwinccompiler.py#L59-L79
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.visit_FromImport
(self, node, frame)
Visit named imports.
Visit named imports.
[ "Visit", "named", "imports", "." ]
def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = %senvironment.get_template(' % (self.environment.is_async and 'await ' or '')) self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module%s(context.get_all(), True, %s)' % (self.environment.is_async and '_async' or '', self.dump_local_context(frame))) elif self.environment.is_async: self.write('_get_default_module_async()') else: self.write('_get_default_module()') var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline('%s = getattr(included_template, ' '%r, missing)' % (frame.symbols.ref(alias), name)) self.writeline('if %s is missing:' % frame.symbols.ref(alias)) self.indent() self.writeline('%s = undefined(%r %% ' 'included_template.__name__, ' 'name=%r)' % (frame.symbols.ref(alias), 'the template %%r (imported on %s) does ' 'not export the requested name %s' % ( self.position(node), repr(name) ), name)) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith('_'): discarded_names.append(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline('context.vars[%r] = %s' % (name, frame.symbols.ref(name))) else: self.writeline('context.vars.update({%s})' % ', '.join( '%r: %s' % (name, frame.symbols.ref(name)) for name in var_names )) if discarded_names: if len(discarded_names) == 1: self.writeline('context.exported_vars.discard(%r)' % discarded_names[0]) else: self.writeline('context.exported_vars.difference_' 'update((%s))' % ', '.join(imap(repr, discarded_names)))
[ "def", "visit_FromImport", "(", "self", ",", "node", ",", "frame", ")", ":", "self", ".", "newline", "(", "node", ")", "self", ".", "write", "(", "'included_template = %senvironment.get_template('", "%", "(", "self", ".", "environment", ".", "is_async", "and", "'await '", "or", "''", ")", ")", "self", ".", "visit", "(", "node", ".", "template", ",", "frame", ")", "self", ".", "write", "(", "', %r).'", "%", "self", ".", "name", ")", "if", "node", ".", "with_context", ":", "self", ".", "write", "(", "'make_module%s(context.get_all(), True, %s)'", "%", "(", "self", ".", "environment", ".", "is_async", "and", "'_async'", "or", "''", ",", "self", ".", "dump_local_context", "(", "frame", ")", ")", ")", "elif", "self", ".", "environment", ".", "is_async", ":", "self", ".", "write", "(", "'_get_default_module_async()'", ")", "else", ":", "self", ".", "write", "(", "'_get_default_module()'", ")", "var_names", "=", "[", "]", "discarded_names", "=", "[", "]", "for", "name", "in", "node", ".", "names", ":", "if", "isinstance", "(", "name", ",", "tuple", ")", ":", "name", ",", "alias", "=", "name", "else", ":", "alias", "=", "name", "self", ".", "writeline", "(", "'%s = getattr(included_template, '", "'%r, missing)'", "%", "(", "frame", ".", "symbols", ".", "ref", "(", "alias", ")", ",", "name", ")", ")", "self", ".", "writeline", "(", "'if %s is missing:'", "%", "frame", ".", "symbols", ".", "ref", "(", "alias", ")", ")", "self", ".", "indent", "(", ")", "self", ".", "writeline", "(", "'%s = undefined(%r %% '", "'included_template.__name__, '", "'name=%r)'", "%", "(", "frame", ".", "symbols", ".", "ref", "(", "alias", ")", ",", "'the template %%r (imported on %s) does '", "'not export the requested name %s'", "%", "(", "self", ".", "position", "(", "node", ")", ",", "repr", "(", "name", ")", ")", ",", "name", ")", ")", "self", ".", "outdent", "(", ")", "if", "frame", ".", "toplevel", ":", "var_names", ".", "append", "(", "alias", ")", "if", "not", "alias", ".", "startswith", "(", "'_'", ")", ":", "discarded_names", ".", "append", "(", "alias", ")", "if", "var_names", ":", "if", "len", "(", "var_names", ")", "==", "1", ":", "name", "=", "var_names", "[", "0", "]", "self", ".", "writeline", "(", "'context.vars[%r] = %s'", "%", "(", "name", ",", "frame", ".", "symbols", ".", "ref", "(", "name", ")", ")", ")", "else", ":", "self", ".", "writeline", "(", "'context.vars.update({%s})'", "%", "', '", ".", "join", "(", "'%r: %s'", "%", "(", "name", ",", "frame", ".", "symbols", ".", "ref", "(", "name", ")", ")", "for", "name", "in", "var_names", ")", ")", "if", "discarded_names", ":", "if", "len", "(", "discarded_names", ")", "==", "1", ":", "self", ".", "writeline", "(", "'context.exported_vars.discard(%r)'", "%", "discarded_names", "[", "0", "]", ")", "else", ":", "self", ".", "writeline", "(", "'context.exported_vars.difference_'", "'update((%s))'", "%", "', '", ".", "join", "(", "imap", "(", "repr", ",", "discarded_names", ")", ")", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/compiler.py#L965-L1022
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/operations/install/wheel.py
python
get_csv_rows_for_installed
( old_csv_rows, # type: List[List[str]] installed, # type: Dict[RecordPath, RecordPath] changed, # type: Set[RecordPath] generated, # type: List[str] lib_dir, # type: str )
return installed_rows
:param installed: A map from archive RECORD path to installation RECORD path.
:param installed: A map from archive RECORD path to installation RECORD path.
[ ":", "param", "installed", ":", "A", "map", "from", "archive", "RECORD", "path", "to", "installation", "RECORD", "path", "." ]
def get_csv_rows_for_installed( old_csv_rows, # type: List[List[str]] installed, # type: Dict[RecordPath, RecordPath] changed, # type: Set[RecordPath] generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[InstalledCSVRow] """ :param installed: A map from archive RECORD path to installation RECORD path. """ installed_rows = [] # type: List[InstalledCSVRow] for row in old_csv_rows: if len(row) > 3: logger.warning('RECORD line has more than three elements: %s', row) old_record_path = _parse_record_path(row[0]) new_record_path = installed.pop(old_record_path, old_record_path) if new_record_path in changed: digest, length = rehash(_record_to_fs_path(new_record_path)) else: digest = row[1] if len(row) > 1 else '' length = row[2] if len(row) > 2 else '' installed_rows.append((new_record_path, digest, length)) for f in generated: path = _fs_to_record_path(f, lib_dir) digest, length = rehash(f) installed_rows.append((path, digest, length)) for installed_record_path in installed.values(): installed_rows.append((installed_record_path, '', '')) return installed_rows
[ "def", "get_csv_rows_for_installed", "(", "old_csv_rows", ",", "# type: List[List[str]]", "installed", ",", "# type: Dict[RecordPath, RecordPath]", "changed", ",", "# type: Set[RecordPath]", "generated", ",", "# type: List[str]", "lib_dir", ",", "# type: str", ")", ":", "# type: (...) -> List[InstalledCSVRow]", "installed_rows", "=", "[", "]", "# type: List[InstalledCSVRow]", "for", "row", "in", "old_csv_rows", ":", "if", "len", "(", "row", ")", ">", "3", ":", "logger", ".", "warning", "(", "'RECORD line has more than three elements: %s'", ",", "row", ")", "old_record_path", "=", "_parse_record_path", "(", "row", "[", "0", "]", ")", "new_record_path", "=", "installed", ".", "pop", "(", "old_record_path", ",", "old_record_path", ")", "if", "new_record_path", "in", "changed", ":", "digest", ",", "length", "=", "rehash", "(", "_record_to_fs_path", "(", "new_record_path", ")", ")", "else", ":", "digest", "=", "row", "[", "1", "]", "if", "len", "(", "row", ")", ">", "1", "else", "''", "length", "=", "row", "[", "2", "]", "if", "len", "(", "row", ")", ">", "2", "else", "''", "installed_rows", ".", "append", "(", "(", "new_record_path", ",", "digest", ",", "length", ")", ")", "for", "f", "in", "generated", ":", "path", "=", "_fs_to_record_path", "(", "f", ",", "lib_dir", ")", "digest", ",", "length", "=", "rehash", "(", "f", ")", "installed_rows", ".", "append", "(", "(", "path", ",", "digest", ",", "length", ")", ")", "for", "installed_record_path", "in", "installed", ".", "values", "(", ")", ":", "installed_rows", ".", "append", "(", "(", "installed_record_path", ",", "''", ",", "''", ")", ")", "return", "installed_rows" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/operations/install/wheel.py#L275-L305
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py
python
mbox._post_message_hook
(self, f)
Called after writing each message to file f.
Called after writing each message to file f.
[ "Called", "after", "writing", "each", "message", "to", "file", "f", "." ]
def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(linesep)
[ "def", "_post_message_hook", "(", "self", ",", "f", ")", ":", "f", ".", "write", "(", "linesep", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L849-L851
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/variable_scope.py
python
variable_scope
(name_or_scope, reuse=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, dtype=None)
Returns a context for variable scope. Variable scope allows to create new variables and to share already created ones while providing checks to not create or share by accident. For details, see the [Variable Scope How To](../../how_tos/variable_scope/index.md), here we present only a few basic examples. Simple example of how to create a new variable: ```python with tf.variable_scope("foo"): with tf.variable_scope("bar"): v = tf.get_variable("v", [1]) assert v.name == "foo/bar/v:0" ``` Basic example of sharing a variable: ```python with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) with tf.variable_scope("foo", reuse=True): v1 = tf.get_variable("v", [1]) assert v1 == v ``` Sharing a variable by capturing a scope and setting reuse: ```python with tf.variable_scope("foo") as scope: v = tf.get_variable("v", [1]) scope.reuse_variables() v1 = tf.get_variable("v", [1]) assert v1 == v ``` To prevent accidental sharing of variables, we raise an exception when getting an existing variable in a non-reusing scope. ```python with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) v1 = tf.get_variable("v", [1]) # Raises ValueError("... v already exists ..."). ``` Similarly, we raise an exception when trying to get a variable that does not exist in reuse mode. ```python with tf.variable_scope("foo", reuse=True): v = tf.get_variable("v", [1]) # Raises ValueError("... v does not exists ..."). ``` Note that the `reuse` flag is inherited: if we open a reusing scope, then all its sub-scopes become reusing as well. Args: name_or_scope: `string` or `VariableScope`: the scope to open. reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as well as all sub-scopes; if `None`, we just inherit the parent scope reuse. initializer: default initializer for variables within this scope. regularizer: default regularizer for variables within this scope. caching_device: default caching device for variables within this scope. partitioner: default partitioner for variables within this scope. custom_getter: default custom getter for variables within this scope. dtype: type of variables created in this scope (defaults to the type in the passed scope, or inherited from parent scope). Returns: A scope that can be to captured and reused. Raises: ValueError: when trying to reuse within a create scope, or create within a reuse scope, or if reuse is not `None` or `True`. TypeError: when the types of some arguments are not appropriate.
Returns a context for variable scope.
[ "Returns", "a", "context", "for", "variable", "scope", "." ]
def variable_scope(name_or_scope, reuse=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, dtype=None): """Returns a context for variable scope. Variable scope allows to create new variables and to share already created ones while providing checks to not create or share by accident. For details, see the [Variable Scope How To](../../how_tos/variable_scope/index.md), here we present only a few basic examples. Simple example of how to create a new variable: ```python with tf.variable_scope("foo"): with tf.variable_scope("bar"): v = tf.get_variable("v", [1]) assert v.name == "foo/bar/v:0" ``` Basic example of sharing a variable: ```python with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) with tf.variable_scope("foo", reuse=True): v1 = tf.get_variable("v", [1]) assert v1 == v ``` Sharing a variable by capturing a scope and setting reuse: ```python with tf.variable_scope("foo") as scope: v = tf.get_variable("v", [1]) scope.reuse_variables() v1 = tf.get_variable("v", [1]) assert v1 == v ``` To prevent accidental sharing of variables, we raise an exception when getting an existing variable in a non-reusing scope. ```python with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) v1 = tf.get_variable("v", [1]) # Raises ValueError("... v already exists ..."). ``` Similarly, we raise an exception when trying to get a variable that does not exist in reuse mode. ```python with tf.variable_scope("foo", reuse=True): v = tf.get_variable("v", [1]) # Raises ValueError("... v does not exists ..."). ``` Note that the `reuse` flag is inherited: if we open a reusing scope, then all its sub-scopes become reusing as well. Args: name_or_scope: `string` or `VariableScope`: the scope to open. reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as well as all sub-scopes; if `None`, we just inherit the parent scope reuse. initializer: default initializer for variables within this scope. regularizer: default regularizer for variables within this scope. caching_device: default caching device for variables within this scope. partitioner: default partitioner for variables within this scope. custom_getter: default custom getter for variables within this scope. dtype: type of variables created in this scope (defaults to the type in the passed scope, or inherited from parent scope). Returns: A scope that can be to captured and reused. Raises: ValueError: when trying to reuse within a create scope, or create within a reuse scope, or if reuse is not `None` or `True`. TypeError: when the types of some arguments are not appropriate. """ if not isinstance(name_or_scope, (VariableScope,) + six.string_types): raise TypeError("VariableScope: name_or_scope must be a string or " "VariableScope.") if isinstance(name_or_scope, six.string_types): name_scope = name_or_scope else: name_scope = name_or_scope.name.split("/")[-1] if name_scope: with ops.name_scope(name_scope) as cur_name_scope: if isinstance(name_or_scope, six.string_types): old_name_scope = cur_name_scope else: old_name_scope = name_or_scope.original_name_scope with _pure_variable_scope( name_or_scope, reuse=reuse, initializer=initializer, regularizer=regularizer, caching_device=caching_device, partitioner=partitioner, custom_getter=custom_getter, old_name_scope=old_name_scope, dtype=dtype) as vs: yield vs else: # This can only happen if someone is entering the root variable scope. with _pure_variable_scope( name_or_scope, reuse=reuse, initializer=initializer, regularizer=regularizer, caching_device=caching_device, partitioner=partitioner, custom_getter=custom_getter, dtype=dtype) as vs: yield vs
[ "def", "variable_scope", "(", "name_or_scope", ",", "reuse", "=", "None", ",", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "caching_device", "=", "None", ",", "partitioner", "=", "None", ",", "custom_getter", "=", "None", ",", "dtype", "=", "None", ")", ":", "if", "not", "isinstance", "(", "name_or_scope", ",", "(", "VariableScope", ",", ")", "+", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"VariableScope: name_or_scope must be a string or \"", "\"VariableScope.\"", ")", "if", "isinstance", "(", "name_or_scope", ",", "six", ".", "string_types", ")", ":", "name_scope", "=", "name_or_scope", "else", ":", "name_scope", "=", "name_or_scope", ".", "name", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "if", "name_scope", ":", "with", "ops", ".", "name_scope", "(", "name_scope", ")", "as", "cur_name_scope", ":", "if", "isinstance", "(", "name_or_scope", ",", "six", ".", "string_types", ")", ":", "old_name_scope", "=", "cur_name_scope", "else", ":", "old_name_scope", "=", "name_or_scope", ".", "original_name_scope", "with", "_pure_variable_scope", "(", "name_or_scope", ",", "reuse", "=", "reuse", ",", "initializer", "=", "initializer", ",", "regularizer", "=", "regularizer", ",", "caching_device", "=", "caching_device", ",", "partitioner", "=", "partitioner", ",", "custom_getter", "=", "custom_getter", ",", "old_name_scope", "=", "old_name_scope", ",", "dtype", "=", "dtype", ")", "as", "vs", ":", "yield", "vs", "else", ":", "# This can only happen if someone is entering the root variable scope.", "with", "_pure_variable_scope", "(", "name_or_scope", ",", "reuse", "=", "reuse", ",", "initializer", "=", "initializer", ",", "regularizer", "=", "regularizer", ",", "caching_device", "=", "caching_device", ",", "partitioner", "=", "partitioner", ",", "custom_getter", "=", "custom_getter", ",", "dtype", "=", "dtype", ")", "as", "vs", ":", "yield", "vs" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/variable_scope.py#L1089-L1210
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py
python
update_module_definition
(ctx, module_type, build_type, kw)
Update the module definition file for the current module :param ctx: Configuration context :param module_type: The module type (from cryengine_modules) :param build_type: The WAF type (shlib, stlib, program) :param kw: The keyword dictionary for the current module
Update the module definition file for the current module
[ "Update", "the", "module", "definition", "file", "for", "the", "current", "module" ]
def update_module_definition(ctx, module_type, build_type, kw): """ Update the module definition file for the current module :param ctx: Configuration context :param module_type: The module type (from cryengine_modules) :param build_type: The WAF type (shlib, stlib, program) :param kw: The keyword dictionary for the current module """ def _to_set(input): if isinstance(input, list): return set(input) else: return set([input]) target = kw.get('target', '') if len(target) == 0: raise Errors.WafError("Missing/invalid 'target' keyword in {}/".format(ctx.path.abspath())) platforms = list(_to_set(kw.get('platforms',['all']))) configurations = list(_to_set(kw.get('configurations',['all']))) # Attempt to collect all permutations of the 'use' keyword so we can build the full 'use' dependencies for all cases use_related_keywords = ctx.get_all_eligible_use_keywords() # Include 'uselib' as a module use append_to_unique_list(use_related_keywords, 'uselib') uses = [] for use_keyword in use_related_keywords: append_to_unique_list(uses, kw.get(use_keyword, [])) path = ctx.path.path_from(ctx.engine_node) module_def = { 'target': target, 'type': build_type, 'module_type': module_type, 'path': path, 'platforms': sorted(platforms), 'configurations': sorted(configurations), 'uses': sorted(uses) } module_def_folder = os.path.join(ctx.engine_path, BINTEMP_FOLDER, BINTEMP_MODULE_DEF) if not ctx.cached_does_path_exist(module_def_folder): os.makedirs(module_def_folder) ctx.cached_does_path_exist(module_def_folder, True) module_def_file = os.path.join(module_def_folder, _get_module_def_filename(target)) write_json_file(module_def, module_def_file)
[ "def", "update_module_definition", "(", "ctx", ",", "module_type", ",", "build_type", ",", "kw", ")", ":", "def", "_to_set", "(", "input", ")", ":", "if", "isinstance", "(", "input", ",", "list", ")", ":", "return", "set", "(", "input", ")", "else", ":", "return", "set", "(", "[", "input", "]", ")", "target", "=", "kw", ".", "get", "(", "'target'", ",", "''", ")", "if", "len", "(", "target", ")", "==", "0", ":", "raise", "Errors", ".", "WafError", "(", "\"Missing/invalid 'target' keyword in {}/\"", ".", "format", "(", "ctx", ".", "path", ".", "abspath", "(", ")", ")", ")", "platforms", "=", "list", "(", "_to_set", "(", "kw", ".", "get", "(", "'platforms'", ",", "[", "'all'", "]", ")", ")", ")", "configurations", "=", "list", "(", "_to_set", "(", "kw", ".", "get", "(", "'configurations'", ",", "[", "'all'", "]", ")", ")", ")", "# Attempt to collect all permutations of the 'use' keyword so we can build the full 'use' dependencies for all cases", "use_related_keywords", "=", "ctx", ".", "get_all_eligible_use_keywords", "(", ")", "# Include 'uselib' as a module use", "append_to_unique_list", "(", "use_related_keywords", ",", "'uselib'", ")", "uses", "=", "[", "]", "for", "use_keyword", "in", "use_related_keywords", ":", "append_to_unique_list", "(", "uses", ",", "kw", ".", "get", "(", "use_keyword", ",", "[", "]", ")", ")", "path", "=", "ctx", ".", "path", ".", "path_from", "(", "ctx", ".", "engine_node", ")", "module_def", "=", "{", "'target'", ":", "target", ",", "'type'", ":", "build_type", ",", "'module_type'", ":", "module_type", ",", "'path'", ":", "path", ",", "'platforms'", ":", "sorted", "(", "platforms", ")", ",", "'configurations'", ":", "sorted", "(", "configurations", ")", ",", "'uses'", ":", "sorted", "(", "uses", ")", "}", "module_def_folder", "=", "os", ".", "path", ".", "join", "(", "ctx", ".", "engine_path", ",", "BINTEMP_FOLDER", ",", "BINTEMP_MODULE_DEF", ")", "if", "not", "ctx", ".", "cached_does_path_exist", "(", "module_def_folder", ")", ":", "os", ".", "makedirs", "(", "module_def_folder", ")", "ctx", ".", "cached_does_path_exist", "(", "module_def_folder", ",", "True", ")", "module_def_file", "=", "os", ".", "path", ".", "join", "(", "module_def_folder", ",", "_get_module_def_filename", "(", "target", ")", ")", "write_json_file", "(", "module_def", ",", "module_def_file", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py#L1073-L1123
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/_compile_utils.py
python
tensor_in_sequence
(x, y)
return result
Assigns whether a sequence contains the given tensor
Assigns whether a sequence contains the given tensor
[ "Assigns", "whether", "a", "sequence", "contains", "the", "given", "tensor" ]
def tensor_in_sequence(x, y): """Assigns whether a sequence contains the given tensor""" result = const_utils.scalar_to_tensor(False) for i in y: if isinstance(i, Tensor) and x.shape == i.shape and x.dtype == i.dtype: result = F.logical_or(F.equal(x, i).all(), result) return result
[ "def", "tensor_in_sequence", "(", "x", ",", "y", ")", ":", "result", "=", "const_utils", ".", "scalar_to_tensor", "(", "False", ")", "for", "i", "in", "y", ":", "if", "isinstance", "(", "i", ",", "Tensor", ")", "and", "x", ".", "shape", "==", "i", ".", "shape", "and", "x", ".", "dtype", "==", "i", ".", "dtype", ":", "result", "=", "F", ".", "logical_or", "(", "F", ".", "equal", "(", "x", ",", "i", ")", ".", "all", "(", ")", ",", "result", ")", "return", "result" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/_compile_utils.py#L990-L996
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/tools/clang/docs/tools/dump_ast_matchers.py
python
act_on_decl
(declaration, comment, allowed_types)
Parse the matcher out of the given declaration and comment. If 'allowed_types' is set, it contains a list of node types the matcher can match on, as extracted from the static type asserts in the matcher definition.
Parse the matcher out of the given declaration and comment.
[ "Parse", "the", "matcher", "out", "of", "the", "given", "declaration", "and", "comment", "." ]
def act_on_decl(declaration, comment, allowed_types): """Parse the matcher out of the given declaration and comment. If 'allowed_types' is set, it contains a list of node types the matcher can match on, as extracted from the static type asserts in the matcher definition. """ if declaration.strip(): # Node matchers are defined by writing: # VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name; m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*< \s*([^\s,]+)\s*(?:, \s*([^\s>]+)\s*)?> \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X) if m: result, inner, name = m.groups() if not inner: inner = result add_matcher(result, name, 'Matcher<%s>...' % inner, comment, is_dyncast=True) return # Parse the various matcher definition macros. m = re.match(""".*AST_TYPE_MATCHER\( \s*([^\s,]+\s*), \s*([^\s,]+\s*) \)\s*;\s*$""", declaration, flags=re.X) if m: inner, name = m.groups() add_matcher('Type', name, 'Matcher<%s>...' % inner, comment, is_dyncast=True) # FIXME: re-enable once we have implemented casting on the TypeLoc # hierarchy. # add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner, # comment, is_dyncast=True) return m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER\( \s*([^\s,]+\s*), \s*(?:[^\s,]+\s*), \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\) \)\s*;\s*$""", declaration, flags=re.X) if m: loc, name, results = m.groups()[0:3] result_types = [r.strip() for r in results.split(',')] comment_result_types = extract_result_types(comment) if (comment_result_types and sorted(result_types) != sorted(comment_result_types)): raise Exception('Inconsistent documentation for: %s' % name) for result_type in result_types: add_matcher(result_type, name, 'Matcher<Type>', comment) if loc: add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>', comment) return m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\( \s*([^\s,]+)\s*, \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\) (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*\d+\s*)? \)\s*{\s*$""", declaration, flags=re.X) if m: p, n, name, results = m.groups()[0:4] args = m.groups()[4:] result_types = [r.strip() for r in results.split(',')] if allowed_types and allowed_types != result_types: raise Exception('Inconsistent documentation for: %s' % name) if n not in ['', '2']: raise Exception('Cannot parse "%s"' % declaration) args = ', '.join('%s %s' % (args[i], args[i+1]) for i in range(0, len(args), 2) if args[i]) for result_type in result_types: add_matcher(result_type, name, args, comment) return m = re.match(r"""^\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\( (?:\s*([^\s,]+)\s*,)? \s*([^\s,]+)\s* (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*\d+\s*)? \)\s*{\s*$""", declaration, flags=re.X) if m: p, n, result, name = m.groups()[0:4] args = m.groups()[4:] if n not in ['', '2']: raise Exception('Cannot parse "%s"' % declaration) args = ', '.join('%s %s' % (args[i], args[i+1]) for i in range(0, len(args), 2) if args[i]) add_matcher(result, name, args, comment) return m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\( (?:\s*([^\s,]+)\s*,)? \s*([^\s,]+)\s* (?:,\s*([^,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*\d+\s*)? \)\s*{\s*$""", declaration, flags=re.X) if m: p, n, result, name = m.groups()[0:4] args = m.groups()[4:] if not result: if not allowed_types: raise Exception('Did not find allowed result types for: %s' % name) result_types = allowed_types else: result_types = [result] if n not in ['', '2']: raise Exception('Cannot parse "%s"' % declaration) args = ', '.join('%s %s' % (args[i], args[i+1]) for i in range(0, len(args), 2) if args[i]) for result_type in result_types: add_matcher(result_type, name, args, comment) return # Parse ArgumentAdapting matchers. m = re.match( r"""^.*ArgumentAdaptingMatcherFunc<.*>\s*(?:LLVM_ATTRIBUTE_UNUSED\s*) ([a-zA-Z]*)\s*=\s*{};$""", declaration, flags=re.X) if m: name = m.groups()[0] add_matcher('*', name, 'Matcher<*>', comment) return # Parse Variadic functions. m = re.match( r"""^.*internal::VariadicFunction\s*<\s*([^,]+),\s*([^,]+),\s*[^>]+>\s* ([a-zA-Z]*)\s*=\s*{.*};$""", declaration, flags=re.X) if m: result, arg, name = m.groups()[:3] add_matcher(result, name, '%s, ..., %s' % (arg, arg), comment) return # Parse Variadic operator matchers. m = re.match( r"""^.*VariadicOperatorMatcherFunc\s*<\s*([^,]+),\s*([^\s>]+)\s*>\s* ([a-zA-Z]*)\s*=\s*{.*};$""", declaration, flags=re.X) if m: min_args, max_args, name = m.groups()[:3] if max_args == '1': add_matcher('*', name, 'Matcher<*>', comment) return elif max_args == 'UINT_MAX': add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment) return # Parse free standing matcher functions, like: # Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) { m = re.match(r"""^\s*(.*)\s+ ([^\s\(]+)\s*\( (.*) \)\s*{""", declaration, re.X) if m: result, name, args = m.groups() args = ', '.join(p.strip() for p in args.split(',')) m = re.match(r'.*\s+internal::(Bindable)?Matcher<([^>]+)>$', result) if m: result_types = [m.group(2)] else: result_types = extract_result_types(comment) if not result_types: if not comment: # Only overloads don't have their own doxygen comments; ignore those. print 'Ignoring "%s"' % name else: print 'Cannot determine result type for "%s"' % name else: for result_type in result_types: add_matcher(result_type, name, args, comment) else: print '*** Unparsable: "' + declaration + '" ***'
[ "def", "act_on_decl", "(", "declaration", ",", "comment", ",", "allowed_types", ")", ":", "if", "declaration", ".", "strip", "(", ")", ":", "# Node matchers are defined by writing:", "# VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;", "m", "=", "re", ".", "match", "(", "r\"\"\".*Variadic(?:DynCast)?AllOfMatcher\\s*<\n \\s*([^\\s,]+)\\s*(?:,\n \\s*([^\\s>]+)\\s*)?>\n \\s*([^\\s;]+)\\s*;\\s*$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "result", ",", "inner", ",", "name", "=", "m", ".", "groups", "(", ")", "if", "not", "inner", ":", "inner", "=", "result", "add_matcher", "(", "result", ",", "name", ",", "'Matcher<%s>...'", "%", "inner", ",", "comment", ",", "is_dyncast", "=", "True", ")", "return", "# Parse the various matcher definition macros.", "m", "=", "re", ".", "match", "(", "\"\"\".*AST_TYPE_MATCHER\\(\n \\s*([^\\s,]+\\s*),\n \\s*([^\\s,]+\\s*)\n \\)\\s*;\\s*$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "inner", ",", "name", "=", "m", ".", "groups", "(", ")", "add_matcher", "(", "'Type'", ",", "name", ",", "'Matcher<%s>...'", "%", "inner", ",", "comment", ",", "is_dyncast", "=", "True", ")", "# FIXME: re-enable once we have implemented casting on the TypeLoc", "# hierarchy.", "# add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,", "# comment, is_dyncast=True)", "return", "m", "=", "re", ".", "match", "(", "\"\"\".*AST_TYPE(LOC)?_TRAVERSE_MATCHER\\(\n \\s*([^\\s,]+\\s*),\n \\s*(?:[^\\s,]+\\s*),\n \\s*AST_POLYMORPHIC_SUPPORTED_TYPES\\(([^)]*)\\)\n \\)\\s*;\\s*$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "loc", ",", "name", ",", "results", "=", "m", ".", "groups", "(", ")", "[", "0", ":", "3", "]", "result_types", "=", "[", "r", ".", "strip", "(", ")", "for", "r", "in", "results", ".", "split", "(", "','", ")", "]", "comment_result_types", "=", "extract_result_types", "(", "comment", ")", "if", "(", "comment_result_types", "and", "sorted", "(", "result_types", ")", "!=", "sorted", "(", "comment_result_types", ")", ")", ":", "raise", "Exception", "(", "'Inconsistent documentation for: %s'", "%", "name", ")", "for", "result_type", "in", "result_types", ":", "add_matcher", "(", "result_type", ",", "name", ",", "'Matcher<Type>'", ",", "comment", ")", "if", "loc", ":", "add_matcher", "(", "'%sLoc'", "%", "result_type", ",", "'%sLoc'", "%", "name", ",", "'Matcher<TypeLoc>'", ",", "comment", ")", "return", "m", "=", "re", ".", "match", "(", "r\"\"\"^\\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\\(\n \\s*([^\\s,]+)\\s*,\n \\s*AST_POLYMORPHIC_SUPPORTED_TYPES\\(([^)]*)\\)\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*\\d+\\s*)?\n \\)\\s*{\\s*$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "p", ",", "n", ",", "name", ",", "results", "=", "m", ".", "groups", "(", ")", "[", "0", ":", "4", "]", "args", "=", "m", ".", "groups", "(", ")", "[", "4", ":", "]", "result_types", "=", "[", "r", ".", "strip", "(", ")", "for", "r", "in", "results", ".", "split", "(", "','", ")", "]", "if", "allowed_types", "and", "allowed_types", "!=", "result_types", ":", "raise", "Exception", "(", "'Inconsistent documentation for: %s'", "%", "name", ")", "if", "n", "not", "in", "[", "''", ",", "'2'", "]", ":", "raise", "Exception", "(", "'Cannot parse \"%s\"'", "%", "declaration", ")", "args", "=", "', '", ".", "join", "(", "'%s %s'", "%", "(", "args", "[", "i", "]", ",", "args", "[", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "args", ")", ",", "2", ")", "if", "args", "[", "i", "]", ")", "for", "result_type", "in", "result_types", ":", "add_matcher", "(", "result_type", ",", "name", ",", "args", ",", "comment", ")", "return", "m", "=", "re", ".", "match", "(", "r\"\"\"^\\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\\(\n (?:\\s*([^\\s,]+)\\s*,)?\n \\s*([^\\s,]+)\\s*\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*\\d+\\s*)?\n \\)\\s*{\\s*$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "p", ",", "n", ",", "result", ",", "name", "=", "m", ".", "groups", "(", ")", "[", "0", ":", "4", "]", "args", "=", "m", ".", "groups", "(", ")", "[", "4", ":", "]", "if", "n", "not", "in", "[", "''", ",", "'2'", "]", ":", "raise", "Exception", "(", "'Cannot parse \"%s\"'", "%", "declaration", ")", "args", "=", "', '", ".", "join", "(", "'%s %s'", "%", "(", "args", "[", "i", "]", ",", "args", "[", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "args", ")", ",", "2", ")", "if", "args", "[", "i", "]", ")", "add_matcher", "(", "result", ",", "name", ",", "args", ",", "comment", ")", "return", "m", "=", "re", ".", "match", "(", "r\"\"\"^\\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\\(\n (?:\\s*([^\\s,]+)\\s*,)?\n \\s*([^\\s,]+)\\s*\n (?:,\\s*([^,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*\\d+\\s*)?\n \\)\\s*{\\s*$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "p", ",", "n", ",", "result", ",", "name", "=", "m", ".", "groups", "(", ")", "[", "0", ":", "4", "]", "args", "=", "m", ".", "groups", "(", ")", "[", "4", ":", "]", "if", "not", "result", ":", "if", "not", "allowed_types", ":", "raise", "Exception", "(", "'Did not find allowed result types for: %s'", "%", "name", ")", "result_types", "=", "allowed_types", "else", ":", "result_types", "=", "[", "result", "]", "if", "n", "not", "in", "[", "''", ",", "'2'", "]", ":", "raise", "Exception", "(", "'Cannot parse \"%s\"'", "%", "declaration", ")", "args", "=", "', '", ".", "join", "(", "'%s %s'", "%", "(", "args", "[", "i", "]", ",", "args", "[", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "args", ")", ",", "2", ")", "if", "args", "[", "i", "]", ")", "for", "result_type", "in", "result_types", ":", "add_matcher", "(", "result_type", ",", "name", ",", "args", ",", "comment", ")", "return", "# Parse ArgumentAdapting matchers.", "m", "=", "re", ".", "match", "(", "r\"\"\"^.*ArgumentAdaptingMatcherFunc<.*>\\s*(?:LLVM_ATTRIBUTE_UNUSED\\s*)\n ([a-zA-Z]*)\\s*=\\s*{};$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "name", "=", "m", ".", "groups", "(", ")", "[", "0", "]", "add_matcher", "(", "'*'", ",", "name", ",", "'Matcher<*>'", ",", "comment", ")", "return", "# Parse Variadic functions.", "m", "=", "re", ".", "match", "(", "r\"\"\"^.*internal::VariadicFunction\\s*<\\s*([^,]+),\\s*([^,]+),\\s*[^>]+>\\s*\n ([a-zA-Z]*)\\s*=\\s*{.*};$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "result", ",", "arg", ",", "name", "=", "m", ".", "groups", "(", ")", "[", ":", "3", "]", "add_matcher", "(", "result", ",", "name", ",", "'%s, ..., %s'", "%", "(", "arg", ",", "arg", ")", ",", "comment", ")", "return", "# Parse Variadic operator matchers.", "m", "=", "re", ".", "match", "(", "r\"\"\"^.*VariadicOperatorMatcherFunc\\s*<\\s*([^,]+),\\s*([^\\s>]+)\\s*>\\s*\n ([a-zA-Z]*)\\s*=\\s*{.*};$\"\"\"", ",", "declaration", ",", "flags", "=", "re", ".", "X", ")", "if", "m", ":", "min_args", ",", "max_args", ",", "name", "=", "m", ".", "groups", "(", ")", "[", ":", "3", "]", "if", "max_args", "==", "'1'", ":", "add_matcher", "(", "'*'", ",", "name", ",", "'Matcher<*>'", ",", "comment", ")", "return", "elif", "max_args", "==", "'UINT_MAX'", ":", "add_matcher", "(", "'*'", ",", "name", ",", "'Matcher<*>, ..., Matcher<*>'", ",", "comment", ")", "return", "# Parse free standing matcher functions, like:", "# Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {", "m", "=", "re", ".", "match", "(", "r\"\"\"^\\s*(.*)\\s+\n ([^\\s\\(]+)\\s*\\(\n (.*)\n \\)\\s*{\"\"\"", ",", "declaration", ",", "re", ".", "X", ")", "if", "m", ":", "result", ",", "name", ",", "args", "=", "m", ".", "groups", "(", ")", "args", "=", "', '", ".", "join", "(", "p", ".", "strip", "(", ")", "for", "p", "in", "args", ".", "split", "(", "','", ")", ")", "m", "=", "re", ".", "match", "(", "r'.*\\s+internal::(Bindable)?Matcher<([^>]+)>$'", ",", "result", ")", "if", "m", ":", "result_types", "=", "[", "m", ".", "group", "(", "2", ")", "]", "else", ":", "result_types", "=", "extract_result_types", "(", "comment", ")", "if", "not", "result_types", ":", "if", "not", "comment", ":", "# Only overloads don't have their own doxygen comments; ignore those.", "print", "'Ignoring \"%s\"'", "%", "name", "else", ":", "print", "'Cannot determine result type for \"%s\"'", "%", "name", "else", ":", "for", "result_type", "in", "result_types", ":", "add_matcher", "(", "result_type", ",", "name", ",", "args", ",", "comment", ")", "else", ":", "print", "'*** Unparsable: \"'", "+", "declaration", "+", "'\" ***'" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/docs/tools/dump_ast_matchers.py#L131-L316
NeoGeographyToolkit/StereoPipeline
eedf54a919fb5cce1ab0e280bb0df4050763aa11
src/asp/IceBridge/pleiades_manager.py
python
getEmailAddress
(userName)
Return the email address to use for a user
Return the email address to use for a user
[ "Return", "the", "email", "address", "to", "use", "for", "a", "user" ]
def getEmailAddress(userName): '''Return the email address to use for a user''' if userName == 'smcmich1': return 'scott.mcmichael@gmail.com' if userName == 'oalexan1': return 'oleg.alexandrov@nasa.gov'
[ "def", "getEmailAddress", "(", "userName", ")", ":", "if", "userName", "==", "'smcmich1'", ":", "return", "'scott.mcmichael@gmail.com'", "if", "userName", "==", "'oalexan1'", ":", "return", "'oleg.alexandrov@nasa.gov'" ]
https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/pleiades_manager.py#L137-L143
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/copyright_scanner/copyright_scanner.py
python
ScanAtPresubmit
(input_api, output_api)
return results
Invoked at change presubmit time. Verifies that updated non third-party code doesn't contain external copyrighted code. input_api: InputAPI of presubmit scripts. output_api: OutputAPI of presubmit scripts.
Invoked at change presubmit time. Verifies that updated non third-party code doesn't contain external copyrighted code. input_api: InputAPI of presubmit scripts. output_api: OutputAPI of presubmit scripts.
[ "Invoked", "at", "change", "presubmit", "time", ".", "Verifies", "that", "updated", "non", "third", "-", "party", "code", "doesn", "t", "contain", "external", "copyrighted", "code", ".", "input_api", ":", "InputAPI", "of", "presubmit", "scripts", ".", "output_api", ":", "OutputAPI", "of", "presubmit", "scripts", "." ]
def ScanAtPresubmit(input_api, output_api): """Invoked at change presubmit time. Verifies that updated non third-party code doesn't contain external copyrighted code. input_api: InputAPI of presubmit scripts. output_api: OutputAPI of presubmit scripts. """ files_to_check = set([]) deleted_files = set([]) whitelist_contents_changed = False for f in input_api.AffectedFiles(): if f.LocalPath() == _GetWhitelistFileName(input_api): whitelist_contents_changed = True deleted_files |= set(_ProcessWhitelistedFilesList( input_api, _GetDeletedContents(f))) continue if f.Action() != 'D': files_to_check.add(f.LocalPath()) else: deleted_files.add(f.LocalPath()) whitelisted_files = set(LoadWhitelistedFilesList(input_api)) if not whitelist_contents_changed: whitelisted_files &= files_to_check | deleted_files else: # Need to re-check the entire contents of the whitelist file. # Also add files removed from the whitelist. If the file has indeed been # deleted, the scanner will not complain. files_to_check |= whitelisted_files | deleted_files (unknown_files, missing_files, stale_files) = _DoScanAtPresubmit( input_api, list(whitelisted_files), list(files_to_check)) results = [] if unknown_files: results.append(output_api.PresubmitError( 'The following files contain a third-party license but are not in ' \ 'a listed third-party directory and are not whitelisted. You must ' \ 'add the following files to the whitelist file %s\n' \ '(Note that if the code you are adding does not actually contain ' \ 'any third-party code, it may contain the word "copyright", which ' \ 'should be masked out, e.g. by writing it as "copy-right"):' \ '' % _GetWhitelistFileName(input_api), sorted(unknown_files))) if missing_files: results.append(output_api.PresubmitPromptWarning( 'The following files are whitelisted in %s, ' \ 'but do not exist or not files:' % _GetWhitelistFileName(input_api), sorted(missing_files))) if stale_files: results.append(output_api.PresubmitPromptWarning( 'The following files are whitelisted unnecessarily. You must ' \ 'remove the following files from the whitelist file ' \ '%s:' % _GetWhitelistFileName(input_api), sorted(stale_files))) return results
[ "def", "ScanAtPresubmit", "(", "input_api", ",", "output_api", ")", ":", "files_to_check", "=", "set", "(", "[", "]", ")", "deleted_files", "=", "set", "(", "[", "]", ")", "whitelist_contents_changed", "=", "False", "for", "f", "in", "input_api", ".", "AffectedFiles", "(", ")", ":", "if", "f", ".", "LocalPath", "(", ")", "==", "_GetWhitelistFileName", "(", "input_api", ")", ":", "whitelist_contents_changed", "=", "True", "deleted_files", "|=", "set", "(", "_ProcessWhitelistedFilesList", "(", "input_api", ",", "_GetDeletedContents", "(", "f", ")", ")", ")", "continue", "if", "f", ".", "Action", "(", ")", "!=", "'D'", ":", "files_to_check", ".", "add", "(", "f", ".", "LocalPath", "(", ")", ")", "else", ":", "deleted_files", ".", "add", "(", "f", ".", "LocalPath", "(", ")", ")", "whitelisted_files", "=", "set", "(", "LoadWhitelistedFilesList", "(", "input_api", ")", ")", "if", "not", "whitelist_contents_changed", ":", "whitelisted_files", "&=", "files_to_check", "|", "deleted_files", "else", ":", "# Need to re-check the entire contents of the whitelist file.", "# Also add files removed from the whitelist. If the file has indeed been", "# deleted, the scanner will not complain.", "files_to_check", "|=", "whitelisted_files", "|", "deleted_files", "(", "unknown_files", ",", "missing_files", ",", "stale_files", ")", "=", "_DoScanAtPresubmit", "(", "input_api", ",", "list", "(", "whitelisted_files", ")", ",", "list", "(", "files_to_check", ")", ")", "results", "=", "[", "]", "if", "unknown_files", ":", "results", ".", "append", "(", "output_api", ".", "PresubmitError", "(", "'The following files contain a third-party license but are not in '", "'a listed third-party directory and are not whitelisted. You must '", "'add the following files to the whitelist file %s\\n'", "'(Note that if the code you are adding does not actually contain '", "'any third-party code, it may contain the word \"copyright\", which '", "'should be masked out, e.g. by writing it as \"copy-right\"):'", "''", "%", "_GetWhitelistFileName", "(", "input_api", ")", ",", "sorted", "(", "unknown_files", ")", ")", ")", "if", "missing_files", ":", "results", ".", "append", "(", "output_api", ".", "PresubmitPromptWarning", "(", "'The following files are whitelisted in %s, '", "'but do not exist or not files:'", "%", "_GetWhitelistFileName", "(", "input_api", ")", ",", "sorted", "(", "missing_files", ")", ")", ")", "if", "stale_files", ":", "results", ".", "append", "(", "output_api", ".", "PresubmitPromptWarning", "(", "'The following files are whitelisted unnecessarily. You must '", "'remove the following files from the whitelist file '", "'%s:'", "%", "_GetWhitelistFileName", "(", "input_api", ")", ",", "sorted", "(", "stale_files", ")", ")", ")", "return", "results" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/copyright_scanner/copyright_scanner.py#L350-L402
raspberrypi/tools
13474ee775d0c5ec8a7da4fb0a9fa84187abfc87
arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/share/gdb/python/gdb/command/explore.py
python
Explorer.explore_type
(name, datatype, is_child)
Main function to explore a data type. Arguments: name: The string representing the path to the data type being explored. datatype: The gdb.Type value of the data type being explored. is_child: Boolean value to indicate if the name is a child. A name is a child if it is derived from the main name entered by the user. For example, if the user entered the name of struct type, then when exploring the fields of the struct, is_child is set to True internally. Returns: No return value.
Main function to explore a data type.
[ "Main", "function", "to", "explore", "a", "data", "type", "." ]
def explore_type(name, datatype, is_child): """Main function to explore a data type. Arguments: name: The string representing the path to the data type being explored. datatype: The gdb.Type value of the data type being explored. is_child: Boolean value to indicate if the name is a child. A name is a child if it is derived from the main name entered by the user. For example, if the user entered the name of struct type, then when exploring the fields of the struct, is_child is set to True internally. Returns: No return value. """ type_code = datatype.code if type_code in Explorer.type_code_to_explorer_map: explorer_class = Explorer.type_code_to_explorer_map[type_code] while explorer_class.explore_type(name, datatype, is_child): pass else: print ("Explorer for type '%s' not yet available.\n" % str(datatype))
[ "def", "explore_type", "(", "name", ",", "datatype", ",", "is_child", ")", ":", "type_code", "=", "datatype", ".", "code", "if", "type_code", "in", "Explorer", ".", "type_code_to_explorer_map", ":", "explorer_class", "=", "Explorer", ".", "type_code_to_explorer_map", "[", "type_code", "]", "while", "explorer_class", ".", "explore_type", "(", "name", ",", "datatype", ",", "is_child", ")", ":", "pass", "else", ":", "print", "(", "\"Explorer for type '%s' not yet available.\\n\"", "%", "str", "(", "datatype", ")", ")" ]
https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/share/gdb/python/gdb/command/explore.py#L92-L115
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/saved_model/function_deserialization.py
python
_list_function_deps
(fdef, library_function_names, library_gradient_names)
return deps
Find functions referenced in `fdef`.
Find functions referenced in `fdef`.
[ "Find", "functions", "referenced", "in", "fdef", "." ]
def _list_function_deps(fdef, library_function_names, library_gradient_names): """Find functions referenced in `fdef`.""" # TODO(b/205023953): Recurse into list attributes and into NameAttrList attrs # both when listing deps and when fixing them. `function_def_to_graph` also # requires fixes. deps = set() for node_def in fdef.node_def: grad_op_type = _get_gradient_op_type(node_def) if node_def.op in library_function_names: deps.add(node_def.op) elif grad_op_type and grad_op_type in library_gradient_names: deps.add(library_gradient_names[grad_op_type]) else: for _, attr_value in node_def.attr.items(): if attr_value.WhichOneof("value") == "func": deps.add(attr_value.func.name) elif attr_value.WhichOneof("value") == "list": for fn in attr_value.list.func: deps.add(fn.name) return deps
[ "def", "_list_function_deps", "(", "fdef", ",", "library_function_names", ",", "library_gradient_names", ")", ":", "# TODO(b/205023953): Recurse into list attributes and into NameAttrList attrs", "# both when listing deps and when fixing them. `function_def_to_graph` also", "# requires fixes.", "deps", "=", "set", "(", ")", "for", "node_def", "in", "fdef", ".", "node_def", ":", "grad_op_type", "=", "_get_gradient_op_type", "(", "node_def", ")", "if", "node_def", ".", "op", "in", "library_function_names", ":", "deps", ".", "add", "(", "node_def", ".", "op", ")", "elif", "grad_op_type", "and", "grad_op_type", "in", "library_gradient_names", ":", "deps", ".", "add", "(", "library_gradient_names", "[", "grad_op_type", "]", ")", "else", ":", "for", "_", ",", "attr_value", "in", "node_def", ".", "attr", ".", "items", "(", ")", ":", "if", "attr_value", ".", "WhichOneof", "(", "\"value\"", ")", "==", "\"func\"", ":", "deps", ".", "add", "(", "attr_value", ".", "func", ".", "name", ")", "elif", "attr_value", ".", "WhichOneof", "(", "\"value\"", ")", "==", "\"list\"", ":", "for", "fn", "in", "attr_value", ".", "list", ".", "func", ":", "deps", ".", "add", "(", "fn", ".", "name", ")", "return", "deps" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/function_deserialization.py#L609-L629
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/elementwise/minimum.py
python
minimum.is_atom_convex
(self)
return False
Is the atom convex?
Is the atom convex?
[ "Is", "the", "atom", "convex?" ]
def is_atom_convex(self) -> bool: """Is the atom convex? """ return False
[ "def", "is_atom_convex", "(", "self", ")", "->", "bool", ":", "return", "False" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/minimum.py#L49-L52
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
IKObjective.setFixedPoint
(self, link, plocal, pworld)
return _robotsim.IKObjective_setFixedPoint(self, link, plocal, pworld)
setFixedPoint(IKObjective self, int link, double const [3] plocal, double const [3] pworld) Sets a fixed-point constraint.
setFixedPoint(IKObjective self, int link, double const [3] plocal, double const [3] pworld)
[ "setFixedPoint", "(", "IKObjective", "self", "int", "link", "double", "const", "[", "3", "]", "plocal", "double", "const", "[", "3", "]", "pworld", ")" ]
def setFixedPoint(self, link, plocal, pworld): """ setFixedPoint(IKObjective self, int link, double const [3] plocal, double const [3] pworld) Sets a fixed-point constraint. """ return _robotsim.IKObjective_setFixedPoint(self, link, plocal, pworld)
[ "def", "setFixedPoint", "(", "self", ",", "link", ",", "plocal", ",", "pworld", ")", ":", "return", "_robotsim", ".", "IKObjective_setFixedPoint", "(", "self", ",", "link", ",", "plocal", ",", "pworld", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L6232-L6241
johmathe/shotdetect
1ecf93a695c96fd7601a41ab5834f1117b9d7d50
tools/cpplint.py
python
CheckSectionSpacing
(filename, clean_lines, class_info, linenum, error)
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for additional blank line issues related to sections.
[ "Checks", "for", "additional", "blank", "line", "issues", "related", "to", "sections", "." ]
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.linenum <= 24 or linenum <= class_info.linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.linenum for i in range(class_info.linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1))
[ "def", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "class_info", ",", "linenum", ",", "error", ")", ":", "# Skip checks if the class is small, where small means 25 lines or less.", "# 25 lines seems like a good cutoff since that's the usual height of", "# terminals, and any class that can't fit in one screen can't really", "# be considered \"small\".", "#", "# Also skip checks if we are on the first line. This accounts for", "# classes that look like", "# class Foo { public: ... };", "#", "# If we didn't find the end of the class, last_line would be zero,", "# and the check will be skipped by the first condition.", "if", "(", "class_info", ".", "last_line", "-", "class_info", ".", "linenum", "<=", "24", "or", "linenum", "<=", "class_info", ".", "linenum", ")", ":", "return", "matched", "=", "Match", "(", "r'\\s*(public|protected|private):'", ",", "clean_lines", ".", "lines", "[", "linenum", "]", ")", "if", "matched", ":", "# Issue warning if the line before public/protected/private was", "# not a blank line, but don't do this if the previous line contains", "# \"class\" or \"struct\". This can happen two ways:", "# - We are at the beginning of the class.", "# - We are forward-declaring an inner class that is semantically", "# private, but needed to be public for implementation reasons.", "prev_line", "=", "clean_lines", ".", "lines", "[", "linenum", "-", "1", "]", "if", "(", "not", "IsBlankLine", "(", "prev_line", ")", "and", "not", "Search", "(", "r'\\b(class|struct)\\b'", ",", "prev_line", ")", ")", ":", "# Try a bit harder to find the beginning of the class. This is to", "# account for multi-line base-specifier lists, e.g.:", "# class Derived", "# : public Base {", "end_class_head", "=", "class_info", ".", "linenum", "for", "i", "in", "range", "(", "class_info", ".", "linenum", ",", "linenum", ")", ":", "if", "Search", "(", "r'\\{\\s*$'", ",", "clean_lines", ".", "lines", "[", "i", "]", ")", ":", "end_class_head", "=", "i", "break", "if", "end_class_head", "<", "linenum", "-", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/blank_line'", ",", "3", ",", "'\"%s:\" should be preceded by a blank line'", "%", "matched", ".", "group", "(", "1", ")", ")" ]
https://github.com/johmathe/shotdetect/blob/1ecf93a695c96fd7601a41ab5834f1117b9d7d50/tools/cpplint.py#L1918-L1967
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py
python
PeakIntegrationTableWidget.simple_integrate_peak
(self, background)
return sum_intensity
Integrate peak in a simple way. Refer to documentation of this interface :param background: :return:
Integrate peak in a simple way. Refer to documentation of this interface :param background: :return:
[ "Integrate", "peak", "in", "a", "simple", "way", ".", "Refer", "to", "documentation", "of", "this", "interface", ":", "param", "background", ":", ":", "return", ":" ]
def simple_integrate_peak(self, background): """ Integrate peak in a simple way. Refer to documentation of this interface :param background: :return: """ # Check assert self.rowCount() > 0, 'Table is empty!' assert isinstance(background, float) and background >= 0. # Integrate sum_intensity = 0. for i_row in range(self.rowCount()): intensity_i = self.get_cell_value(i_row, self._maskedIntensityColIndex) sum_intensity += intensity_i - background return sum_intensity
[ "def", "simple_integrate_peak", "(", "self", ",", "background", ")", ":", "# Check", "assert", "self", ".", "rowCount", "(", ")", ">", "0", ",", "'Table is empty!'", "assert", "isinstance", "(", "background", ",", "float", ")", "and", "background", ">=", "0.", "# Integrate", "sum_intensity", "=", "0.", "for", "i_row", "in", "range", "(", "self", ".", "rowCount", "(", ")", ")", ":", "intensity_i", "=", "self", ".", "get_cell_value", "(", "i_row", ",", "self", ".", "_maskedIntensityColIndex", ")", "sum_intensity", "+=", "intensity_i", "-", "background", "return", "sum_intensity" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L452-L468
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/ast.py
python
walk
(node)
Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
[ "Recursively", "yield", "all", "descendant", "nodes", "in", "the", "tree", "starting", "at", "*", "node", "*", "(", "including", "*", "node", "*", "itself", ")", "in", "no", "specified", "order", ".", "This", "is", "useful", "if", "you", "only", "want", "to", "modify", "nodes", "in", "place", "and", "don", "t", "care", "about", "the", "context", "." ]
def walk(node): """ Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: node = todo.popleft() todo.extend(iter_child_nodes(node)) yield node
[ "def", "walk", "(", "node", ")", ":", "from", "collections", "import", "deque", "todo", "=", "deque", "(", "[", "node", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "todo", ".", "extend", "(", "iter_child_nodes", "(", "node", ")", ")", "yield", "node" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/ast.py#L203-L214
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/node/variant.py
python
SkeletonNode.DefaultAttributes
(self)
return {'encoding' : ''}
If not specified, 'encoding' will actually default to the parent node's encoding.
If not specified, 'encoding' will actually default to the parent node's encoding.
[ "If", "not", "specified", "encoding", "will", "actually", "default", "to", "the", "parent", "node", "s", "encoding", "." ]
def DefaultAttributes(self): '''If not specified, 'encoding' will actually default to the parent node's encoding. ''' return {'encoding' : ''}
[ "def", "DefaultAttributes", "(", "self", ")", ":", "return", "{", "'encoding'", ":", "''", "}" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/node/variant.py#L22-L26
sonyxperiadev/WebGL
0299b38196f78c6d5f74bcf6fa312a3daee6de60
Tools/CodeCoverage/cov.py
python
parse_source_file
(file)
return f_source_list
Parse one source file and return a list of lines
Parse one source file and return a list of lines
[ "Parse", "one", "source", "file", "and", "return", "a", "list", "of", "lines" ]
def parse_source_file(file): """ Parse one source file and return a list of lines """ f_source_list = [] init_state = STATE_NOT_SEEN in_test_code = False nesting = 0 for line in open(file, "r"): code = line.split(":", 2)[-1] if not in_test_code and code.startswith("#ifdef BUILD_UNIT_TESTS"): in_test_code = 1 if in_test_code and code.startswith("#if"): nesting += 1 if in_test_code and code.startswith("#endif"): nesting -= 1 if not nesting: in_test_code = True if in_test_code: init_state = STATE_TEST_CODE else: init_state = STATE_NOT_SEEN f_source_list.append([init_state, line.split(":", 1)[1]]) return f_source_list
[ "def", "parse_source_file", "(", "file", ")", ":", "f_source_list", "=", "[", "]", "init_state", "=", "STATE_NOT_SEEN", "in_test_code", "=", "False", "nesting", "=", "0", "for", "line", "in", "open", "(", "file", ",", "\"r\"", ")", ":", "code", "=", "line", ".", "split", "(", "\":\"", ",", "2", ")", "[", "-", "1", "]", "if", "not", "in_test_code", "and", "code", ".", "startswith", "(", "\"#ifdef BUILD_UNIT_TESTS\"", ")", ":", "in_test_code", "=", "1", "if", "in_test_code", "and", "code", ".", "startswith", "(", "\"#if\"", ")", ":", "nesting", "+=", "1", "if", "in_test_code", "and", "code", ".", "startswith", "(", "\"#endif\"", ")", ":", "nesting", "-=", "1", "if", "not", "nesting", ":", "in_test_code", "=", "True", "if", "in_test_code", ":", "init_state", "=", "STATE_TEST_CODE", "else", ":", "init_state", "=", "STATE_NOT_SEEN", "f_source_list", ".", "append", "(", "[", "init_state", ",", "line", ".", "split", "(", "\":\"", ",", "1", ")", "[", "1", "]", "]", ")", "return", "f_source_list" ]
https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/CodeCoverage/cov.py#L83-L108
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/main_estimator.py
python
model_fn
(features, labels, mode, params)
Function specifying the model that is required by the `tf.estimator` API. Args: features: Input images labels: Labels of images mode: One of `ModeKeys.TRAIN`, `ModeKeys.EVAL` or 'ModeKeys.PREDICT' params: A dictionary of extra parameter that might be passed Returns: An instance of `tf.estimator.EstimatorSpec`
Function specifying the model that is required by the `tf.estimator` API.
[ "Function", "specifying", "the", "model", "that", "is", "required", "by", "the", "tf", ".", "estimator", "API", "." ]
def model_fn(features, labels, mode, params): """Function specifying the model that is required by the `tf.estimator` API. Args: features: Input images labels: Labels of images mode: One of `ModeKeys.TRAIN`, `ModeKeys.EVAL` or 'ModeKeys.PREDICT' params: A dictionary of extra parameter that might be passed Returns: An instance of `tf.estimator.EstimatorSpec` """ inputs = features if isinstance(inputs, dict): inputs = features["image"] config = params["config"] model = revnet.RevNet(config=config) if mode == tf.estimator.ModeKeys.TRAIN: global_step = tf.train.get_or_create_global_step() learning_rate = tf.train.piecewise_constant( global_step, config.lr_decay_steps, config.lr_list) optimizer = tf.train.MomentumOptimizer( learning_rate, momentum=config.momentum) logits, saved_hidden = model(inputs, training=True) grads, loss = model.compute_gradients(saved_hidden, labels, training=True) with tf.control_dependencies(model.get_updates_for(inputs)): train_op = optimizer.apply_gradients( zip(grads, model.trainable_variables), global_step=global_step) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) else: logits, _ = model(inputs, training=False) predictions = tf.argmax(logits, axis=1) probabilities = tf.nn.softmax(logits) if mode == tf.estimator.ModeKeys.EVAL: loss = model.compute_loss(labels=labels, logits=logits) return tf.estimator.EstimatorSpec( mode=mode, loss=loss, eval_metric_ops={ "accuracy": tf.metrics.accuracy(labels=labels, predictions=predictions) }) else: # mode == tf.estimator.ModeKeys.PREDICT result = { "classes": predictions, "probabilities": probabilities, } return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, export_outputs={ "classify": tf.estimator.export.PredictOutput(result) })
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "inputs", "=", "features", "if", "isinstance", "(", "inputs", ",", "dict", ")", ":", "inputs", "=", "features", "[", "\"image\"", "]", "config", "=", "params", "[", "\"config\"", "]", "model", "=", "revnet", ".", "RevNet", "(", "config", "=", "config", ")", "if", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ":", "global_step", "=", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")", "learning_rate", "=", "tf", ".", "train", ".", "piecewise_constant", "(", "global_step", ",", "config", ".", "lr_decay_steps", ",", "config", ".", "lr_list", ")", "optimizer", "=", "tf", ".", "train", ".", "MomentumOptimizer", "(", "learning_rate", ",", "momentum", "=", "config", ".", "momentum", ")", "logits", ",", "saved_hidden", "=", "model", "(", "inputs", ",", "training", "=", "True", ")", "grads", ",", "loss", "=", "model", ".", "compute_gradients", "(", "saved_hidden", ",", "labels", ",", "training", "=", "True", ")", "with", "tf", ".", "control_dependencies", "(", "model", ".", "get_updates_for", "(", "inputs", ")", ")", ":", "train_op", "=", "optimizer", ".", "apply_gradients", "(", "zip", "(", "grads", ",", "model", ".", "trainable_variables", ")", ",", "global_step", "=", "global_step", ")", "return", "tf", ".", "estimator", ".", "EstimatorSpec", "(", "mode", "=", "mode", ",", "loss", "=", "loss", ",", "train_op", "=", "train_op", ")", "else", ":", "logits", ",", "_", "=", "model", "(", "inputs", ",", "training", "=", "False", ")", "predictions", "=", "tf", ".", "argmax", "(", "logits", ",", "axis", "=", "1", ")", "probabilities", "=", "tf", ".", "nn", ".", "softmax", "(", "logits", ")", "if", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ":", "loss", "=", "model", ".", "compute_loss", "(", "labels", "=", "labels", ",", "logits", "=", "logits", ")", "return", "tf", ".", "estimator", ".", "EstimatorSpec", "(", "mode", "=", "mode", ",", "loss", "=", "loss", ",", "eval_metric_ops", "=", "{", "\"accuracy\"", ":", "tf", ".", "metrics", ".", "accuracy", "(", "labels", "=", "labels", ",", "predictions", "=", "predictions", ")", "}", ")", "else", ":", "# mode == tf.estimator.ModeKeys.PREDICT", "result", "=", "{", "\"classes\"", ":", "predictions", ",", "\"probabilities\"", ":", "probabilities", ",", "}", "return", "tf", ".", "estimator", ".", "EstimatorSpec", "(", "mode", "=", "mode", ",", "predictions", "=", "predictions", ",", "export_outputs", "=", "{", "\"classify\"", ":", "tf", ".", "estimator", ".", "export", ".", "PredictOutput", "(", "result", ")", "}", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/main_estimator.py#L30-L89
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/feature_selection/_mutual_info.py
python
mutual_info_classif
(X, y, discrete_features='auto', n_neighbors=3, copy=True, random_state=None)
return _estimate_mi(X, y, discrete_features, True, n_neighbors, copy, random_state)
Estimate mutual information for a discrete target variable. Mutual information (MI) [1]_ between two random variables is a non-negative value, which measures the dependency between the variables. It is equal to zero if and only if two random variables are independent, and higher values mean higher dependency. The function relies on nonparametric methods based on entropy estimation from k-nearest neighbors distances as described in [2]_ and [3]_. Both methods are based on the idea originally proposed in [4]_. It can be used for univariate features selection, read more in the :ref:`User Guide <univariate_feature_selection>`. Parameters ---------- X : array_like or sparse matrix, shape (n_samples, n_features) Feature matrix. y : array_like, shape (n_samples,) Target vector. discrete_features : {'auto', bool, array_like}, default 'auto' If bool, then determines whether to consider all features discrete or continuous. If array, then it should be either a boolean mask with shape (n_features,) or array with indices of discrete features. If 'auto', it is assigned to False for dense `X` and to True for sparse `X`. n_neighbors : int, default 3 Number of neighbors to use for MI estimation for continuous variables, see [2]_ and [3]_. Higher values reduce variance of the estimation, but could introduce a bias. copy : bool, default True Whether to make a copy of the given data. If set to False, the initial data will be overwritten. random_state : int, RandomState instance or None, optional, default None The seed of the pseudo random number generator for adding small noise to continuous variables in order to remove repeated values. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- mi : ndarray, shape (n_features,) Estimated mutual information between each feature and the target. Notes ----- 1. The term "discrete features" is used instead of naming them "categorical", because it describes the essence more accurately. For example, pixel intensities of an image are discrete features (but hardly categorical) and you will get better results if mark them as such. Also note, that treating a continuous variable as discrete and vice versa will usually give incorrect results, so be attentive about that. 2. True mutual information can't be negative. If its estimate turns out to be negative, it is replaced by zero. References ---------- .. [1] `Mutual Information <https://en.wikipedia.org/wiki/Mutual_information>`_ on Wikipedia. .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual information". Phys. Rev. E 69, 2004. .. [3] B. C. Ross "Mutual Information between Discrete and Continuous Data Sets". PLoS ONE 9(2), 2014. .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16
Estimate mutual information for a discrete target variable.
[ "Estimate", "mutual", "information", "for", "a", "discrete", "target", "variable", "." ]
def mutual_info_classif(X, y, discrete_features='auto', n_neighbors=3, copy=True, random_state=None): """Estimate mutual information for a discrete target variable. Mutual information (MI) [1]_ between two random variables is a non-negative value, which measures the dependency between the variables. It is equal to zero if and only if two random variables are independent, and higher values mean higher dependency. The function relies on nonparametric methods based on entropy estimation from k-nearest neighbors distances as described in [2]_ and [3]_. Both methods are based on the idea originally proposed in [4]_. It can be used for univariate features selection, read more in the :ref:`User Guide <univariate_feature_selection>`. Parameters ---------- X : array_like or sparse matrix, shape (n_samples, n_features) Feature matrix. y : array_like, shape (n_samples,) Target vector. discrete_features : {'auto', bool, array_like}, default 'auto' If bool, then determines whether to consider all features discrete or continuous. If array, then it should be either a boolean mask with shape (n_features,) or array with indices of discrete features. If 'auto', it is assigned to False for dense `X` and to True for sparse `X`. n_neighbors : int, default 3 Number of neighbors to use for MI estimation for continuous variables, see [2]_ and [3]_. Higher values reduce variance of the estimation, but could introduce a bias. copy : bool, default True Whether to make a copy of the given data. If set to False, the initial data will be overwritten. random_state : int, RandomState instance or None, optional, default None The seed of the pseudo random number generator for adding small noise to continuous variables in order to remove repeated values. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- mi : ndarray, shape (n_features,) Estimated mutual information between each feature and the target. Notes ----- 1. The term "discrete features" is used instead of naming them "categorical", because it describes the essence more accurately. For example, pixel intensities of an image are discrete features (but hardly categorical) and you will get better results if mark them as such. Also note, that treating a continuous variable as discrete and vice versa will usually give incorrect results, so be attentive about that. 2. True mutual information can't be negative. If its estimate turns out to be negative, it is replaced by zero. References ---------- .. [1] `Mutual Information <https://en.wikipedia.org/wiki/Mutual_information>`_ on Wikipedia. .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual information". Phys. Rev. E 69, 2004. .. [3] B. C. Ross "Mutual Information between Discrete and Continuous Data Sets". PLoS ONE 9(2), 2014. .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16 """ check_classification_targets(y) return _estimate_mi(X, y, discrete_features, True, n_neighbors, copy, random_state)
[ "def", "mutual_info_classif", "(", "X", ",", "y", ",", "discrete_features", "=", "'auto'", ",", "n_neighbors", "=", "3", ",", "copy", "=", "True", ",", "random_state", "=", "None", ")", ":", "check_classification_targets", "(", "y", ")", "return", "_estimate_mi", "(", "X", ",", "y", ",", "discrete_features", ",", "True", ",", "n_neighbors", ",", "copy", ",", "random_state", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_selection/_mutual_info.py#L374-L451
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/pickletools.py
python
read_uint1
(f)
r""" >>> import StringIO >>> read_uint1(StringIO.StringIO('\xff')) 255
r""" >>> import StringIO >>> read_uint1(StringIO.StringIO('\xff')) 255
[ "r", ">>>", "import", "StringIO", ">>>", "read_uint1", "(", "StringIO", ".", "StringIO", "(", "\\", "xff", "))", "255" ]
def read_uint1(f): r""" >>> import StringIO >>> read_uint1(StringIO.StringIO('\xff')) 255 """ data = f.read(1) if data: return ord(data) raise ValueError("not enough data in stream to read uint1")
[ "def", "read_uint1", "(", "f", ")", ":", "data", "=", "f", ".", "read", "(", "1", ")", "if", "data", ":", "return", "ord", "(", "data", ")", "raise", "ValueError", "(", "\"not enough data in stream to read uint1\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pickletools.py#L201-L211
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/ndlstm/python/lstm1d.py
python
sequence_softmax
(inputs, noutput, scope=None, name=None, linear_name=None)
return outputs
Run a softmax layer over all the time steps of an input sequence. Args: inputs: (length, batch_size, depth) tensor noutput: output depth scope: optional scope name name: optional name for output tensor linear_name: name for linear (pre-softmax) output Returns: A tensor of size (length, batch_size, noutput).
Run a softmax layer over all the time steps of an input sequence.
[ "Run", "a", "softmax", "layer", "over", "all", "the", "time", "steps", "of", "an", "input", "sequence", "." ]
def sequence_softmax(inputs, noutput, scope=None, name=None, linear_name=None): """Run a softmax layer over all the time steps of an input sequence. Args: inputs: (length, batch_size, depth) tensor noutput: output depth scope: optional scope name name: optional name for output tensor linear_name: name for linear (pre-softmax) output Returns: A tensor of size (length, batch_size, noutput). """ length, _, ninputs = _shape(inputs) inputs_u = array_ops.unstack(inputs) output_u = [] with variable_scope.variable_scope(scope, "SequenceSoftmax", [inputs]): initial_w = random_ops.truncated_normal([0 + ninputs, noutput], stddev=0.1) initial_b = constant_op.constant(0.1, shape=[noutput]) w = variables.model_variable("weights", initializer=initial_w) b = variables.model_variable("biases", initializer=initial_b) for i in xrange(length): with variable_scope.variable_scope(scope, "SequenceSoftmaxStep", [inputs_u[i]]): # TODO(tmb) consider using slim.fully_connected(..., # activation_fn=tf.nn.softmax) linear = nn_ops.xw_plus_b(inputs_u[i], w, b, name=linear_name) output = nn_ops.softmax(linear) output_u += [output] outputs = array_ops.stack(output_u, name=name) return outputs
[ "def", "sequence_softmax", "(", "inputs", ",", "noutput", ",", "scope", "=", "None", ",", "name", "=", "None", ",", "linear_name", "=", "None", ")", ":", "length", ",", "_", ",", "ninputs", "=", "_shape", "(", "inputs", ")", "inputs_u", "=", "array_ops", ".", "unstack", "(", "inputs", ")", "output_u", "=", "[", "]", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "\"SequenceSoftmax\"", ",", "[", "inputs", "]", ")", ":", "initial_w", "=", "random_ops", ".", "truncated_normal", "(", "[", "0", "+", "ninputs", ",", "noutput", "]", ",", "stddev", "=", "0.1", ")", "initial_b", "=", "constant_op", ".", "constant", "(", "0.1", ",", "shape", "=", "[", "noutput", "]", ")", "w", "=", "variables", ".", "model_variable", "(", "\"weights\"", ",", "initializer", "=", "initial_w", ")", "b", "=", "variables", ".", "model_variable", "(", "\"biases\"", ",", "initializer", "=", "initial_b", ")", "for", "i", "in", "xrange", "(", "length", ")", ":", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "\"SequenceSoftmaxStep\"", ",", "[", "inputs_u", "[", "i", "]", "]", ")", ":", "# TODO(tmb) consider using slim.fully_connected(...,", "# activation_fn=tf.nn.softmax)", "linear", "=", "nn_ops", ".", "xw_plus_b", "(", "inputs_u", "[", "i", "]", ",", "w", ",", "b", ",", "name", "=", "linear_name", ")", "output", "=", "nn_ops", ".", "softmax", "(", "linear", ")", "output_u", "+=", "[", "output", "]", "outputs", "=", "array_ops", ".", "stack", "(", "output_u", ",", "name", "=", "name", ")", "return", "outputs" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/ndlstm/python/lstm1d.py#L161-L192
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/patchcheck.py
python
reported_news
(file_paths)
return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next')) for p in file_paths)
Check if Misc/NEWS.d has been changed.
Check if Misc/NEWS.d has been changed.
[ "Check", "if", "Misc", "/", "NEWS", ".", "d", "has", "been", "changed", "." ]
def reported_news(file_paths): """Check if Misc/NEWS.d has been changed.""" return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next')) for p in file_paths)
[ "def", "reported_news", "(", "file_paths", ")", ":", "return", "any", "(", "p", ".", "startswith", "(", "os", ".", "path", ".", "join", "(", "'Misc'", ",", "'NEWS.d'", ",", "'next'", ")", ")", "for", "p", "in", "file_paths", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/patchcheck.py#L202-L205
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
FileCtrlEvent.GetDirectory
(*args, **kwargs)
return _controls_.FileCtrlEvent_GetDirectory(*args, **kwargs)
GetDirectory(self) -> String
GetDirectory(self) -> String
[ "GetDirectory", "(", "self", ")", "-", ">", "String" ]
def GetDirectory(*args, **kwargs): """GetDirectory(self) -> String""" return _controls_.FileCtrlEvent_GetDirectory(*args, **kwargs)
[ "def", "GetDirectory", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "FileCtrlEvent_GetDirectory", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L7706-L7708
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/bdb.py
python
_set_stopinfo
(self, stopframe, returnframe, stoplineno=0)
Set the attributes for stopping. If stoplineno is greater than or equal to 0, then stop at line greater than or equal to the stopline. If stoplineno is -1, then don't stop at all.
Set the attributes for stopping.
[ "Set", "the", "attributes", "for", "stopping", "." ]
def _set_stopinfo(self, stopframe, returnframe, stoplineno=0): """Set the attributes for stopping. If stoplineno is greater than or equal to 0, then stop at line greater than or equal to the stopline. If stoplineno is -1, then don't stop at all. """ self.stopframe = stopframe self.returnframe = returnframe self.quitting = False # stoplineno >= 0 means: stop at line >= the stoplineno # stoplineno -1 means: don't stop at all self.stoplineno = stoplineno
[ "def", "_set_stopinfo", "(", "self", ",", "stopframe", ",", "returnframe", ",", "stoplineno", "=", "0", ")", ":", "self", ".", "stopframe", "=", "stopframe", "self", ".", "returnframe", "=", "returnframe", "self", ".", "quitting", "=", "False", "# stoplineno >= 0 means: stop at line >= the stoplineno", "# stoplineno -1 means: don't stop at all", "self", ".", "stoplineno", "=", "stoplineno" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/bdb.py#L273-L285
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/quopri.py
python
encode
(input, output, quotetabs, header = 0)
Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. The 'header' flag indicates whether we are encoding spaces as _ as per RFC 1522.
Read 'input', apply quoted-printable encoding, and write to 'output'.
[ "Read", "input", "apply", "quoted", "-", "printable", "encoding", "and", "write", "to", "output", "." ]
def encode(input, output, quotetabs, header = 0): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. The 'header' flag indicates whether we are encoding spaces as _ as per RFC 1522. """ if b2a_qp is not None: data = input.read() odata = b2a_qp(data, quotetabs = quotetabs, header = header) output.write(odata) return def write(s, output=output, lineEnd='\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) elif s == '.': output.write(quote(s) + lineEnd) else: output.write(s + lineEnd) prevline = None while 1: line = input.readline() if not line: break outline = [] # Strip off any readline induced trailing newline stripped = '' if line[-1:] == '\n': line = line[:-1] stripped = '\n' # Calculate the un-length-limited encoded line for c in line: if needsquoting(c, quotetabs, header): c = quote(c) if header and c == ' ': outline.append('_') else: outline.append(c) # First, write out the previous line if prevline is not None: write(prevline) # Now see if we need any soft line breaks because of RFC-imposed # length limitations. Then do the thisline->prevline dance. thisline = EMPTYSTRING.join(outline) while len(thisline) > MAXLINESIZE: # Don't forget to include the soft line break `=' sign in the # length calculation! write(thisline[:MAXLINESIZE-1], lineEnd='=\n') thisline = thisline[MAXLINESIZE-1:] # Write out the current line prevline = thisline # Write out the last line, without a trailing newline if prevline is not None: write(prevline, lineEnd=stripped)
[ "def", "encode", "(", "input", ",", "output", ",", "quotetabs", ",", "header", "=", "0", ")", ":", "if", "b2a_qp", "is", "not", "None", ":", "data", "=", "input", ".", "read", "(", ")", "odata", "=", "b2a_qp", "(", "data", ",", "quotetabs", "=", "quotetabs", ",", "header", "=", "header", ")", "output", ".", "write", "(", "odata", ")", "return", "def", "write", "(", "s", ",", "output", "=", "output", ",", "lineEnd", "=", "'\\n'", ")", ":", "# RFC 1521 requires that the line ending in a space or tab must have", "# that trailing character encoded.", "if", "s", "and", "s", "[", "-", "1", ":", "]", "in", "' \\t'", ":", "output", ".", "write", "(", "s", "[", ":", "-", "1", "]", "+", "quote", "(", "s", "[", "-", "1", "]", ")", "+", "lineEnd", ")", "elif", "s", "==", "'.'", ":", "output", ".", "write", "(", "quote", "(", "s", ")", "+", "lineEnd", ")", "else", ":", "output", ".", "write", "(", "s", "+", "lineEnd", ")", "prevline", "=", "None", "while", "1", ":", "line", "=", "input", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "outline", "=", "[", "]", "# Strip off any readline induced trailing newline", "stripped", "=", "''", "if", "line", "[", "-", "1", ":", "]", "==", "'\\n'", ":", "line", "=", "line", "[", ":", "-", "1", "]", "stripped", "=", "'\\n'", "# Calculate the un-length-limited encoded line", "for", "c", "in", "line", ":", "if", "needsquoting", "(", "c", ",", "quotetabs", ",", "header", ")", ":", "c", "=", "quote", "(", "c", ")", "if", "header", "and", "c", "==", "' '", ":", "outline", ".", "append", "(", "'_'", ")", "else", ":", "outline", ".", "append", "(", "c", ")", "# First, write out the previous line", "if", "prevline", "is", "not", "None", ":", "write", "(", "prevline", ")", "# Now see if we need any soft line breaks because of RFC-imposed", "# length limitations. Then do the thisline->prevline dance.", "thisline", "=", "EMPTYSTRING", ".", "join", "(", "outline", ")", "while", "len", "(", "thisline", ")", ">", "MAXLINESIZE", ":", "# Don't forget to include the soft line break `=' sign in the", "# length calculation!", "write", "(", "thisline", "[", ":", "MAXLINESIZE", "-", "1", "]", ",", "lineEnd", "=", "'=\\n'", ")", "thisline", "=", "thisline", "[", "MAXLINESIZE", "-", "1", ":", "]", "# Write out the current line", "prevline", "=", "thisline", "# Write out the last line, without a trailing newline", "if", "prevline", "is", "not", "None", ":", "write", "(", "prevline", ",", "lineEnd", "=", "stripped", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/quopri.py#L42-L103
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py2/pygments/util.py
python
format_lines
(var_name, seq, raw=False, indent_level=0)
return '\n'.join(lines)
Formats a sequence of strings for output.
Formats a sequence of strings for output.
[ "Formats", "a", "sequence", "of", "strings", "for", "output", "." ]
def format_lines(var_name, seq, raw=False, indent_level=0): """Formats a sequence of strings for output.""" lines = [] base_indent = ' ' * indent_level * 4 inner_indent = ' ' * (indent_level + 1) * 4 lines.append(base_indent + var_name + ' = (') if raw: # These should be preformatted reprs of, say, tuples. for i in seq: lines.append(inner_indent + i + ',') else: for i in seq: # Force use of single quotes r = repr(i + '"') lines.append(inner_indent + r[:-2] + r[-1] + ',') lines.append(base_indent + ')') return '\n'.join(lines)
[ "def", "format_lines", "(", "var_name", ",", "seq", ",", "raw", "=", "False", ",", "indent_level", "=", "0", ")", ":", "lines", "=", "[", "]", "base_indent", "=", "' '", "*", "indent_level", "*", "4", "inner_indent", "=", "' '", "*", "(", "indent_level", "+", "1", ")", "*", "4", "lines", ".", "append", "(", "base_indent", "+", "var_name", "+", "' = ('", ")", "if", "raw", ":", "# These should be preformatted reprs of, say, tuples.", "for", "i", "in", "seq", ":", "lines", ".", "append", "(", "inner_indent", "+", "i", "+", "','", ")", "else", ":", "for", "i", "in", "seq", ":", "# Force use of single quotes", "r", "=", "repr", "(", "i", "+", "'\"'", ")", "lines", ".", "append", "(", "inner_indent", "+", "r", "[", ":", "-", "2", "]", "+", "r", "[", "-", "1", "]", "+", "','", ")", "lines", ".", "append", "(", "base_indent", "+", "')'", ")", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py2/pygments/util.py#L257-L273
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
TextBoxAttr.GetBottomMargin
(*args)
return _richtext.TextBoxAttr_GetBottomMargin(*args)
GetBottomMargin(self) -> TextAttrDimension GetBottomMargin(self) -> TextAttrDimension
GetBottomMargin(self) -> TextAttrDimension GetBottomMargin(self) -> TextAttrDimension
[ "GetBottomMargin", "(", "self", ")", "-", ">", "TextAttrDimension", "GetBottomMargin", "(", "self", ")", "-", ">", "TextAttrDimension" ]
def GetBottomMargin(*args): """ GetBottomMargin(self) -> TextAttrDimension GetBottomMargin(self) -> TextAttrDimension """ return _richtext.TextBoxAttr_GetBottomMargin(*args)
[ "def", "GetBottomMargin", "(", "*", "args", ")", ":", "return", "_richtext", ".", "TextBoxAttr_GetBottomMargin", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L656-L661
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/report.py
python
ReportHandler._GetQueryStringForOldUri
(self)
return query_string
Gets a new query string if old URI parameters are present. SID is a hash string generated from a page state dictionary which is created here from old URI request parameters. Returns: A query string if request parameters are from old URI, otherwise None.
Gets a new query string if old URI parameters are present.
[ "Gets", "a", "new", "query", "string", "if", "old", "URI", "parameters", "are", "present", "." ]
def _GetQueryStringForOldUri(self): """Gets a new query string if old URI parameters are present. SID is a hash string generated from a page state dictionary which is created here from old URI request parameters. Returns: A query string if request parameters are from old URI, otherwise None. """ masters = self.request.get('masters') bots = self.request.get('bots') tests = self.request.get('tests') checked = self.request.get('checked') if not (masters and bots and tests): return None # Page state is a list of chart state. Chart state is # a list of pair of test path and selected series which is used # to generate a chart on /report page. state = _CreatePageState(masters, bots, tests, checked) # Replace default separators to remove whitespace. state_json = json.dumps(state, separators=(',', ':')) state_id = short_uri.GenerateHash(state_json) # Save page state. if not ndb.Key(page_state.PageState, state_id).get(): page_state.PageState(id=state_id, value=state_json).put() query_string = 'sid=' + state_id if self.request.get('start_rev'): query_string += '&start_rev=' + self.request.get('start_rev') if self.request.get('end_rev'): query_string += '&end_rev=' + self.request.get('end_rev') if self.request.get('rev'): query_string += '&rev=' + self.request.get('rev') return query_string
[ "def", "_GetQueryStringForOldUri", "(", "self", ")", ":", "masters", "=", "self", ".", "request", ".", "get", "(", "'masters'", ")", "bots", "=", "self", ".", "request", ".", "get", "(", "'bots'", ")", "tests", "=", "self", ".", "request", ".", "get", "(", "'tests'", ")", "checked", "=", "self", ".", "request", ".", "get", "(", "'checked'", ")", "if", "not", "(", "masters", "and", "bots", "and", "tests", ")", ":", "return", "None", "# Page state is a list of chart state. Chart state is", "# a list of pair of test path and selected series which is used", "# to generate a chart on /report page.", "state", "=", "_CreatePageState", "(", "masters", ",", "bots", ",", "tests", ",", "checked", ")", "# Replace default separators to remove whitespace.", "state_json", "=", "json", ".", "dumps", "(", "state", ",", "separators", "=", "(", "','", ",", "':'", ")", ")", "state_id", "=", "short_uri", ".", "GenerateHash", "(", "state_json", ")", "# Save page state.", "if", "not", "ndb", ".", "Key", "(", "page_state", ".", "PageState", ",", "state_id", ")", ".", "get", "(", ")", ":", "page_state", ".", "PageState", "(", "id", "=", "state_id", ",", "value", "=", "state_json", ")", ".", "put", "(", ")", "query_string", "=", "'sid='", "+", "state_id", "if", "self", ".", "request", ".", "get", "(", "'start_rev'", ")", ":", "query_string", "+=", "'&start_rev='", "+", "self", ".", "request", ".", "get", "(", "'start_rev'", ")", "if", "self", ".", "request", ".", "get", "(", "'end_rev'", ")", ":", "query_string", "+=", "'&end_rev='", "+", "self", ".", "request", ".", "get", "(", "'end_rev'", ")", "if", "self", ".", "request", ".", "get", "(", "'rev'", ")", ":", "query_string", "+=", "'&rev='", "+", "self", ".", "request", ".", "get", "(", "'rev'", ")", "return", "query_string" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/report.py#L43-L80
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/sping/pid.py
python
Canvas.flush
(self)
Call this to indicate that any comamnds that have been issued \ but which might be buffered should be flushed to the screen
Call this to indicate that any comamnds that have been issued \ but which might be buffered should be flushed to the screen
[ "Call", "this", "to", "indicate", "that", "any", "comamnds", "that", "have", "been", "issued", "\\", "but", "which", "might", "be", "buffered", "should", "be", "flushed", "to", "the", "screen" ]
def flush(self): "Call this to indicate that any comamnds that have been issued \ but which might be buffered should be flushed to the screen" pass
[ "def", "flush", "(", "self", ")", ":", "pass" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/pid.py#L258-L262
MrMC/mrmc
5a8e460b2aec44f03eb9604cbd7681d4277dbb81
tools/EventClients/lib/python/xbmcclient.py
python
XBMCClient.send_keyboard_button
(self, button=None)
return self.send_button(map="KB", button=button)
Send a keyboard event to XBMC Keyword Arguments: button -- name of the keyboard button to send (same as in Keymap.xml)
Send a keyboard event to XBMC Keyword Arguments: button -- name of the keyboard button to send (same as in Keymap.xml)
[ "Send", "a", "keyboard", "event", "to", "XBMC", "Keyword", "Arguments", ":", "button", "--", "name", "of", "the", "keyboard", "button", "to", "send", "(", "same", "as", "in", "Keymap", ".", "xml", ")" ]
def send_keyboard_button(self, button=None): """Send a keyboard event to XBMC Keyword Arguments: button -- name of the keyboard button to send (same as in Keymap.xml) """ if not button: return return self.send_button(map="KB", button=button)
[ "def", "send_keyboard_button", "(", "self", ",", "button", "=", "None", ")", ":", "if", "not", "button", ":", "return", "return", "self", ".", "send_button", "(", "map", "=", "\"KB\"", ",", "button", "=", "button", ")" ]
https://github.com/MrMC/mrmc/blob/5a8e460b2aec44f03eb9604cbd7681d4277dbb81/tools/EventClients/lib/python/xbmcclient.py#L527-L534
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TFltRect.Save
(self, *args)
return _snap.TFltRect_Save(self, *args)
Save(TFltRect self, TSOut SOut) Parameters: SOut: TSOut &
Save(TFltRect self, TSOut SOut)
[ "Save", "(", "TFltRect", "self", "TSOut", "SOut", ")" ]
def Save(self, *args): """ Save(TFltRect self, TSOut SOut) Parameters: SOut: TSOut & """ return _snap.TFltRect_Save(self, *args)
[ "def", "Save", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TFltRect_Save", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L15166-L15174
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
ScrollHelper.GetViewStart
(*args, **kwargs)
return _windows_.ScrollHelper_GetViewStart(*args, **kwargs)
GetViewStart(self) -> Point Get the view start
GetViewStart(self) -> Point
[ "GetViewStart", "(", "self", ")", "-", ">", "Point" ]
def GetViewStart(*args, **kwargs): """ GetViewStart(self) -> Point Get the view start """ return _windows_.ScrollHelper_GetViewStart(*args, **kwargs)
[ "def", "GetViewStart", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "ScrollHelper_GetViewStart", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L191-L197
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/image/image.py
python
random_size_crop
(src, size, area, ratio, interp=2, **kwargs)
return center_crop(src, size, interp)
Randomly crop src with size. Randomize area and aspect ratio. Parameters ---------- src : NDArray Input image size : tuple of (int, int) Size of the crop formatted as (width, height). area : float in (0, 1] or tuple of (float, float) If tuple, minimum area and maximum area to be maintained after cropping If float, minimum area to be maintained after cropping, maximum area is set to 1.0 ratio : tuple of (float, float) Aspect ratio range as (min_aspect_ratio, max_aspect_ratio) interp: int, optional, default=2 Interpolation method. See resize_short for details. Returns ------- NDArray An `NDArray` containing the cropped image. Tuple A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the original image and (width, height) are the dimensions of the cropped image.
Randomly crop src with size. Randomize area and aspect ratio.
[ "Randomly", "crop", "src", "with", "size", ".", "Randomize", "area", "and", "aspect", "ratio", "." ]
def random_size_crop(src, size, area, ratio, interp=2, **kwargs): """Randomly crop src with size. Randomize area and aspect ratio. Parameters ---------- src : NDArray Input image size : tuple of (int, int) Size of the crop formatted as (width, height). area : float in (0, 1] or tuple of (float, float) If tuple, minimum area and maximum area to be maintained after cropping If float, minimum area to be maintained after cropping, maximum area is set to 1.0 ratio : tuple of (float, float) Aspect ratio range as (min_aspect_ratio, max_aspect_ratio) interp: int, optional, default=2 Interpolation method. See resize_short for details. Returns ------- NDArray An `NDArray` containing the cropped image. Tuple A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the original image and (width, height) are the dimensions of the cropped image. """ h, w, _ = src.shape src_area = h * w if 'min_area' in kwargs: warnings.warn('`min_area` is deprecated. Please use `area` instead.', DeprecationWarning) area = kwargs.pop('min_area') assert not kwargs, "unexpected keyword arguments for `random_size_crop`." if isinstance(area, numeric_types): area = (area, 1.0) for _ in range(10): target_area = random.uniform(area[0], area[1]) * src_area log_ratio = (np.log(ratio[0]), np.log(ratio[1])) new_ratio = np.exp(random.uniform(*log_ratio)) new_w = int(round(np.sqrt(target_area * new_ratio))) new_h = int(round(np.sqrt(target_area / new_ratio))) if new_w <= w and new_h <= h: x0 = random.randint(0, w - new_w) y0 = random.randint(0, h - new_h) out = fixed_crop(src, x0, y0, new_w, new_h, size, interp) return out, (x0, y0, new_w, new_h) # fall back to center_crop return center_crop(src, size, interp)
[ "def", "random_size_crop", "(", "src", ",", "size", ",", "area", ",", "ratio", ",", "interp", "=", "2", ",", "*", "*", "kwargs", ")", ":", "h", ",", "w", ",", "_", "=", "src", ".", "shape", "src_area", "=", "h", "*", "w", "if", "'min_area'", "in", "kwargs", ":", "warnings", ".", "warn", "(", "'`min_area` is deprecated. Please use `area` instead.'", ",", "DeprecationWarning", ")", "area", "=", "kwargs", ".", "pop", "(", "'min_area'", ")", "assert", "not", "kwargs", ",", "\"unexpected keyword arguments for `random_size_crop`.\"", "if", "isinstance", "(", "area", ",", "numeric_types", ")", ":", "area", "=", "(", "area", ",", "1.0", ")", "for", "_", "in", "range", "(", "10", ")", ":", "target_area", "=", "random", ".", "uniform", "(", "area", "[", "0", "]", ",", "area", "[", "1", "]", ")", "*", "src_area", "log_ratio", "=", "(", "np", ".", "log", "(", "ratio", "[", "0", "]", ")", ",", "np", ".", "log", "(", "ratio", "[", "1", "]", ")", ")", "new_ratio", "=", "np", ".", "exp", "(", "random", ".", "uniform", "(", "*", "log_ratio", ")", ")", "new_w", "=", "int", "(", "round", "(", "np", ".", "sqrt", "(", "target_area", "*", "new_ratio", ")", ")", ")", "new_h", "=", "int", "(", "round", "(", "np", ".", "sqrt", "(", "target_area", "/", "new_ratio", ")", ")", ")", "if", "new_w", "<=", "w", "and", "new_h", "<=", "h", ":", "x0", "=", "random", ".", "randint", "(", "0", ",", "w", "-", "new_w", ")", "y0", "=", "random", ".", "randint", "(", "0", ",", "h", "-", "new_h", ")", "out", "=", "fixed_crop", "(", "src", ",", "x0", ",", "y0", ",", "new_w", ",", "new_h", ",", "size", ",", "interp", ")", "return", "out", ",", "(", "x0", ",", "y0", ",", "new_w", ",", "new_h", ")", "# fall back to center_crop", "return", "center_crop", "(", "src", ",", "size", ",", "interp", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/image/image.py#L550-L602
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py
python
FieldMask.FromJsonString
(self, value)
Converts string to FieldMask according to proto3 JSON spec.
Converts string to FieldMask according to proto3 JSON spec.
[ "Converts", "string", "to", "FieldMask", "according", "to", "proto3", "JSON", "spec", "." ]
def FromJsonString(self, value): """Converts string to FieldMask according to proto3 JSON spec.""" self.Clear() for path in value.split(','): self.paths.append(path)
[ "def", "FromJsonString", "(", "self", ",", "value", ")", ":", "self", ".", "Clear", "(", ")", "for", "path", "in", "value", ".", "split", "(", "','", ")", ":", "self", ".", "paths", ".", "append", "(", "path", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py#L384-L388
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/xcodeproj_file.py
python
XCObject._SetDefaultsFromSchema
(self)
Assign object default values according to the schema. This will not overwrite properties that have already been set.
Assign object default values according to the schema. This will not overwrite properties that have already been set.
[ "Assign", "object", "default", "values", "according", "to", "the", "schema", ".", "This", "will", "not", "overwrite", "properties", "that", "have", "already", "been", "set", "." ]
def _SetDefaultsFromSchema(self): """Assign object default values according to the schema. This will not overwrite properties that have already been set.""" defaults = {} for property, attributes in self._schema.iteritems(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and len(attributes) >= 5 and \ not property in self._properties: default = attributes[4] defaults[property] = default if len(defaults) > 0: # Use do_copy=True so that each new object gets its own copy of strong # objects, lists, and dicts. self.UpdateProperties(defaults, do_copy=True)
[ "def", "_SetDefaultsFromSchema", "(", "self", ")", ":", "defaults", "=", "{", "}", "for", "property", ",", "attributes", "in", "self", ".", "_schema", ".", "iteritems", "(", ")", ":", "(", "is_list", ",", "property_type", ",", "is_strong", ",", "is_required", ")", "=", "attributes", "[", "0", ":", "4", "]", "if", "is_required", "and", "len", "(", "attributes", ")", ">=", "5", "and", "not", "property", "in", "self", ".", "_properties", ":", "default", "=", "attributes", "[", "4", "]", "defaults", "[", "property", "]", "=", "default", "if", "len", "(", "defaults", ")", ">", "0", ":", "# Use do_copy=True so that each new object gets its own copy of strong", "# objects, lists, and dicts.", "self", ".", "UpdateProperties", "(", "defaults", ",", "do_copy", "=", "True", ")" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/xcodeproj_file.py#L873-L889
opencv/opencv
76aff8478883858f0e46746044348ebb16dc3c67
samples/dnn/dnn_model_runner/dnn_conversion/paddlepaddle/paddle_resnet50.py
python
export_onnx_resnet50
(save_path)
export PaddlePaddle model to ONNX format Args: save_path(str): Path to save exported ONNX model Returns: None
export PaddlePaddle model to ONNX format
[ "export", "PaddlePaddle", "model", "to", "ONNX", "format" ]
def export_onnx_resnet50(save_path): ''' export PaddlePaddle model to ONNX format Args: save_path(str): Path to save exported ONNX model Returns: None ''' model = hub.Module(name="resnet50_vd_imagenet_ssld") input_spec = paddle.static.InputSpec( [1, 3, 224, 224], "float32", "image") paddle.onnx.export(model, save_path, input_spec=[input_spec], opset_version=10)
[ "def", "export_onnx_resnet50", "(", "save_path", ")", ":", "model", "=", "hub", ".", "Module", "(", "name", "=", "\"resnet50_vd_imagenet_ssld\"", ")", "input_spec", "=", "paddle", ".", "static", ".", "InputSpec", "(", "[", "1", ",", "3", ",", "224", ",", "224", "]", ",", "\"float32\"", ",", "\"image\"", ")", "paddle", ".", "onnx", ".", "export", "(", "model", ",", "save_path", ",", "input_spec", "=", "[", "input_spec", "]", ",", "opset_version", "=", "10", ")" ]
https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/samples/dnn/dnn_model_runner/dnn_conversion/paddlepaddle/paddle_resnet50.py#L27-L41
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/importIFClegacy.py
python
IfcFile.parseLine
(self, line)
return {"id": id, "name": name, "attributes": self.parseAttributes(name, attrs)}
Parse a line
Parse a line
[ "Parse", "a", "line" ]
def parseLine(self, line): """ Parse a line """ m = IFCLINE_RE.search(line) # id,name,attrs if m: id, name, attrs = m.groups() id = id.strip() name = name.strip() attrs = attrs.strip() else: return False return {"id": id, "name": name, "attributes": self.parseAttributes(name, attrs)}
[ "def", "parseLine", "(", "self", ",", "line", ")", ":", "m", "=", "IFCLINE_RE", ".", "search", "(", "line", ")", "# id,name,attrs", "if", "m", ":", "id", ",", "name", ",", "attrs", "=", "m", ".", "groups", "(", ")", "id", "=", "id", ".", "strip", "(", ")", "name", "=", "name", ".", "strip", "(", ")", "attrs", "=", "attrs", ".", "strip", "(", ")", "else", ":", "return", "False", "return", "{", "\"id\"", ":", "id", ",", "\"name\"", ":", "name", ",", "\"attributes\"", ":", "self", ".", "parseAttributes", "(", "name", ",", "attrs", ")", "}" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/importIFClegacy.py#L1548-L1561
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py
python
Counter.update
(*args, **kwds)
Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4
Like dict.update() but add counts instead of replacing them.
[ "Like", "dict", ".", "update", "()", "but", "add", "counts", "instead", "of", "replacing", "them", "." ]
def update(*args, **kwds): '''Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 ''' # The regular dict.update() operation makes no sense here because the # replace behavior results in the some of original untouched counts # being mixed-in with all of the other counts for a mismash that # doesn't have a straight-forward interpretation in most counting # contexts. Instead, we implement straight-addition. Both the inputs # and outputs are allowed to contain zero and negative counts. if not args: raise TypeError("descriptor 'update' of 'Counter' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) iterable = args[0] if args else None if iterable is not None: if isinstance(iterable, _collections_abc.Mapping): if self: self_get = self.get for elem, count in iterable.items(): self[elem] = count + self_get(elem, 0) else: super(Counter, self).update(iterable) # fast path when counter is empty else: _count_elements(self, iterable) if kwds: self.update(kwds)
[ "def", "update", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "# The regular dict.update() operation makes no sense here because the", "# replace behavior results in the some of original untouched counts", "# being mixed-in with all of the other counts for a mismash that", "# doesn't have a straight-forward interpretation in most counting", "# contexts. Instead, we implement straight-addition. Both the inputs", "# and outputs are allowed to contain zero and negative counts.", "if", "not", "args", ":", "raise", "TypeError", "(", "\"descriptor 'update' of 'Counter' object \"", "\"needs an argument\"", ")", "self", ",", "", "*", "args", "=", "args", "if", "len", "(", "args", ")", ">", "1", ":", "raise", "TypeError", "(", "'expected at most 1 arguments, got %d'", "%", "len", "(", "args", ")", ")", "iterable", "=", "args", "[", "0", "]", "if", "args", "else", "None", "if", "iterable", "is", "not", "None", ":", "if", "isinstance", "(", "iterable", ",", "_collections_abc", ".", "Mapping", ")", ":", "if", "self", ":", "self_get", "=", "self", ".", "get", "for", "elem", ",", "count", "in", "iterable", ".", "items", "(", ")", ":", "self", "[", "elem", "]", "=", "count", "+", "self_get", "(", "elem", ",", "0", ")", "else", ":", "super", "(", "Counter", ",", "self", ")", ".", "update", "(", "iterable", ")", "# fast path when counter is empty", "else", ":", "_count_elements", "(", "self", ",", "iterable", ")", "if", "kwds", ":", "self", ".", "update", "(", "kwds", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py#L619-L657
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py
python
SysLogHandler.mapPriority
(self, levelName)
return self.priority_map.get(levelName, "warning")
Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can't do a straightforward mapping by lowercasing the logging level name because of locale- specific issues (see SF #1524081).
Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can't do a straightforward mapping by lowercasing the logging level name because of locale- specific issues (see SF #1524081).
[ "Map", "a", "logging", "level", "name", "to", "a", "key", "in", "the", "priority_names", "map", ".", "This", "is", "useful", "in", "two", "scenarios", ":", "when", "custom", "levels", "are", "being", "used", "and", "in", "the", "case", "where", "you", "can", "t", "do", "a", "straightforward", "mapping", "by", "lowercasing", "the", "logging", "level", "name", "because", "of", "locale", "-", "specific", "issues", "(", "see", "SF", "#1524081", ")", "." ]
def mapPriority(self, levelName): """ Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can't do a straightforward mapping by lowercasing the logging level name because of locale- specific issues (see SF #1524081). """ return self.priority_map.get(levelName, "warning")
[ "def", "mapPriority", "(", "self", ",", "levelName", ")", ":", "return", "self", ".", "priority_map", ".", "get", "(", "levelName", ",", "\"warning\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py#L897-L905
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py
python
Index._sort_levels_monotonic
(self)
return self
Compat with MultiIndex.
Compat with MultiIndex.
[ "Compat", "with", "MultiIndex", "." ]
def _sort_levels_monotonic(self): """ Compat with MultiIndex. """ return self
[ "def", "_sort_levels_monotonic", "(", "self", ")", ":", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L1390-L1394
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/number-of-substrings-containing-all-three-characters.py
python
Solution2.numberOfSubstrings
(self, s)
return result
:type s: str :rtype: int
:type s: str :rtype: int
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "int" ]
def numberOfSubstrings(self, s): """ :type s: str :rtype: int """ result, left, count = 0, 0, [0]*3 for right, c in enumerate(s): count[ord(s[right])-ord('a')] += 1 while all(count): count[ord(s[left])-ord('a')] -= 1 left += 1 result += left return result
[ "def", "numberOfSubstrings", "(", "self", ",", "s", ")", ":", "result", ",", "left", ",", "count", "=", "0", ",", "0", ",", "[", "0", "]", "*", "3", "for", "right", ",", "c", "in", "enumerate", "(", "s", ")", ":", "count", "[", "ord", "(", "s", "[", "right", "]", ")", "-", "ord", "(", "'a'", ")", "]", "+=", "1", "while", "all", "(", "count", ")", ":", "count", "[", "ord", "(", "s", "[", "left", "]", ")", "-", "ord", "(", "'a'", ")", "]", "-=", "1", "left", "+=", "1", "result", "+=", "left", "return", "result" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/number-of-substrings-containing-all-three-characters.py#L20-L32
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/service_reflection.py
python
_ServiceBuilder._CallMethod
(self, srvc, method_descriptor, rpc_controller, request, callback)
return method(rpc_controller, request, callback)
Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method's execution. request: Request protocol message. callback: A callback to invoke after the method has completed.
Calls the method described by a given method descriptor.
[ "Calls", "the", "method", "described", "by", "a", "given", "method", "descriptor", "." ]
def _CallMethod(self, srvc, method_descriptor, rpc_controller, request, callback): """Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method's execution. request: Request protocol message. callback: A callback to invoke after the method has completed. """ if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'CallMethod() given method descriptor for wrong service type.') method = getattr(srvc, method_descriptor.name) return method(rpc_controller, request, callback)
[ "def", "_CallMethod", "(", "self", ",", "srvc", ",", "method_descriptor", ",", "rpc_controller", ",", "request", ",", "callback", ")", ":", "if", "method_descriptor", ".", "containing_service", "!=", "self", ".", "descriptor", ":", "raise", "RuntimeError", "(", "'CallMethod() given method descriptor for wrong service type.'", ")", "method", "=", "getattr", "(", "srvc", ",", "method_descriptor", ".", "name", ")", "return", "method", "(", "rpc_controller", ",", "request", ",", "callback", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/service_reflection.py#L159-L174
nileshkulkarni/csm
0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc
csm/utils/bird_vis.py
python
VisRenderer.__call__
(self, verts, cams=None, texture=None, rend_mask=False)
return rend.astype(np.uint8)
verts is |V| x 3 cuda torch Variable cams is 7, cuda torch Variable Returns N x N x 3 numpy
verts is |V| x 3 cuda torch Variable cams is 7, cuda torch Variable Returns N x N x 3 numpy
[ "verts", "is", "|V|", "x", "3", "cuda", "torch", "Variable", "cams", "is", "7", "cuda", "torch", "Variable", "Returns", "N", "x", "N", "x", "3", "numpy" ]
def __call__(self, verts, cams=None, texture=None, rend_mask=False): """ verts is |V| x 3 cuda torch Variable cams is 7, cuda torch Variable Returns N x N x 3 numpy """ if texture is None: texture = self.default_tex elif texture.dim() == 5: # Here input it F x T x T x T x 3 (instead of F x T x T x 3) # So add batch dim. texture = torch.unsqueeze(texture, 0) if cams is None: cams = self.default_cam elif cams.dim() == 1: cams = torch.unsqueeze(cams, 0) if verts.dim() == 2: verts = torch.unsqueeze(verts, 0) verts = asVariable(verts) cams = asVariable(cams) texture = asVariable(texture) if rend_mask: rend = self.renderer.forward(verts, self.faces, cams) rend = rend.repeat(3, 1, 1) rend = rend.unsqueeze(0) else: rend = self.renderer.forward(verts, self.faces, cams, texture) rend = rend.data.cpu().numpy()[0].transpose((1, 2, 0)) rend = np.clip(rend, 0, 1) * 255.0 return rend.astype(np.uint8)
[ "def", "__call__", "(", "self", ",", "verts", ",", "cams", "=", "None", ",", "texture", "=", "None", ",", "rend_mask", "=", "False", ")", ":", "if", "texture", "is", "None", ":", "texture", "=", "self", ".", "default_tex", "elif", "texture", ".", "dim", "(", ")", "==", "5", ":", "# Here input it F x T x T x T x 3 (instead of F x T x T x 3)", "# So add batch dim.", "texture", "=", "torch", ".", "unsqueeze", "(", "texture", ",", "0", ")", "if", "cams", "is", "None", ":", "cams", "=", "self", ".", "default_cam", "elif", "cams", ".", "dim", "(", ")", "==", "1", ":", "cams", "=", "torch", ".", "unsqueeze", "(", "cams", ",", "0", ")", "if", "verts", ".", "dim", "(", ")", "==", "2", ":", "verts", "=", "torch", ".", "unsqueeze", "(", "verts", ",", "0", ")", "verts", "=", "asVariable", "(", "verts", ")", "cams", "=", "asVariable", "(", "cams", ")", "texture", "=", "asVariable", "(", "texture", ")", "if", "rend_mask", ":", "rend", "=", "self", ".", "renderer", ".", "forward", "(", "verts", ",", "self", ".", "faces", ",", "cams", ")", "rend", "=", "rend", ".", "repeat", "(", "3", ",", "1", ",", "1", ")", "rend", "=", "rend", ".", "unsqueeze", "(", "0", ")", "else", ":", "rend", "=", "self", ".", "renderer", ".", "forward", "(", "verts", ",", "self", ".", "faces", ",", "cams", ",", "texture", ")", "rend", "=", "rend", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "[", "0", "]", ".", "transpose", "(", "(", "1", ",", "2", ",", "0", ")", ")", "rend", "=", "np", ".", "clip", "(", "rend", ",", "0", ",", "1", ")", "*", "255.0", "return", "rend", ".", "astype", "(", "np", ".", "uint8", ")" ]
https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/utils/bird_vis.py#L58-L92
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/collection.py
python
ResourceCollection.filter
(self, **kwargs)
return self._clone(**kwargs)
Get items from the collection, passing keyword arguments along as parameters to the underlying service operation, which are typically used to filter the results. This method returns an iterable generator which yields individual resource instances. Example use:: # Iterate through items >>> for queue in sqs.queues.filter(Param='foo'): ... print(queue.url) 'https://url1' 'https://url2' # Convert to list >>> queues = list(sqs.queues.filter(Param='foo')) >>> len(queues) 2 :rtype: :py:class:`ResourceCollection`
Get items from the collection, passing keyword arguments along as parameters to the underlying service operation, which are typically used to filter the results.
[ "Get", "items", "from", "the", "collection", "passing", "keyword", "arguments", "along", "as", "parameters", "to", "the", "underlying", "service", "operation", "which", "are", "typically", "used", "to", "filter", "the", "results", "." ]
def filter(self, **kwargs): """ Get items from the collection, passing keyword arguments along as parameters to the underlying service operation, which are typically used to filter the results. This method returns an iterable generator which yields individual resource instances. Example use:: # Iterate through items >>> for queue in sqs.queues.filter(Param='foo'): ... print(queue.url) 'https://url1' 'https://url2' # Convert to list >>> queues = list(sqs.queues.filter(Param='foo')) >>> len(queues) 2 :rtype: :py:class:`ResourceCollection` """ return self._clone(**kwargs)
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_clone", "(", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/collection.py#L204-L226
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/database.py
python
Distribution.name_and_version
(self)
return '%s (%s)' % (self.name, self.version)
A utility property which displays the name and version in parentheses.
A utility property which displays the name and version in parentheses.
[ "A", "utility", "property", "which", "displays", "the", "name", "and", "version", "in", "parentheses", "." ]
def name_and_version(self): """ A utility property which displays the name and version in parentheses. """ return '%s (%s)' % (self.name, self.version)
[ "def", "name_and_version", "(", "self", ")", ":", "return", "'%s (%s)'", "%", "(", "self", ".", "name", ",", "self", ".", "version", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/database.py#L362-L366
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/msvs_emulation.py
python
MsvsSettings._GetPchFlags
(self, config, extension)
return []
Get the flags to be added to the cflags for precompiled header support.
Get the flags to be added to the cflags for precompiled header support.
[ "Get", "the", "flags", "to", "be", "added", "to", "the", "cflags", "for", "precompiled", "header", "support", "." ]
def _GetPchFlags(self, config, extension): """Get the flags to be added to the cflags for precompiled header support. """ config = self._TargetConfig(config) # The PCH is only built once by a particular source file. Usage of PCH must # only be for the same language (i.e. C vs. C++), so only include the pch # flags when the language matches. if self.msvs_precompiled_header[config]: source_ext = os.path.splitext(self.msvs_precompiled_source[config])[1] if _LanguageMatchesForPch(source_ext, extension): pch = self.msvs_precompiled_header[config] pchbase = os.path.split(pch)[1] return ['/Yu' + pch, '/FI' + pch, '/Fp${pchprefix}.' + pchbase + '.pch'] return []
[ "def", "_GetPchFlags", "(", "self", ",", "config", ",", "extension", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "# The PCH is only built once by a particular source file. Usage of PCH must", "# only be for the same language (i.e. C vs. C++), so only include the pch", "# flags when the language matches.", "if", "self", ".", "msvs_precompiled_header", "[", "config", "]", ":", "source_ext", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "msvs_precompiled_source", "[", "config", "]", ")", "[", "1", "]", "if", "_LanguageMatchesForPch", "(", "source_ext", ",", "extension", ")", ":", "pch", "=", "self", ".", "msvs_precompiled_header", "[", "config", "]", "pchbase", "=", "os", ".", "path", ".", "split", "(", "pch", ")", "[", "1", "]", "return", "[", "'/Yu'", "+", "pch", ",", "'/FI'", "+", "pch", ",", "'/Fp${pchprefix}.'", "+", "pchbase", "+", "'.pch'", "]", "return", "[", "]" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/msvs_emulation.py#L446-L459
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/estimator/estimator.py
python
Estimator.get_variable_value
(self, name)
return training.load_variable(self.model_dir, name)
Returns value of the variable given by name. Args: name: string or a list of string, name of the tensor. Returns: Numpy array - value of the tensor. Raises: ValueError: If the Estimator has not produced a checkpoint yet.
Returns value of the variable given by name.
[ "Returns", "value", "of", "the", "variable", "given", "by", "name", "." ]
def get_variable_value(self, name): """Returns value of the variable given by name. Args: name: string or a list of string, name of the tensor. Returns: Numpy array - value of the tensor. Raises: ValueError: If the Estimator has not produced a checkpoint yet. """ _check_checkpoint_available(self.model_dir) return training.load_variable(self.model_dir, name)
[ "def", "get_variable_value", "(", "self", ",", "name", ")", ":", "_check_checkpoint_available", "(", "self", ".", "model_dir", ")", "return", "training", ".", "load_variable", "(", "self", ".", "model_dir", ",", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/estimator/estimator.py#L209-L222
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/feature_selection/univariate_selection.py
python
f_regression
(X, y, center=True)
return F, pv
Univariate linear regression tests. Quick linear model for testing the effect of a single regressor, sequentially for many regressors. This is done in 2 steps: 1. The cross correlation between each regressor and the target is computed, that is, ((X[:, i] - mean(X[:, i])) * (y - mean_y)) / (std(X[:, i]) * std(y)). 2. It is converted to an F score then to a p-value. Read more in the :ref:`User Guide <univariate_feature_selection>`. Parameters ---------- X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will be tested sequentially. y : array of shape(n_samples). The data matrix center : True, bool, If true, X and y will be centered. Returns ------- F : array, shape=(n_features,) F values of features. pval : array, shape=(n_features,) p-values of F-scores. See also -------- f_classif: ANOVA F-value between label/feature for classification tasks. chi2: Chi-squared stats of non-negative features for classification tasks.
Univariate linear regression tests.
[ "Univariate", "linear", "regression", "tests", "." ]
def f_regression(X, y, center=True): """Univariate linear regression tests. Quick linear model for testing the effect of a single regressor, sequentially for many regressors. This is done in 2 steps: 1. The cross correlation between each regressor and the target is computed, that is, ((X[:, i] - mean(X[:, i])) * (y - mean_y)) / (std(X[:, i]) * std(y)). 2. It is converted to an F score then to a p-value. Read more in the :ref:`User Guide <univariate_feature_selection>`. Parameters ---------- X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will be tested sequentially. y : array of shape(n_samples). The data matrix center : True, bool, If true, X and y will be centered. Returns ------- F : array, shape=(n_features,) F values of features. pval : array, shape=(n_features,) p-values of F-scores. See also -------- f_classif: ANOVA F-value between label/feature for classification tasks. chi2: Chi-squared stats of non-negative features for classification tasks. """ if issparse(X) and center: raise ValueError("center=True only allowed for dense data") X, y = check_X_y(X, y, ['csr', 'csc', 'coo'], dtype=np.float64) if center: y = y - np.mean(y) X = X.copy('F') # faster in fortran X -= X.mean(axis=0) # compute the correlation corr = safe_sparse_dot(y, X) corr /= row_norms(X.T) corr /= norm(y) # convert to p-value degrees_of_freedom = y.size - (2 if center else 1) F = corr ** 2 / (1 - corr ** 2) * degrees_of_freedom pv = stats.f.sf(F, 1, degrees_of_freedom) return F, pv
[ "def", "f_regression", "(", "X", ",", "y", ",", "center", "=", "True", ")", ":", "if", "issparse", "(", "X", ")", "and", "center", ":", "raise", "ValueError", "(", "\"center=True only allowed for dense data\"", ")", "X", ",", "y", "=", "check_X_y", "(", "X", ",", "y", ",", "[", "'csr'", ",", "'csc'", ",", "'coo'", "]", ",", "dtype", "=", "np", ".", "float64", ")", "if", "center", ":", "y", "=", "y", "-", "np", ".", "mean", "(", "y", ")", "X", "=", "X", ".", "copy", "(", "'F'", ")", "# faster in fortran", "X", "-=", "X", ".", "mean", "(", "axis", "=", "0", ")", "# compute the correlation", "corr", "=", "safe_sparse_dot", "(", "y", ",", "X", ")", "corr", "/=", "row_norms", "(", "X", ".", "T", ")", "corr", "/=", "norm", "(", "y", ")", "# convert to p-value", "degrees_of_freedom", "=", "y", ".", "size", "-", "(", "2", "if", "center", "else", "1", ")", "F", "=", "corr", "**", "2", "/", "(", "1", "-", "corr", "**", "2", ")", "*", "degrees_of_freedom", "pv", "=", "stats", ".", "f", ".", "sf", "(", "F", ",", "1", ",", "degrees_of_freedom", ")", "return", "F", ",", "pv" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/feature_selection/univariate_selection.py#L230-L286
cinder/Cinder
e83f5bb9c01a63eec20168d02953a0879e5100f7
docs/libs/pystache/context.py
python
ContextStack.pop
(self)
return self._stack.pop()
Pop an item off of the stack, and return it.
Pop an item off of the stack, and return it.
[ "Pop", "an", "item", "off", "of", "the", "stack", "and", "return", "it", "." ]
def pop(self): """ Pop an item off of the stack, and return it. """ return self._stack.pop()
[ "def", "pop", "(", "self", ")", ":", "return", "self", ".", "_stack", ".", "pop", "(", ")" ]
https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/pystache/context.py#L323-L328
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
VideoMode.IsOk
(*args, **kwargs)
return _misc_.VideoMode_IsOk(*args, **kwargs)
IsOk(self) -> bool returns true if the object has been initialized
IsOk(self) -> bool
[ "IsOk", "(", "self", ")", "-", ">", "bool" ]
def IsOk(*args, **kwargs): """ IsOk(self) -> bool returns true if the object has been initialized """ return _misc_.VideoMode_IsOk(*args, **kwargs)
[ "def", "IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "VideoMode_IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6050-L6056