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
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/mac_tool.py
python
MacTool._LoadPlistMaybeBinary
(self, plist_path)
Loads into a memory a plist possibly encoded in binary format. This is a wrapper around plistlib.readPlist that tries to convert the plist to the XML format if it can't be parsed (assuming that it is in the binary format). Args: plist_path: string, path to a plist file, in XML or binary format Returns: Content of the plist as a dictionary.
Loads into a memory a plist possibly encoded in binary format.
[ "Loads", "into", "a", "memory", "a", "plist", "possibly", "encoded", "in", "binary", "format", "." ]
def _LoadPlistMaybeBinary(self, plist_path): """Loads into a memory a plist possibly encoded in binary format. This is a wrapper around plistlib.readPlist that tries to convert the plist to the XML format if it can't be parsed (assuming that it is in the binary format). Args: plist_path: string, path to a plist file, in XML or binary format Returns: Content of the plist as a dictionary. """ try: # First, try to read the file using plistlib that only supports XML, # and if an exception is raised, convert a temporary copy to XML and # load that copy. return plistlib.readPlist(plist_path) except: pass with tempfile.NamedTemporaryFile() as temp: shutil.copy2(plist_path, temp.name) subprocess.check_call(['plutil', '-convert', 'xml1', temp.name]) return plistlib.readPlist(temp.name)
[ "def", "_LoadPlistMaybeBinary", "(", "self", ",", "plist_path", ")", ":", "try", ":", "# First, try to read the file using plistlib that only supports XML,", "# and if an exception is raised, convert a temporary copy to XML and", "# load that copy.", "return", "plistlib", ".", "readP...
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/mac_tool.py#L496-L519
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
native_client_sdk/src/tools/decode_dump.py
python
CoreDecoder.StackTrace
(self, info)
return trace
Convert a decoded core.json dump to a simple stack trace. Args: info: core.json info with decoded code addresses. Returns: A list of dicts with filename, lineno, function (deepest first).
Convert a decoded core.json dump to a simple stack trace.
[ "Convert", "a", "decoded", "core", ".", "json", "dump", "to", "a", "simple", "stack", "trace", "." ]
def StackTrace(self, info): """Convert a decoded core.json dump to a simple stack trace. Args: info: core.json info with decoded code addresses. Returns: A list of dicts with filename, lineno, function (deepest first). """ trace = [] for frame in info['frames']: for scope in frame['scopes']: trace.append(scope) return trace
[ "def", "StackTrace", "(", "self", ",", "info", ")", ":", "trace", "=", "[", "]", "for", "frame", "in", "info", "[", "'frames'", "]", ":", "for", "scope", "in", "frame", "[", "'scopes'", "]", ":", "trace", ".", "append", "(", "scope", ")", "return",...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/tools/decode_dump.py#L151-L163
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
tools/eval_recall.py
python
parse_args
()
return args
Parse input arguments
Parse input arguments
[ "Parse", "input", "arguments" ]
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('--imdb', dest='imdb_name', help='dataset to test', default='voc_2007_test', type=str) parser.add_argument('--method', dest='method', help='proposal method', default='selective_search', type=str) parser.add_argument('--rpn-file', dest='rpn_file', default=None, type=str) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Test a Fast R-CNN network'", ")", "parser", ".", "add_argument", "(", "'--imdb'", ",", "dest", "=", "'imdb_name'", ",", "help", "=", "'dataset to tes...
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/tools/eval_recall.py#L10-L29
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/cli/debugger_cli_common.py
python
RichTextLines.write_to_file
(self, file_path)
Write the object itself to file, in a plain format. The font_attr_segs and annotations are ignored. Args: file_path: (str) path of the file to write to.
Write the object itself to file, in a plain format.
[ "Write", "the", "object", "itself", "to", "file", "in", "a", "plain", "format", "." ]
def write_to_file(self, file_path): """Write the object itself to file, in a plain format. The font_attr_segs and annotations are ignored. Args: file_path: (str) path of the file to write to. """ with gfile.Open(file_path, "w") as f: for line in self._lines: f.write(line + "\n")
[ "def", "write_to_file", "(", "self", ",", "file_path", ")", ":", "with", "gfile", ".", "Open", "(", "file_path", ",", "\"w\"", ")", "as", "f", ":", "for", "line", "in", "self", ".", "_lines", ":", "f", ".", "write", "(", "line", "+", "\"\\n\"", ")"...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/debugger_cli_common.py#L344-L355
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/html5lib/treebuilders/base.py
python
TreeBuilder.insertElementTable
(self, token)
return element
Create an element and insert it into the tree
Create an element and insert it into the tree
[ "Create", "an", "element", "and", "insert", "it", "into", "the", "tree" ]
def insertElementTable(self, token): """Create an element and insert it into the tree""" element = self.createElement(token) if self.openElements[-1].name not in tableInsertModeElements: return self.insertElementNormal(token) else: # We should be in the InTable mode. This means we want to do # special magic element rearranging parent, insertBefore = self.getTableMisnestedNodePosition() if insertBefore is None: parent.appendChild(element) else: parent.insertBefore(element, insertBefore) self.openElements.append(element) return element
[ "def", "insertElementTable", "(", "self", ",", "token", ")", ":", "element", "=", "self", ".", "createElement", "(", "token", ")", "if", "self", ".", "openElements", "[", "-", "1", "]", ".", "name", "not", "in", "tableInsertModeElements", ":", "return", ...
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/html5lib/treebuilders/base.py#L333-L347
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/locale.py
python
Locale.get_closest
(cls, *locale_codes: str)
return cls.get(_default_locale)
Returns the closest match for the given locale code.
Returns the closest match for the given locale code.
[ "Returns", "the", "closest", "match", "for", "the", "given", "locale", "code", "." ]
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: continue elif len(parts) == 2: code = parts[0].lower() + "_" + parts[1].upper() if code in _supported_locales: return cls.get(code) if parts[0].lower() in _supported_locales: return cls.get(parts[0].lower()) return cls.get(_default_locale)
[ "def", "get_closest", "(", "cls", ",", "*", "locale_codes", ":", "str", ")", "->", "\"Locale\"", ":", "for", "code", "in", "locale_codes", ":", "if", "not", "code", ":", "continue", "code", "=", "code", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/locale.py#L234-L249
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
assembler/ext/src/python_libs/joblib3/memory.py
python
Memory.eval
(self, func, *args, **kwargs)
return self.cache(func)(*args, **kwargs)
Eval function func with arguments `*args` and `**kwargs`, in the context of the memory. This method works similarly to the builtin `apply`, except that the function is called only if the cache is not up to date.
Eval function func with arguments `*args` and `**kwargs`, in the context of the memory.
[ "Eval", "function", "func", "with", "arguments", "*", "args", "and", "**", "kwargs", "in", "the", "context", "of", "the", "memory", "." ]
def eval(self, func, *args, **kwargs): """ Eval function func with arguments `*args` and `**kwargs`, in the context of the memory. This method works similarly to the builtin `apply`, except that the function is called only if the cache is not up to date. """ if self.cachedir is None: return func(*args, **kwargs) return self.cache(func)(*args, **kwargs)
[ "def", "eval", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "cachedir", "is", "None", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "cache", "(...
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/assembler/ext/src/python_libs/joblib3/memory.py#L890-L901
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/core/naming.py
python
Namer.function_name
(self, original_fqn)
return new_name
Returns the name of a converted function.
Returns the name of a converted function.
[ "Returns", "the", "name", "of", "a", "converted", "function", "." ]
def function_name(self, original_fqn): """Returns the name of a converted function.""" canonical_name = self._as_symbol_name( original_fqn, style=_NamingStyle.SNAKE) new_name_root = 'tf__%s' % canonical_name new_name = new_name_root n = 0 while new_name in self.global_namespace: n += 1 new_name = '%s_%d' % (new_name_root, n) self.generated_names.add(new_name) return new_name
[ "def", "function_name", "(", "self", ",", "original_fqn", ")", ":", "canonical_name", "=", "self", ".", "_as_symbol_name", "(", "original_fqn", ",", "style", "=", "_NamingStyle", ".", "SNAKE", ")", "new_name_root", "=", "'tf__%s'", "%", "canonical_name", "new_na...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/core/naming.py#L90-L101
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
DQMServices/Components/python/HTTP.py
python
RequestManager.__init__
(self, num_connections = 10, ssl_opts = None, user_agent = None, request_headers = None, request_init = None, request_respond = None, request_error = None, handle_init = None)
Initialise the request manager. The arguments are: :arg num_connections: maximum number of simultaneous connections. :arg ssl_opts: optional SSLOptions (Monitoring.Core.X509) for SSL X509 parametre values, e.g. for X509 client authentication. :arg user_agent: sets user agent identification string if defined. :arg request_headers: if defined, specifies list of additional HTTP request headers to be added to each request. :arg request_init: optional callback to initialise requests; the default assumes each task is a URL to access and sets the `URL` property on the curl object to the task value. :arg request_respond: callback for handling responses; at the very minimum this should be defined as the default one does nothing. :arg request_error: callback for handling connection errors; the default one raises a RuntimeException. :arg handle_init: callback for customising connection handles at creation time; the callback will be invoked for each connection object as it's created and queued to the idle connection list.
Initialise the request manager. The arguments are:
[ "Initialise", "the", "request", "manager", ".", "The", "arguments", "are", ":" ]
def __init__(self, num_connections = 10, ssl_opts = None, user_agent = None, request_headers = None, request_init = None, request_respond = None, request_error = None, handle_init = None): """Initialise the request manager. The arguments are: :arg num_connections: maximum number of simultaneous connections. :arg ssl_opts: optional SSLOptions (Monitoring.Core.X509) for SSL X509 parametre values, e.g. for X509 client authentication. :arg user_agent: sets user agent identification string if defined. :arg request_headers: if defined, specifies list of additional HTTP request headers to be added to each request. :arg request_init: optional callback to initialise requests; the default assumes each task is a URL to access and sets the `URL` property on the curl object to the task value. :arg request_respond: callback for handling responses; at the very minimum this should be defined as the default one does nothing. :arg request_error: callback for handling connection errors; the default one raises a RuntimeException. :arg handle_init: callback for customising connection handles at creation time; the callback will be invoked for each connection object as it's created and queued to the idle connection list.""" self.request_respond = request_respond or self._request_respond self.request_error = request_error or self._request_error self.request_init = request_init or self._request_init self.cm = CurlMulti() self.handles = [Curl() for i in range(0, num_connections)] self.free = [c for c in self.handles] self.queue = [] for c in self.handles: c.buffer = None c.setopt(NOSIGNAL, 1) c.setopt(TIMEOUT, 300) c.setopt(CONNECTTIMEOUT, 30) c.setopt(FOLLOWLOCATION, 1) c.setopt(MAXREDIRS, 5) if user_agent: c.setopt(USERAGENT, user_agent) if ssl_opts: c.setopt(CAPATH, ssl_opts.ca_path) c.setopt(SSLCERT, ssl_opts.cert_file) c.setopt(SSLKEY, ssl_opts.key_file) if ssl_opts.key_pass: c.setopt(SSLKEYPASSWD, ssl_opts.key_pass) if request_headers: c.setopt(HTTPHEADER, request_headers) if handle_init: handle_init(c)
[ "def", "__init__", "(", "self", ",", "num_connections", "=", "10", ",", "ssl_opts", "=", "None", ",", "user_agent", "=", "None", ",", "request_headers", "=", "None", ",", "request_init", "=", "None", ",", "request_respond", "=", "None", ",", "request_error",...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQMServices/Components/python/HTTP.py#L24-L72
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Environment.py
python
OverrideEnvironment.get
(self, key, default=None)
Emulates the get() method of dictionaries.
Emulates the get() method of dictionaries.
[ "Emulates", "the", "get", "()", "method", "of", "dictionaries", "." ]
def get(self, key, default=None): """Emulates the get() method of dictionaries.""" try: return self.__dict__['overrides'][key] except KeyError: return self.__dict__['__subject'].get(key, default)
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", ".", "__dict__", "[", "'overrides'", "]", "[", "key", "]", "except", "KeyError", ":", "return", "self", ".", "__dict__", "[", "'__subject'", "...
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Environment.py#L2330-L2335
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TDbStr.GetSecHashCd
(self)
return _snap.TDbStr_GetSecHashCd(self)
GetSecHashCd(TDbStr self) -> int Parameters: self: TDbStr const *
GetSecHashCd(TDbStr self) -> int
[ "GetSecHashCd", "(", "TDbStr", "self", ")", "-", ">", "int" ]
def GetSecHashCd(self): """ GetSecHashCd(TDbStr self) -> int Parameters: self: TDbStr const * """ return _snap.TDbStr_GetSecHashCd(self)
[ "def", "GetSecHashCd", "(", "self", ")", ":", "return", "_snap", ".", "TDbStr_GetSecHashCd", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L11475-L11483
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/array_ops.py
python
_slice_helper
(tensor, slice_spec, var=None)
Overload for Tensor.__getitem__. This operation extracts the specified region from the tensor. The notation is similar to NumPy with the restriction that currently only support basic indexing. That means that using a non-scalar tensor as input is not currently allowed. Some useful examples: ```python # Strip leading and trailing 2 elements foo = tf.constant([1,2,3,4,5,6]) print(foo[2:-2].eval()) # => [3,4] # Skip every other row and reverse the order of the columns foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[::2,::-1].eval()) # => [[3,2,1], [9,8,7]] # Use scalar tensors as indices on both dimensions print(foo[tf.constant(0), tf.constant(2)].eval()) # => 3 # Insert another dimension foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[:, tf.newaxis, :].eval()) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]] print(foo[:, :, tf.newaxis].eval()) # => [[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]] # Ellipses (3 equivalent operations) foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[tf.newaxis, ...].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[tf.newaxis].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] # Masks foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[foo > 2].eval()) # => [3, 4, 5, 6, 7, 8, 9] ``` Notes: - `tf.newaxis` is `None` as in NumPy. - An implicit ellipsis is placed at the end of the `slice_spec` - NumPy advanced indexing is currently not supported. Purpose in the API: This method is exposed in TensorFlow's API so that library developers can register dispatching for `Tensor.__getitem__` to allow it to handle custom composite tensors & other custom objects. The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation. Args: tensor: An ops.Tensor object. slice_spec: The arguments to Tensor.__getitem__. var: In the case of variable slice assignment, the Variable object to slice (i.e. tensor is the read-only view of this variable). Returns: The appropriate slice of "tensor", based on "slice_spec". Raises: ValueError: If a slice range is negative size. TypeError: If the slice indices aren't int, slice, ellipsis, tf.newaxis or scalar int32/int64 tensors.
Overload for Tensor.__getitem__.
[ "Overload", "for", "Tensor", ".", "__getitem__", "." ]
def _slice_helper(tensor, slice_spec, var=None): """Overload for Tensor.__getitem__. This operation extracts the specified region from the tensor. The notation is similar to NumPy with the restriction that currently only support basic indexing. That means that using a non-scalar tensor as input is not currently allowed. Some useful examples: ```python # Strip leading and trailing 2 elements foo = tf.constant([1,2,3,4,5,6]) print(foo[2:-2].eval()) # => [3,4] # Skip every other row and reverse the order of the columns foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[::2,::-1].eval()) # => [[3,2,1], [9,8,7]] # Use scalar tensors as indices on both dimensions print(foo[tf.constant(0), tf.constant(2)].eval()) # => 3 # Insert another dimension foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[:, tf.newaxis, :].eval()) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]] print(foo[:, :, tf.newaxis].eval()) # => [[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]] # Ellipses (3 equivalent operations) foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[tf.newaxis, ...].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[tf.newaxis].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] # Masks foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[foo > 2].eval()) # => [3, 4, 5, 6, 7, 8, 9] ``` Notes: - `tf.newaxis` is `None` as in NumPy. - An implicit ellipsis is placed at the end of the `slice_spec` - NumPy advanced indexing is currently not supported. Purpose in the API: This method is exposed in TensorFlow's API so that library developers can register dispatching for `Tensor.__getitem__` to allow it to handle custom composite tensors & other custom objects. The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation. Args: tensor: An ops.Tensor object. slice_spec: The arguments to Tensor.__getitem__. var: In the case of variable slice assignment, the Variable object to slice (i.e. tensor is the read-only view of this variable). Returns: The appropriate slice of "tensor", based on "slice_spec". Raises: ValueError: If a slice range is negative size. TypeError: If the slice indices aren't int, slice, ellipsis, tf.newaxis or scalar int32/int64 tensors. """ tensor = ops.convert_to_tensor(tensor) # TODO(wangpeng): Consider supporting var if var is None and ops._numpy_style_slicing: # pylint: disable=protected-access return tensor._numpy_style_getitem(slice_spec) # pylint: disable=protected-access if isinstance(slice_spec, bool) or \ (isinstance(slice_spec, ops.Tensor) and slice_spec.dtype == dtypes.bool) or \ (isinstance(slice_spec, np.ndarray) and slice_spec.dtype == bool): return boolean_mask(tensor=tensor, mask=slice_spec) if not isinstance(slice_spec, (list, tuple)): slice_spec = [slice_spec] begin, end, strides = [], [], [] index = 0 new_axis_mask, shrink_axis_mask = 0, 0 begin_mask, end_mask = 0, 0 ellipsis_mask = 0 for s in slice_spec: if isinstance(s, _BaseSlice): # Finds the best dtype for begin, end, and strides. dtype = None for t in [s.start, s.stop, s.step]: if t is None or not isinstance(t, ops.Tensor): continue if t.dtype == dtypes.int64: dtype = dtypes.int64 elif t.dtype == dtypes.int32 and dtype != dtypes.int64: dtype = dtypes.int32 elif t.dtype == dtypes.int16 and dtype is None: dtype = dtypes.int16 if s.start is not None and not _is_undefined_dimension(s.start): _check_index(s.start) begin.append(s.start) else: if dtype is not None: begin.append(constant_op.constant(0, dtype=dtype)) else: begin.append(0) begin_mask |= (1 << index) if s.stop is not None and not _is_undefined_dimension(s.stop): _check_index(s.stop) end.append(s.stop) else: if dtype is not None: end.append(constant_op.constant(0, dtype=dtype)) else: end.append(0) end_mask |= (1 << index) if s.step is not None and not _is_undefined_dimension(s.step): _check_index(s.step) strides.append(s.step) else: if dtype is not None: strides.append(constant_op.constant(1, dtype=dtype)) else: strides.append(1) elif s is Ellipsis: begin.append(0) end.append(0) strides.append(1) ellipsis_mask |= (1 << index) elif s is newaxis: begin.append(0) end.append(0) strides.append(1) new_axis_mask |= (1 << index) else: _check_index(s) begin.append(s) end.append(s + 1) # TODO(mdan): Investigate why we can't set int32 here. if isinstance(s, ops.Tensor) and (s.dtype == dtypes.int16 or s.dtype == dtypes.int64): strides.append(constant_op.constant(1, dtype=s.dtype)) else: strides.append(1) shrink_axis_mask |= (1 << index) index += 1 # stack possibly involves no tensors, so we must use op_scope correct graph. with ops.name_scope( None, "strided_slice", [tensor] + begin + end + strides, skip_on_eager=False) as name: if begin: packed_begin, packed_end, packed_strides = (stack(begin), stack(end), stack(strides)) # TODO(mdan): Instead of implicitly casting, it's better to enforce the # same dtypes. if (packed_begin.dtype == dtypes.int64 or packed_end.dtype == dtypes.int64 or packed_strides.dtype == dtypes.int64): if packed_begin.dtype != dtypes.int64: packed_begin = gen_math_ops.cast(packed_begin, dtypes.int64) if packed_end.dtype != dtypes.int64: packed_end = gen_math_ops.cast(packed_end, dtypes.int64) if packed_strides.dtype != dtypes.int64: packed_strides = gen_math_ops.cast(packed_strides, dtypes.int64) elif (packed_begin.dtype == dtypes.int16 and packed_end.dtype == dtypes.int16 and packed_strides.dtype == dtypes.int16): if packed_begin.dtype != dtypes.int16: packed_begin = gen_math_ops.cast(packed_begin, dtypes.int16) if packed_end.dtype != dtypes.int16: packed_end = gen_math_ops.cast(packed_end, dtypes.int16) if packed_strides.dtype != dtypes.int16: packed_strides = gen_math_ops.cast(packed_strides, dtypes.int16) else: var_empty = constant([], dtype=dtypes.int32) packed_begin = packed_end = packed_strides = var_empty return strided_slice( tensor, packed_begin, packed_end, packed_strides, begin_mask=begin_mask, end_mask=end_mask, shrink_axis_mask=shrink_axis_mask, new_axis_mask=new_axis_mask, ellipsis_mask=ellipsis_mask, var=var, name=name)
[ "def", "_slice_helper", "(", "tensor", ",", "slice_spec", ",", "var", "=", "None", ")", ":", "tensor", "=", "ops", ".", "convert_to_tensor", "(", "tensor", ")", "# TODO(wangpeng): Consider supporting var", "if", "var", "is", "None", "and", "ops", ".", "_numpy_...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_ops.py#L916-L1108
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/utils/validation.py
python
_num_samples
(x)
Return number of samples in array-like x.
Return number of samples in array-like x.
[ "Return", "number", "of", "samples", "in", "array", "-", "like", "x", "." ]
def _num_samples(x): """Return number of samples in array-like x.""" message = 'Expected sequence or array-like, got %s' % type(x) if hasattr(x, 'fit') and callable(x.fit): # Don't get num_samples from an ensembles length! raise TypeError(message) if not hasattr(x, '__len__') and not hasattr(x, 'shape'): if hasattr(x, '__array__'): x = np.asarray(x) else: raise TypeError(message) if hasattr(x, 'shape') and x.shape is not None: if len(x.shape) == 0: raise TypeError("Singleton array %r cannot be considered" " a valid collection." % x) # Check that shape is returning an integer or default to len # Dask dataframes may not return numeric shape[0] value if isinstance(x.shape[0], numbers.Integral): return x.shape[0] try: return len(x) except TypeError: raise TypeError(message)
[ "def", "_num_samples", "(", "x", ")", ":", "message", "=", "'Expected sequence or array-like, got %s'", "%", "type", "(", "x", ")", "if", "hasattr", "(", "x", ",", "'fit'", ")", "and", "callable", "(", "x", ".", "fit", ")", ":", "# Don't get num_samples from...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/validation.py#L136-L161
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py
python
_NNTPBase.description
(self, group)
return self._getdescriptions(group, False)
Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.
Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string.
[ "Get", "a", "description", "for", "a", "single", "group", ".", "If", "more", "than", "one", "group", "matches", "(", "group", "is", "a", "pattern", ")", "return", "the", "first", ".", "If", "no", "group", "matches", "return", "an", "empty", "string", "...
def description(self, group): """Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.""" return self._getdescriptions(group, False)
[ "def", "description", "(", "self", ",", "group", ")", ":", "return", "self", ".", "_getdescriptions", "(", "group", ",", "False", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py#L634-L645
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_endpoints.py
python
Receiver.recv
(self, limit: int)
Receive message data for the current delivery on this receiver. .. note:: The link API can be used to stream large messages across the network, so just because there is no data to read does not imply the message is complete. To ensure the entirety of the message data has been read, either invoke :meth:`recv` until ``None`` is returned. :param limit: the max data size to receive of this message :return: The received message data, or ``None`` if the message has been completely received. :raise: * :class:`Timeout` if timed out * :class:`Interrupt` if interrupted * :class:`LinkException` for all other exceptions
Receive message data for the current delivery on this receiver.
[ "Receive", "message", "data", "for", "the", "current", "delivery", "on", "this", "receiver", "." ]
def recv(self, limit: int) -> Optional[bytes]: """ Receive message data for the current delivery on this receiver. .. note:: The link API can be used to stream large messages across the network, so just because there is no data to read does not imply the message is complete. To ensure the entirety of the message data has been read, either invoke :meth:`recv` until ``None`` is returned. :param limit: the max data size to receive of this message :return: The received message data, or ``None`` if the message has been completely received. :raise: * :class:`Timeout` if timed out * :class:`Interrupt` if interrupted * :class:`LinkException` for all other exceptions """ n, binary = pn_link_recv(self._impl, limit) if n == PN_EOS: return None else: self._check(n) return binary
[ "def", "recv", "(", "self", ",", "limit", ":", "int", ")", "->", "Optional", "[", "bytes", "]", ":", "n", ",", "binary", "=", "pn_link_recv", "(", "self", ".", "_impl", ",", "limit", ")", "if", "n", "==", "PN_EOS", ":", "return", "None", "else", ...
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_endpoints.py#L1230-L1252
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/protourlencode.py
python
URLEncodedRequestBuilder.add_parameter
(self, parameter, values)
return True
Add a single parameter. Adds a single parameter and its value to the request message. Args: parameter: Query string parameter to map to request. values: List of values to assign to request message. Returns: True if parameter was valid and added to the message, else False. Raises: DecodeError if the parameter refers to a valid field, and the values parameter does not have one and only one value. Non-valid query parameters may have multiple values and should not cause an error.
Add a single parameter.
[ "Add", "a", "single", "parameter", "." ]
def add_parameter(self, parameter, values): """Add a single parameter. Adds a single parameter and its value to the request message. Args: parameter: Query string parameter to map to request. values: List of values to assign to request message. Returns: True if parameter was valid and added to the message, else False. Raises: DecodeError if the parameter refers to a valid field, and the values parameter does not have one and only one value. Non-valid query parameters may have multiple values and should not cause an error. """ path = self.make_path(parameter) if not path: return False # Must check that all indexes of all items in the path are correct before # instantiating any of them. For example, consider: # # class Repeated(object): # ... # # class Inner(object): # # repeated = messages.MessageField(Repeated, 1, repeated=True) # # class Outer(object): # # inner = messages.MessageField(Inner, 1) # # instance = Outer() # builder = URLEncodedRequestBuilder(instance) # builder.add_parameter('inner.repeated') # # assert not hasattr(instance, 'inner') # # The check is done relative to the instance of Outer pass in to the # constructor of the builder. This instance is not referred to at all # because all names are assumed to be relative to it. # # The 'repeated' part of the path is not correct because it is missing an # index. Because it is missing an index, it should not create an instance # of Repeated. In this case add_parameter will return False and have no # side effects. # # A correct path that would cause a new Inner instance to be inserted at # instance.inner and a new Repeated instance to be appended to the # instance.inner.repeated list would be 'inner.repeated-0'. if not self.__check_indexes(path): return False # Ok to build objects. parent_path = path[:-1] parent = self.__get_or_create_path(parent_path) name, index = path[-1] field = parent.field_by_name(name) if len(values) != 1: raise messages.DecodeError( 'Found repeated values for field %s.' % field.name) value = values[0] if isinstance(field, messages.IntegerField): converted_value = int(value) elif isinstance(field, message_types.DateTimeField): try: converted_value = util.decode_datetime(value) except ValueError as e: raise messages.DecodeError(e) elif isinstance(field, messages.MessageField): # Just make sure it's instantiated. Assignment to field or # appending to list is done in __get_or_create_path. self.__get_or_create_path(path) return True elif isinstance(field, messages.StringField): converted_value = value.decode('utf-8') elif isinstance(field, messages.BooleanField): converted_value = value.lower() == 'true' and True or False else: try: converted_value = field.type(value) except TypeError: raise messages.DecodeError('Invalid enum value "%s"' % value) if field.repeated: value_list = getattr(parent, field.name, None) if value_list is None: setattr(parent, field.name, [converted_value]) else: if index == len(value_list): value_list.append(converted_value) else: # Index should never be above len(value_list) because it was # verified during the index check above. value_list[index] = converted_value else: setattr(parent, field.name, converted_value) return True
[ "def", "add_parameter", "(", "self", ",", "parameter", ",", "values", ")", ":", "path", "=", "self", ".", "make_path", "(", "parameter", ")", "if", "not", "path", ":", "return", "False", "# Must check that all indexes of all items in the path are correct before", "#...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/protourlencode.py#L355-L460
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/lidar.py
python
Lidar.__init__
(self, carla_actor, parent, communication, synchronous_mode)
Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param communication: communication-handle :type communication: carla_ros_bridge.communication
Constructor
[ "Constructor" ]
def __init__(self, carla_actor, parent, communication, synchronous_mode): """ Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param communication: communication-handle :type communication: carla_ros_bridge.communication """ super(Lidar, self).__init__(carla_actor=carla_actor, parent=parent, communication=communication, synchronous_mode=synchronous_mode, prefix='lidar/' + carla_actor.attributes.get('role_name'))
[ "def", "__init__", "(", "self", ",", "carla_actor", ",", "parent", ",", "communication", ",", "synchronous_mode", ")", ":", "super", "(", "Lidar", ",", "self", ")", ".", "__init__", "(", "carla_actor", "=", "carla_actor", ",", "parent", "=", "parent", ",",...
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/lidar.py#L29-L44
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/kfac/examples/mlp.py
python
fc_layer
(layer_id, inputs, output_size)
return preactivations, activations, tuple(layer.weights)
Builds a fully connected layer. Args: layer_id: int. Integer ID for this layer's variables. inputs: Tensor of shape [num_examples, input_size]. Each row corresponds to a single example. output_size: int. Number of output dimensions after fully connected layer. Returns: preactivations: Tensor of shape [num_examples, output_size]. Values of the layer immediately before the activation function. activations: Tensor of shape [num_examples, output_size]. Values of the layer immediately after the activation function. params: Tuple of (weights, bias), parameters for this layer.
Builds a fully connected layer.
[ "Builds", "a", "fully", "connected", "layer", "." ]
def fc_layer(layer_id, inputs, output_size): """Builds a fully connected layer. Args: layer_id: int. Integer ID for this layer's variables. inputs: Tensor of shape [num_examples, input_size]. Each row corresponds to a single example. output_size: int. Number of output dimensions after fully connected layer. Returns: preactivations: Tensor of shape [num_examples, output_size]. Values of the layer immediately before the activation function. activations: Tensor of shape [num_examples, output_size]. Values of the layer immediately after the activation function. params: Tuple of (weights, bias), parameters for this layer. """ # TODO(b/67004004): Delete this function and rely on tf.layers exclusively. layer = tf.layers.Dense( output_size, kernel_initializer=tf.random_normal_initializer(), name="fc_%d" % layer_id) preactivations = layer(inputs) activations = tf.nn.tanh(preactivations) # layer.weights is a list. This converts it a (hashable) tuple. return preactivations, activations, tuple(layer.weights)
[ "def", "fc_layer", "(", "layer_id", ",", "inputs", ",", "output_size", ")", ":", "# TODO(b/67004004): Delete this function and rely on tf.layers exclusively.", "layer", "=", "tf", ".", "layers", ".", "Dense", "(", "output_size", ",", "kernel_initializer", "=", "tf", "...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/kfac/examples/mlp.py#L38-L63
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/find-array-given-subset-sums.py
python
Solution3.recoverArray
(self, n, sums)
return result
:type n: int :type sums: List[int] :rtype: List[int]
:type n: int :type sums: List[int] :rtype: List[int]
[ ":", "type", "n", ":", "int", ":", "type", "sums", ":", "List", "[", "int", "]", ":", "rtype", ":", "List", "[", "int", "]" ]
def recoverArray(self, n, sums): """ :type n: int :type sums: List[int] :rtype: List[int] """ dp = {k: v for k, v in collections.Counter(sums).iteritems()} total = reduce(operator.ior, dp.itervalues(), 0) basis = total&-total # find rightmost bit 1 if basis > 1: for k in dp.iterkeys(): dp[k] //= basis sorted_sums = sorted(dp.iterkeys()) # Time: O(2^n * log(2^n)) = O(n * 2^n) shift = 0 result = [0]*(basis.bit_length()-1) for _ in xrange(n-len(result)): # log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n) new_dp = {} new_sorted_sums = [] new_shift = sorted_sums[0]-sorted_sums[1] assert(new_shift < 0) for x in sorted_sums: if not dp[x]: continue dp[x-new_shift] -= dp[x] new_dp[x-new_shift] = dp[x] new_sorted_sums.append(x-new_shift) dp = new_dp sorted_sums = new_sorted_sums if shift in dp: # contain 0, choose this side result.append(new_shift) else: # contain no 0, choose another side and shift 0 offset result.append(-new_shift) shift -= new_shift return result
[ "def", "recoverArray", "(", "self", ",", "n", ",", "sums", ")", ":", "dp", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "collections", ".", "Counter", "(", "sums", ")", ".", "iteritems", "(", ")", "}", "total", "=", "reduce", "(", "oper...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-array-given-subset-sums.py#L104-L137
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/stats.py
python
kruskal
(*args, **kwargs)
return KruskalResult(h, distributions.chi2.sf(h, df))
Compute the Kruskal-Wallis H-test for independent samples The Kruskal-Wallis H-test tests the null hypothesis that the population median of all of the groups are equal. It is a non-parametric version of ANOVA. The test works on 2 or more independent samples, which may have different sizes. Note that rejecting the null hypothesis does not indicate which of the groups differs. Post-hoc comparisons between groups are required to determine which groups are different. Parameters ---------- sample1, sample2, ... : array_like Two or more arrays with the sample measurements can be given as arguments. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Returns ------- statistic : float The Kruskal-Wallis H statistic, corrected for ties pvalue : float The p-value for the test using the assumption that H has a chi square distribution See Also -------- f_oneway : 1-way ANOVA mannwhitneyu : Mann-Whitney rank test on two samples. friedmanchisquare : Friedman test for repeated measurements Notes ----- Due to the assumption that H has a chi square distribution, the number of samples in each group must not be too small. A typical rule is that each sample must have at least 5 measurements. References ---------- .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in One-Criterion Variance Analysis", Journal of the American Statistical Association, Vol. 47, Issue 260, pp. 583-621, 1952. .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance Examples -------- >>> from scipy import stats >>> x = [1, 3, 5, 7, 9] >>> y = [2, 4, 6, 8, 10] >>> stats.kruskal(x, y) KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895) >>> x = [1, 1, 1] >>> y = [2, 2, 2] >>> z = [2, 2] >>> stats.kruskal(x, y, z) KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
Compute the Kruskal-Wallis H-test for independent samples
[ "Compute", "the", "Kruskal", "-", "Wallis", "H", "-", "test", "for", "independent", "samples" ]
def kruskal(*args, **kwargs): """ Compute the Kruskal-Wallis H-test for independent samples The Kruskal-Wallis H-test tests the null hypothesis that the population median of all of the groups are equal. It is a non-parametric version of ANOVA. The test works on 2 or more independent samples, which may have different sizes. Note that rejecting the null hypothesis does not indicate which of the groups differs. Post-hoc comparisons between groups are required to determine which groups are different. Parameters ---------- sample1, sample2, ... : array_like Two or more arrays with the sample measurements can be given as arguments. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Returns ------- statistic : float The Kruskal-Wallis H statistic, corrected for ties pvalue : float The p-value for the test using the assumption that H has a chi square distribution See Also -------- f_oneway : 1-way ANOVA mannwhitneyu : Mann-Whitney rank test on two samples. friedmanchisquare : Friedman test for repeated measurements Notes ----- Due to the assumption that H has a chi square distribution, the number of samples in each group must not be too small. A typical rule is that each sample must have at least 5 measurements. References ---------- .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in One-Criterion Variance Analysis", Journal of the American Statistical Association, Vol. 47, Issue 260, pp. 583-621, 1952. .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance Examples -------- >>> from scipy import stats >>> x = [1, 3, 5, 7, 9] >>> y = [2, 4, 6, 8, 10] >>> stats.kruskal(x, y) KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895) >>> x = [1, 1, 1] >>> y = [2, 2, 2] >>> z = [2, 2] >>> stats.kruskal(x, y, z) KruskalResult(statistic=7.0, pvalue=0.0301973834223185) """ args = list(map(np.asarray, args)) num_groups = len(args) if num_groups < 2: raise ValueError("Need at least two groups in stats.kruskal()") for arg in args: if arg.size == 0: return KruskalResult(np.nan, np.nan) n = np.asarray(list(map(len, args))) if 'nan_policy' in kwargs.keys(): if kwargs['nan_policy'] not in ('propagate', 'raise', 'omit'): raise ValueError("nan_policy must be 'propagate', " "'raise' or'omit'") else: nan_policy = kwargs['nan_policy'] else: nan_policy = 'propagate' contains_nan = False for arg in args: cn = _contains_nan(arg, nan_policy) if cn[0]: contains_nan = True break if contains_nan and nan_policy == 'omit': for a in args: a = ma.masked_invalid(a) return mstats_basic.kruskal(*args) if contains_nan and nan_policy == 'propagate': return KruskalResult(np.nan, np.nan) alldata = np.concatenate(args) ranked = rankdata(alldata) ties = tiecorrect(ranked) if ties == 0: raise ValueError('All numbers are identical in kruskal') # Compute sum^2/n for each group and sum j = np.insert(np.cumsum(n), 0, 0) ssbn = 0 for i in range(num_groups): ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i] totaln = np.sum(n) h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1) df = num_groups - 1 h /= ties return KruskalResult(h, distributions.chi2.sf(h, df))
[ "def", "kruskal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "map", "(", "np", ".", "asarray", ",", "args", ")", ")", "num_groups", "=", "len", "(", "args", ")", "if", "num_groups", "<", "2", ":", "raise", "V...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/stats.py#L5107-L5221
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/python_gflags/gflags.py
python
DEFINE_boolean
(name, default, help, flag_values=FLAGS, **args)
Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line.
Registers a boolean flag.
[ "Registers", "a", "boolean", "flag", "." ]
def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): """Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. """ DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values)
[ "def", "DEFINE_boolean", "(", "name", ",", "default", ",", "help", ",", "flag_values", "=", "FLAGS", ",", "*", "*", "args", ")", ":", "DEFINE_flag", "(", "BooleanFlag", "(", "name", ",", "default", ",", "help", ",", "*", "*", "args", ")", ",", "flag_...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/python_gflags/gflags.py#L2367-L2378
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
DC.GetSizeMMTuple
(*args, **kwargs)
return _gdi_.DC_GetSizeMMTuple(*args, **kwargs)
GetSizeMMTuple() -> (width, height) Get the DC size in milimeters.
GetSizeMMTuple() -> (width, height)
[ "GetSizeMMTuple", "()", "-", ">", "(", "width", "height", ")" ]
def GetSizeMMTuple(*args, **kwargs): """ GetSizeMMTuple() -> (width, height) Get the DC size in milimeters. """ return _gdi_.DC_GetSizeMMTuple(*args, **kwargs)
[ "def", "GetSizeMMTuple", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_GetSizeMMTuple", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L4207-L4213
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/filters.py
python
do_forceescape
(value: "t.Union[str, HasHTML]")
return escape(str(value))
Enforce HTML escaping. This will probably double escape variables.
Enforce HTML escaping. This will probably double escape variables.
[ "Enforce", "HTML", "escaping", ".", "This", "will", "probably", "double", "escape", "variables", "." ]
def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup: """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, "__html__"): value = t.cast("HasHTML", value).__html__() return escape(str(value))
[ "def", "do_forceescape", "(", "value", ":", "\"t.Union[str, HasHTML]\"", ")", "->", "Markup", ":", "if", "hasattr", "(", "value", ",", "\"__html__\"", ")", ":", "value", "=", "t", ".", "cast", "(", "\"HasHTML\"", ",", "value", ")", ".", "__html__", "(", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L189-L194
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/check-completeness-of-a-binary-tree.py
python
Solution.isCompleteTree
(self, root)
return True
:type root: TreeNode :rtype: bool
:type root: TreeNode :rtype: bool
[ ":", "type", "root", ":", "TreeNode", ":", "rtype", ":", "bool" ]
def isCompleteTree(self, root): """ :type root: TreeNode :rtype: bool """ end = False current = [root] while current: next_level = [] for node in current: if not node: end = True continue if end: return False next_level.append(node.left) next_level.append(node.right) current = next_level return True
[ "def", "isCompleteTree", "(", "self", ",", "root", ")", ":", "end", "=", "False", "current", "=", "[", "root", "]", "while", "current", ":", "next_level", "=", "[", "]", "for", "node", "in", "current", ":", "if", "not", "node", ":", "end", "=", "Tr...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/check-completeness-of-a-binary-tree.py#L13-L31
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__init__
(self, message_listener, type_checker)
Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified. type_checker: A type_checkers.ValueChecker instance to run on elements inserted into this container.
Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified. type_checker: A type_checkers.ValueChecker instance to run on elements inserted into this container.
[ "Args", ":", "message_listener", ":", "A", "MessageListener", "implementation", ".", "The", "RepeatedScalarFieldContainer", "will", "call", "this", "object", "s", "Modified", "()", "method", "when", "it", "is", "modified", ".", "type_checker", ":", "A", "type_chec...
def __init__(self, message_listener, type_checker): """ Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified. type_checker: A type_checkers.ValueChecker instance to run on elements inserted into this container. """ super(RepeatedScalarFieldContainer, self).__init__(message_listener) self._type_checker = type_checker
[ "def", "__init__", "(", "self", ",", "message_listener", ",", "type_checker", ")", ":", "super", "(", "RepeatedScalarFieldContainer", ",", "self", ")", ".", "__init__", "(", "message_listener", ")", "self", ".", "_type_checker", "=", "type_checker" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/containers.py#L97-L107
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py
python
File.get_max_drift_csig
(self)
return None
Returns the content signature currently stored for this node if it's been unmodified longer than the max_drift value, or the max_drift value is 0. Returns None otherwise.
Returns the content signature currently stored for this node if it's been unmodified longer than the max_drift value, or the max_drift value is 0. Returns None otherwise.
[ "Returns", "the", "content", "signature", "currently", "stored", "for", "this", "node", "if", "it", "s", "been", "unmodified", "longer", "than", "the", "max_drift", "value", "or", "the", "max_drift", "value", "is", "0", ".", "Returns", "None", "otherwise", "...
def get_max_drift_csig(self): """ Returns the content signature currently stored for this node if it's been unmodified longer than the max_drift value, or the max_drift value is 0. Returns None otherwise. """ old = self.get_stored_info() mtime = self.get_timestamp() max_drift = self.fs.max_drift if max_drift > 0: if (time.time() - mtime) > max_drift: try: n = old.ninfo if n.timestamp and n.csig and n.timestamp == mtime: return n.csig except AttributeError: pass elif max_drift == 0: try: return old.ninfo.csig except AttributeError: pass return None
[ "def", "get_max_drift_csig", "(", "self", ")", ":", "old", "=", "self", ".", "get_stored_info", "(", ")", "mtime", "=", "self", ".", "get_timestamp", "(", ")", "max_drift", "=", "self", ".", "fs", ".", "max_drift", "if", "max_drift", ">", "0", ":", "if...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py#L3168-L3192
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/Instruments.py
python
FermiChopper.getTransmission
(self, Ei, freq)
return Chop.achop(Ei, freq, dslat, self.pslit / 1000., self.radius / 1000., self.rho / 1000.) / dslat
Calculates the chopper transmission
Calculates the chopper transmission
[ "Calculates", "the", "chopper", "transmission" ]
def getTransmission(self, Ei, freq): """ Calculates the chopper transmission """ dslat = (self.pslit + self.pslat) / 1000 return Chop.achop(Ei, freq, dslat, self.pslit / 1000., self.radius / 1000., self.rho / 1000.) / dslat
[ "def", "getTransmission", "(", "self", ",", "Ei", ",", "freq", ")", ":", "dslat", "=", "(", "self", ".", "pslit", "+", "self", ".", "pslat", ")", "/", "1000", "return", "Chop", ".", "achop", "(", "Ei", ",", "freq", ",", "dslat", ",", "self", ".",...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/Instruments.py#L98-L101
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/input.py
python
_select_which_to_enqueue
(tensor_list, keep_input)
return tensor_list
Select which examples to enqueue based on vector `keep_input`.
Select which examples to enqueue based on vector `keep_input`.
[ "Select", "which", "examples", "to", "enqueue", "based", "on", "vector", "keep_input", "." ]
def _select_which_to_enqueue(tensor_list, keep_input): """Select which examples to enqueue based on vector `keep_input`.""" select_i = math_ops.cast(keep_input, dtypes.int32) tensor_list = [ data_flow_ops.dynamic_partition(x, select_i, num_partitions=2)[1] for x in tensor_list] return tensor_list
[ "def", "_select_which_to_enqueue", "(", "tensor_list", ",", "keep_input", ")", ":", "select_i", "=", "math_ops", ".", "cast", "(", "keep_input", ",", "dtypes", ".", "int32", ")", "tensor_list", "=", "[", "data_flow_ops", ".", "dynamic_partition", "(", "x", ","...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/input.py#L709-L715
xenia-project/xenia
9b1fdac98665ac091b9660a5d0fbb259ed79e578
third_party/google-styleguide/cpplint/cpplint.py
python
CheckVlogArguments
(filename, clean_lines, linenum, error)
Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. 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.
Checks that VLOG() is only used for defining a logging level.
[ "Checks", "that", "VLOG", "()", "is", "only", "used", "for", "defining", "a", "logging", "level", "." ]
def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. 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] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.')
[ "def", "CheckVlogArguments", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)'", ",", "line", ")", ...
https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L1772-L1788
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/__init__.py
python
BaseNode.dot
(self, marks)
return True
Print a dot representation of this node build graph.
Print a dot representation of this node build graph.
[ "Print", "a", "dot", "representation", "of", "this", "node", "build", "graph", "." ]
def dot(self, marks): """Print a dot representation of this node build graph.""" if self in marks: return True marks[self] = None print(' node_%s [label="%s"]' % (self.uid, self.__name)) if self.builder is not None: if self.builder.dot(marks): print(' builder_%s -> node_%s' % (self.builder.uid, self.uid)) return True
[ "def", "dot", "(", "self", ",", "marks", ")", ":", "if", "self", "in", "marks", ":", "return", "True", "marks", "[", "self", "]", "=", "None", "print", "(", "' node_%s [label=\"%s\"]'", "%", "(", "self", ".", "uid", ",", "self", ".", "__name", ")", ...
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L1410-L1420
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibook.py
python
TabFrame.DoSetSize
(self, x, y, width, height, flags=wx.SIZE_AUTO)
Sets the position and size of the window in pixels. The `flags` parameter indicates the interpretation of the other params if they are equal to -1. :param integer `x`: the window `x` position; :param integer `y`: the window `y` position; :param integer `width`: the window width; :param integer `height`: the window height; :param integer `flags`: may have one of this bit set: =================================== ====================================== Size Flags Description =================================== ====================================== ``wx.SIZE_AUTO`` A -1 indicates that a class-specific default should be used. ``wx.SIZE_AUTO_WIDTH`` A -1 indicates that a class-specific default should be used for the width. ``wx.SIZE_AUTO_HEIGHT`` A -1 indicates that a class-specific default should be used for the height. ``wx.SIZE_USE_EXISTING`` Existing dimensions should be used if -1 values are supplied. ``wx.SIZE_ALLOW_MINUS_ONE`` Allow dimensions of -1 and less to be interpreted as real dimensions, not default values. ``wx.SIZE_FORCE`` Normally, if the position and the size of the window are already the same as the parameters of this function, nothing is done. but with this flag a window resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented for MSW and ignored elsewhere currently) =================================== ====================================== :note: Overridden from :class:`PyControl`.
Sets the position and size of the window in pixels. The `flags` parameter indicates the interpretation of the other params if they are equal to -1.
[ "Sets", "the", "position", "and", "size", "of", "the", "window", "in", "pixels", ".", "The", "flags", "parameter", "indicates", "the", "interpretation", "of", "the", "other", "params", "if", "they", "are", "equal", "to", "-", "1", "." ]
def DoSetSize(self, x, y, width, height, flags=wx.SIZE_AUTO): """ Sets the position and size of the window in pixels. The `flags` parameter indicates the interpretation of the other params if they are equal to -1. :param integer `x`: the window `x` position; :param integer `y`: the window `y` position; :param integer `width`: the window width; :param integer `height`: the window height; :param integer `flags`: may have one of this bit set: =================================== ====================================== Size Flags Description =================================== ====================================== ``wx.SIZE_AUTO`` A -1 indicates that a class-specific default should be used. ``wx.SIZE_AUTO_WIDTH`` A -1 indicates that a class-specific default should be used for the width. ``wx.SIZE_AUTO_HEIGHT`` A -1 indicates that a class-specific default should be used for the height. ``wx.SIZE_USE_EXISTING`` Existing dimensions should be used if -1 values are supplied. ``wx.SIZE_ALLOW_MINUS_ONE`` Allow dimensions of -1 and less to be interpreted as real dimensions, not default values. ``wx.SIZE_FORCE`` Normally, if the position and the size of the window are already the same as the parameters of this function, nothing is done. but with this flag a window resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented for MSW and ignored elsewhere currently) =================================== ====================================== :note: Overridden from :class:`PyControl`. """ self._rect = wx.Rect(x, y, max(1, width), max(1, height)) self.DoSizing()
[ "def", "DoSetSize", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "flags", "=", "wx", ".", "SIZE_AUTO", ")", ":", "self", ".", "_rect", "=", "wx", ".", "Rect", "(", "x", ",", "y", ",", "max", "(", "1", ",", "width", ")", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibook.py#L2663-L2693
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/CEF3/cef_source/tools/automate/automate-git.py
python
copy_directory
(source, target, allow_overwrite=False)
Copies a directory from source to target.
Copies a directory from source to target.
[ "Copies", "a", "directory", "from", "source", "to", "target", "." ]
def copy_directory(source, target, allow_overwrite=False): """ Copies a directory from source to target. """ if not options.dryrun and os.path.exists(target): if not allow_overwrite: raise Exception("Directory %s already exists" % (target)) remove_directory(target) if os.path.exists(source): msg("Copying directory %s to %s" % (source, target)); if not options.dryrun: shutil.copytree(source, target)
[ "def", "copy_directory", "(", "source", ",", "target", ",", "allow_overwrite", "=", "False", ")", ":", "if", "not", "options", ".", "dryrun", "and", "os", ".", "path", ".", "exists", "(", "target", ")", ":", "if", "not", "allow_overwrite", ":", "raise", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/automate/automate-git.py#L75-L84
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/pipeline.py
python
Pipeline.score
(self, X, y=None)
return self.steps[-1][-1].score(Xt, y)
Apply transforms, and score with the final estimator Parameters ---------- X : iterable Data to predict on. Must fulfill input requirements of first step of the pipeline. y : iterable, default=None Targets used for scoring. Must fulfill label requirements for all steps of the pipeline. Returns ------- score : float
Apply transforms, and score with the final estimator
[ "Apply", "transforms", "and", "score", "with", "the", "final", "estimator" ]
def score(self, X, y=None): """Apply transforms, and score with the final estimator Parameters ---------- X : iterable Data to predict on. Must fulfill input requirements of first step of the pipeline. y : iterable, default=None Targets used for scoring. Must fulfill label requirements for all steps of the pipeline. Returns ------- score : float """ Xt = X for name, transform in self.steps[:-1]: if transform is not None: Xt = transform.transform(Xt) return self.steps[-1][-1].score(Xt, y)
[ "def", "score", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "Xt", "=", "X", "for", "name", ",", "transform", "in", "self", ".", "steps", "[", ":", "-", "1", "]", ":", "if", "transform", "is", "not", "None", ":", "Xt", "=", "transf...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/pipeline.py#L484-L505
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
_random_exp_initializer
(minval, maxval, seed=None, dtype=dtypes.float32)
return _initializer
Returns an exponential distribution initializer. Args: minval: float or a scalar float Tensor. With value > 0. Lower bound of the range of random values to generate. maxval: float or a scalar float Tensor. With value > minval. Upper bound of the range of random values to generate. seed: An integer. Used to create random seeds. dtype: The data type. Returns: An initializer that generates tensors with an exponential distribution.
Returns an exponential distribution initializer.
[ "Returns", "an", "exponential", "distribution", "initializer", "." ]
def _random_exp_initializer(minval, maxval, seed=None, dtype=dtypes.float32): """Returns an exponential distribution initializer. Args: minval: float or a scalar float Tensor. With value > 0. Lower bound of the range of random values to generate. maxval: float or a scalar float Tensor. With value > minval. Upper bound of the range of random values to generate. seed: An integer. Used to create random seeds. dtype: The data type. Returns: An initializer that generates tensors with an exponential distribution. """ def _initializer(shape, dtype=dtype, partition_info=None): del partition_info # Unused. return math_ops.exp( random_ops.random_uniform( shape, math_ops.log(minval), math_ops.log(maxval), dtype, seed=seed)) return _initializer
[ "def", "_random_exp_initializer", "(", "minval", ",", "maxval", ",", "seed", "=", "None", ",", "dtype", "=", "dtypes", ".", "float32", ")", ":", "def", "_initializer", "(", "shape", ",", "dtype", "=", "dtype", ",", "partition_info", "=", "None", ")", ":"...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1751-L1779
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/collide.py
python
bb_intersect
(a,b)
return not any(q < u or v < p for (p,q,u,v) in zip(amin,amax,bmin,bmax))
Returns true if the bounding boxes (a[0]->a[1]) and (b[0]->b[1]) intersect
Returns true if the bounding boxes (a[0]->a[1]) and (b[0]->b[1]) intersect
[ "Returns", "true", "if", "the", "bounding", "boxes", "(", "a", "[", "0", "]", "-", ">", "a", "[", "1", "]", ")", "and", "(", "b", "[", "0", "]", "-", ">", "b", "[", "1", "]", ")", "intersect" ]
def bb_intersect(a,b): """Returns true if the bounding boxes (a[0]->a[1]) and (b[0]->b[1]) intersect""" amin,amax=a bmin,bmax=b return not any(q < u or v < p for (p,q,u,v) in zip(amin,amax,bmin,bmax))
[ "def", "bb_intersect", "(", "a", ",", "b", ")", ":", "amin", ",", "amax", "=", "a", "bmin", ",", "bmax", "=", "b", "return", "not", "any", "(", "q", "<", "u", "or", "v", "<", "p", "for", "(", "p", ",", "q", ",", "u", ",", "v", ")", "in", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/collide.py#L19-L23
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/__init__.py
python
ServicerContext.code
(self)
Accesses the value to be used as status code upon RPC completion. This is an EXPERIMENTAL API. Returns: The StatusCode value for the RPC.
Accesses the value to be used as status code upon RPC completion.
[ "Accesses", "the", "value", "to", "be", "used", "as", "status", "code", "upon", "RPC", "completion", "." ]
def code(self): """Accesses the value to be used as status code upon RPC completion. This is an EXPERIMENTAL API. Returns: The StatusCode value for the RPC. """ raise NotImplementedError()
[ "def", "code", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/__init__.py#L1254-L1262
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py
python
EquivSet.insert_equiv
(self, *objs)
return self._insert(objs)
Insert a set of equivalent objects by modifying self. This method can be overloaded to transform object type before insertion.
Insert a set of equivalent objects by modifying self. This method can be overloaded to transform object type before insertion.
[ "Insert", "a", "set", "of", "equivalent", "objects", "by", "modifying", "self", ".", "This", "method", "can", "be", "overloaded", "to", "transform", "object", "type", "before", "insertion", "." ]
def insert_equiv(self, *objs): """Insert a set of equivalent objects by modifying self. This method can be overloaded to transform object type before insertion. """ return self._insert(objs)
[ "def", "insert_equiv", "(", "self", ",", "*", "objs", ")", ":", "return", "self", ".", "_insert", "(", "objs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py#L279-L283
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/range.py
python
RangeIndex._start
(self)
return self.start
The value of the `start` parameter (``0`` if this was not supplied). .. deprecated:: 0.25.0 Use ``start`` instead.
The value of the `start` parameter (``0`` if this was not supplied).
[ "The", "value", "of", "the", "start", "parameter", "(", "0", "if", "this", "was", "not", "supplied", ")", "." ]
def _start(self): """ The value of the `start` parameter (``0`` if this was not supplied). .. deprecated:: 0.25.0 Use ``start`` instead. """ warnings.warn( self._deprecation_message.format("_start", "start"), FutureWarning, stacklevel=2, ) return self.start
[ "def", "_start", "(", "self", ")", ":", "warnings", ".", "warn", "(", "self", ".", "_deprecation_message", ".", "format", "(", "\"_start\"", ",", "\"start\"", ")", ",", "FutureWarning", ",", "stacklevel", "=", "2", ",", ")", "return", "self", ".", "start...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/range.py#L219-L231
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/polynomial.py
python
poly1d.deriv
(self, m=1)
return poly1d(polyder(self.coeffs, m=m))
Return a derivative of this polynomial. Refer to `polyder` for full documentation. See Also -------- polyder : equivalent function
Return a derivative of this polynomial.
[ "Return", "a", "derivative", "of", "this", "polynomial", "." ]
def deriv(self, m=1): """ Return a derivative of this polynomial. Refer to `polyder` for full documentation. See Also -------- polyder : equivalent function """ return poly1d(polyder(self.coeffs, m=m))
[ "def", "deriv", "(", "self", ",", "m", "=", "1", ")", ":", "return", "poly1d", "(", "polyder", "(", "self", ".", "coeffs", ",", "m", "=", "m", ")", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/polynomial.py#L1218-L1229
cocos-creator/engine-native
984c4c9f5838253313b44ccd429bd8fac4ec8a6a
tools/bindings-generator/clang/cindex.py
python
Cursor.is_scoped_enum
(self)
return conf.lib.clang_EnumDecl_isScoped(self)
Returns True if the cursor refers to a scoped enum declaration.
Returns True if the cursor refers to a scoped enum declaration.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "scoped", "enum", "declaration", "." ]
def is_scoped_enum(self): """Returns True if the cursor refers to a scoped enum declaration. """ return conf.lib.clang_EnumDecl_isScoped(self)
[ "def", "is_scoped_enum", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_EnumDecl_isScoped", "(", "self", ")" ]
https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L1506-L1509
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/supervised_session.py
python
Scaffold.finalize
(self)
Creates operations if needed and finalizes the graph.
Creates operations if needed and finalizes the graph.
[ "Creates", "operations", "if", "needed", "and", "finalizes", "the", "graph", "." ]
def finalize(self): """Creates operations if needed and finalizes the graph.""" if self._global_step_tensor is None: self._global_step_tensor = contrib_variables.get_or_create_global_step() if self._init_op is None: self._init_op = Scaffold._get_or_default( 'init_op', ops.GraphKeys.INIT_OP, variables.initialize_all_variables) if self._ready_op is None: self._ready_op = Scaffold._get_or_default( 'ready_op', ops.GraphKeys.READY_OP, variables.report_uninitialized_variables) if self._local_init_op is None: self._local_init_op = Scaffold._get_or_default( 'local_init_op', ops.GraphKeys.LOCAL_INIT_OP, Scaffold._default_local_init_op) if self._summary_op is None: self._summary_op = Scaffold._get_or_default( 'summary_op', ops.GraphKeys.SUMMARY_OP, logging_ops.merge_all_summaries) # pylint: disable=g-long-lambda if self._saver is None: self._saver = Scaffold._get_or_default( 'saver', ops.GraphKeys.SAVERS, lambda: training_saver.Saver(sharded=True, max_to_keep=self._keep_checkpoint_max)) # pylint: enable=g-long-lambda ops.get_default_graph().finalize()
[ "def", "finalize", "(", "self", ")", ":", "if", "self", ".", "_global_step_tensor", "is", "None", ":", "self", ".", "_global_step_tensor", "=", "contrib_variables", ".", "get_or_create_global_step", "(", ")", "if", "self", ".", "_init_op", "is", "None", ":", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/supervised_session.py#L139-L167
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Point2D.Set
(*args, **kwargs)
return _core_.Point2D_Set(*args, **kwargs)
Set(self, double x=0, double y=0)
Set(self, double x=0, double y=0)
[ "Set", "(", "self", "double", "x", "=", "0", "double", "y", "=", "0", ")" ]
def Set(*args, **kwargs): """Set(self, double x=0, double y=0)""" return _core_.Point2D_Set(*args, **kwargs)
[ "def", "Set", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Point2D_Set", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1774-L1776
douban/paracel
d1548dd94cff9123653689e385253bb34c3260c2
prun.py
python
init_starter
(method, mem_limit, ppn, hostfile, group)
return starter
Assemble commands for running paracel programs
Assemble commands for running paracel programs
[ "Assemble", "commands", "for", "running", "paracel", "programs" ]
def init_starter(method, mem_limit, ppn, hostfile, group): '''Assemble commands for running paracel programs''' starter = '' if not hostfile: hostfile = '~/.mpi/large.18' if method == 'mesos': if group: starter = '%s/mrun -m %s -p %s -g %s -n ' % (PARACEL_INSTALL_PREFIX, mem_limit, ppn, group) else: starter = '%s/mrun -m %s -p %s -n ' % (PARACEL_INSTALL_PREFIX, mem_limit, ppn) elif method == 'mpi': starter = 'mpirun --hostfile %s -n ' % hostfile elif method == 'local': starter = 'mpirun -n ' else: print 'method %s not supported.' % method sys.exit(1) return starter
[ "def", "init_starter", "(", "method", ",", "mem_limit", ",", "ppn", ",", "hostfile", ",", "group", ")", ":", "starter", "=", "''", "if", "not", "hostfile", ":", "hostfile", "=", "'~/.mpi/large.18'", "if", "method", "==", "'mesos'", ":", "if", "group", ":...
https://github.com/douban/paracel/blob/d1548dd94cff9123653689e385253bb34c3260c2/prun.py#L66-L83
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/mailbox.py
python
MH.__len__
(self)
return len(list(self.iterkeys()))
Return a count of messages in the mailbox.
Return a count of messages in the mailbox.
[ "Return", "a", "count", "of", "messages", "in", "the", "mailbox", "." ]
def __len__(self): """Return a count of messages in the mailbox.""" return len(list(self.iterkeys()))
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "list", "(", "self", ".", "iterkeys", "(", ")", ")", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L962-L964
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/bullet/minitaur_duck_gym_env.py
python
MinitaurBulletDuckEnv.get_minitaur_motor_velocities
(self)
return np.array( self._observation[MOTOR_VELOCITY_OBSERVATION_INDEX:MOTOR_VELOCITY_OBSERVATION_INDEX + NUM_MOTORS])
Get the minitaur's motor velocities. Returns: A numpy array of motor velocities.
Get the minitaur's motor velocities.
[ "Get", "the", "minitaur", "s", "motor", "velocities", "." ]
def get_minitaur_motor_velocities(self): """Get the minitaur's motor velocities. Returns: A numpy array of motor velocities. """ return np.array( self._observation[MOTOR_VELOCITY_OBSERVATION_INDEX:MOTOR_VELOCITY_OBSERVATION_INDEX + NUM_MOTORS])
[ "def", "get_minitaur_motor_velocities", "(", "self", ")", ":", "return", "np", ".", "array", "(", "self", ".", "_observation", "[", "MOTOR_VELOCITY_OBSERVATION_INDEX", ":", "MOTOR_VELOCITY_OBSERVATION_INDEX", "+", "NUM_MOTORS", "]", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/bullet/minitaur_duck_gym_env.py#L303-L311
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/examples/customization/bin-utils/binutils.py
python
positions
(width)
return ['{0:2}'.format(i)[-2:] for i in reversed(range(width))]
Helper function returning a list describing the bit positions. Bit positions greater than 99 are truncated to 2 digits, for example, 100 -> 00 and 127 -> 27.
Helper function returning a list describing the bit positions. Bit positions greater than 99 are truncated to 2 digits, for example, 100 -> 00 and 127 -> 27.
[ "Helper", "function", "returning", "a", "list", "describing", "the", "bit", "positions", ".", "Bit", "positions", "greater", "than", "99", "are", "truncated", "to", "2", "digits", "for", "example", "100", "-", ">", "00", "and", "127", "-", ">", "27", "."...
def positions(width): """Helper function returning a list describing the bit positions. Bit positions greater than 99 are truncated to 2 digits, for example, 100 -> 00 and 127 -> 27.""" return ['{0:2}'.format(i)[-2:] for i in reversed(range(width))]
[ "def", "positions", "(", "width", ")", ":", "return", "[", "'{0:2}'", ".", "format", "(", "i", ")", "[", "-", "2", ":", "]", "for", "i", "in", "reversed", "(", "range", "(", "width", ")", ")", "]" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/examples/customization/bin-utils/binutils.py#L58-L62
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py
python
_NestingState.UpdatePreprocessor
(self, line)
Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check.
Update preprocessor stack.
[ "Update", "preprocessor", "stack", "." ]
def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass
[ "def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "# Beginning of #if block, save the nesting stack here. The saved", "# stack will allow us to restore the parsing state in the #else cas...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py#L1948-L2002
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/RecoTrack/python/plotting/plotting.py
python
PlotTextBox.__init__
(self, xmin, ymin, xmax, ymax, lineheight=0.04, fillColor=ROOT.kWhite, transparent=True, **kwargs)
Constructor Arguments: xmin -- X min coordinate of the box (NDC) ymin -- Y min coordinate of the box (NDC) (if None, deduced automatically) xmax -- X max coordinate of the box (NDC) ymax -- Y max coordinate of the box (NDC) lineheight -- Line height fillColor -- Fill color of the box transparent -- Should the box be transparent? (in practive the TPave is not created) Keyword arguments are forwarded to constructor of PlotText
Constructor
[ "Constructor" ]
def __init__(self, xmin, ymin, xmax, ymax, lineheight=0.04, fillColor=ROOT.kWhite, transparent=True, **kwargs): """Constructor Arguments: xmin -- X min coordinate of the box (NDC) ymin -- Y min coordinate of the box (NDC) (if None, deduced automatically) xmax -- X max coordinate of the box (NDC) ymax -- Y max coordinate of the box (NDC) lineheight -- Line height fillColor -- Fill color of the box transparent -- Should the box be transparent? (in practive the TPave is not created) Keyword arguments are forwarded to constructor of PlotText """ # ROOT.TPave Set/GetX1NDC() etc don't seem to work as expected. self._xmin = xmin self._xmax = xmax self._ymin = ymin self._ymax = ymax self._lineheight = lineheight self._fillColor = fillColor self._transparent = transparent self._texts = [] self._textArgs = {} self._textArgs.update(kwargs) self._currenty = ymax
[ "def", "__init__", "(", "self", ",", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ",", "lineheight", "=", "0.04", ",", "fillColor", "=", "ROOT", ".", "kWhite", ",", "transparent", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# ROOT.TPave Set/GetX...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/plotting.py#L1585-L1611
yan99033/CNN-SVO
d5591ea88103f8d1b26e5296129bf3b3196a14f1
rpg_vikit/vikit_py/src/vikit_py/transformations.py
python
decompose_matrix
(matrix)
return scale, shear, angles, translate, perspective
Return sequence of transformations from transformation matrix. matrix : array_like Non-degenerative homogeneous transformation matrix Return tuple of: scale : vector of 3 scaling factors shear : list of shear factors for x-y, x-z, y-z axes angles : list of Euler angles about static x, y, z axes translate : translation vector along x, y, z axes perspective : perspective partition of matrix Raise ValueError if matrix is of wrong type or degenerative. >>> T0 = translation_matrix((1, 2, 3)) >>> scale, shear, angles, trans, persp = decompose_matrix(T0) >>> T1 = translation_matrix(trans) >>> numpy.allclose(T0, T1) True >>> S = scale_matrix(0.123) >>> scale, shear, angles, trans, persp = decompose_matrix(S) >>> scale[0] 0.123 >>> R0 = euler_matrix(1, 2, 3) >>> scale, shear, angles, trans, persp = decompose_matrix(R0) >>> R1 = euler_matrix(*angles) >>> numpy.allclose(R0, R1) True
Return sequence of transformations from transformation matrix.
[ "Return", "sequence", "of", "transformations", "from", "transformation", "matrix", "." ]
def decompose_matrix(matrix): """Return sequence of transformations from transformation matrix. matrix : array_like Non-degenerative homogeneous transformation matrix Return tuple of: scale : vector of 3 scaling factors shear : list of shear factors for x-y, x-z, y-z axes angles : list of Euler angles about static x, y, z axes translate : translation vector along x, y, z axes perspective : perspective partition of matrix Raise ValueError if matrix is of wrong type or degenerative. >>> T0 = translation_matrix((1, 2, 3)) >>> scale, shear, angles, trans, persp = decompose_matrix(T0) >>> T1 = translation_matrix(trans) >>> numpy.allclose(T0, T1) True >>> S = scale_matrix(0.123) >>> scale, shear, angles, trans, persp = decompose_matrix(S) >>> scale[0] 0.123 >>> R0 = euler_matrix(1, 2, 3) >>> scale, shear, angles, trans, persp = decompose_matrix(R0) >>> R1 = euler_matrix(*angles) >>> numpy.allclose(R0, R1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=True).T if abs(M[3, 3]) < _EPS: raise ValueError("M[3, 3] is zero") M /= M[3, 3] P = M.copy() P[:, 3] = 0, 0, 0, 1 if not numpy.linalg.det(P): raise ValueError("Matrix is singular") scale = numpy.zeros((3, ), dtype=numpy.float64) shear = [0, 0, 0] angles = [0, 0, 0] if any(abs(M[:3, 3]) > _EPS): perspective = numpy.dot(M[:, 3], numpy.linalg.inv(P.T)) M[:, 3] = 0, 0, 0, 1 else: perspective = numpy.array((0, 0, 0, 1), dtype=numpy.float64) translate = M[3, :3].copy() M[3, :3] = 0 row = M[:3, :3].copy() scale[0] = vector_norm(row[0]) row[0] /= scale[0] shear[0] = numpy.dot(row[0], row[1]) row[1] -= row[0] * shear[0] scale[1] = vector_norm(row[1]) row[1] /= scale[1] shear[0] /= scale[1] shear[1] = numpy.dot(row[0], row[2]) row[2] -= row[0] * shear[1] shear[2] = numpy.dot(row[1], row[2]) row[2] -= row[1] * shear[2] scale[2] = vector_norm(row[2]) row[2] /= scale[2] shear[1:] /= scale[2] if numpy.dot(row[0], numpy.cross(row[1], row[2])) < 0: scale *= -1 row *= -1 angles[1] = math.asin(-row[0, 2]) if math.cos(angles[1]): angles[0] = math.atan2(row[1, 2], row[2, 2]) angles[2] = math.atan2(row[0, 1], row[0, 0]) else: #angles[0] = math.atan2(row[1, 0], row[1, 1]) angles[0] = math.atan2(-row[2, 1], row[1, 1]) angles[2] = 0.0 return scale, shear, angles, translate, perspective
[ "def", "decompose_matrix", "(", "matrix", ")", ":", "M", "=", "numpy", ".", "array", "(", "matrix", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", ".", "T", "if", "abs", "(", "M", "[", "3", ",", "3", "]", ")", "<", ...
https://github.com/yan99033/CNN-SVO/blob/d5591ea88103f8d1b26e5296129bf3b3196a14f1/rpg_vikit/vikit_py/src/vikit_py/transformations.py#L704-L786
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
xmlNode.addChildList
(self, cur)
return __tmp
Add a list of node at the end of the child list of the parent merging adjacent TEXT nodes (@cur may be freed)
Add a list of node at the end of the child list of the parent merging adjacent TEXT nodes (
[ "Add", "a", "list", "of", "node", "at", "the", "end", "of", "the", "child", "list", "of", "the", "parent", "merging", "adjacent", "TEXT", "nodes", "(" ]
def addChildList(self, cur): """Add a list of node at the end of the child list of the parent merging adjacent TEXT nodes (@cur may be freed) """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlAddChildList(self._o, cur__o) if ret is None:raise treeError('xmlAddChildList() failed') __tmp = xmlNode(_obj=ret) return __tmp
[ "def", "addChildList", "(", "self", ",", "cur", ")", ":", "if", "cur", "is", "None", ":", "cur__o", "=", "None", "else", ":", "cur__o", "=", "cur", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlAddChildList", "(", "self", ".", "_o", ",", "cur__o", ...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L3088-L3096
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/analyzer.py
python
_ToGypPath
(path)
return path
Converts a path to the format used by gyp.
Converts a path to the format used by gyp.
[ "Converts", "a", "path", "to", "the", "format", "used", "by", "gyp", "." ]
def _ToGypPath(path): """Converts a path to the format used by gyp.""" if os.sep == '\\' and os.altsep == '/': return path.replace('\\', '/') return path
[ "def", "_ToGypPath", "(", "path", ")", ":", "if", "os", ".", "sep", "==", "'\\\\'", "and", "os", ".", "altsep", "==", "'/'", ":", "return", "path", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "return", "path" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/analyzer.py#L76-L80
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGrid.GetCommonValueLabel
(*args, **kwargs)
return _propgrid.PropertyGrid_GetCommonValueLabel(*args, **kwargs)
GetCommonValueLabel(self, int i) -> String
GetCommonValueLabel(self, int i) -> String
[ "GetCommonValueLabel", "(", "self", "int", "i", ")", "-", ">", "String" ]
def GetCommonValueLabel(*args, **kwargs): """GetCommonValueLabel(self, int i) -> String""" return _propgrid.PropertyGrid_GetCommonValueLabel(*args, **kwargs)
[ "def", "GetCommonValueLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_GetCommonValueLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2327-L2329
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
SourceLocation.file
(self)
return self._get_instantiation()[0]
Get the file represented by this source location.
Get the file represented by this source location.
[ "Get", "the", "file", "represented", "by", "this", "source", "location", "." ]
def file(self): """Get the file represented by this source location.""" return self._get_instantiation()[0]
[ "def", "file", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "0", "]" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L198-L200
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_data.py
python
DebugDumpDir.node_device
(self, node_name)
return output[0] if len(output) == 1 else output
Get the names of the devices that has nodes of the specified name. Args: node_name: (`str`) name of the node. Returns: (`str` or `list` of `str`) name of the device(s) on which the node of the given name is found. Returns a `str` if there is only one such device, otherwise return a `list` of `str`. Raises: LookupError: If node inputs and control inputs have not been loaded from partition graphs yet. ValueError: If the node does not exist in partition graphs.
Get the names of the devices that has nodes of the specified name.
[ "Get", "the", "names", "of", "the", "devices", "that", "has", "nodes", "of", "the", "specified", "name", "." ]
def node_device(self, node_name): """Get the names of the devices that has nodes of the specified name. Args: node_name: (`str`) name of the node. Returns: (`str` or `list` of `str`) name of the device(s) on which the node of the given name is found. Returns a `str` if there is only one such device, otherwise return a `list` of `str`. Raises: LookupError: If node inputs and control inputs have not been loaded from partition graphs yet. ValueError: If the node does not exist in partition graphs. """ if not self._debug_graphs: raise LookupError( "Node devices are not loaded from partition graphs yet.") if node_name not in self._node_devices: raise ValueError("Node '%s' does not exist in partition graphs." % node_name) output = list(self._node_devices[node_name]) return output[0] if len(output) == 1 else output
[ "def", "node_device", "(", "self", ",", "node_name", ")", ":", "if", "not", "self", ".", "_debug_graphs", ":", "raise", "LookupError", "(", "\"Node devices are not loaded from partition graphs yet.\"", ")", "if", "node_name", "not", "in", "self", ".", "_node_devices...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_data.py#L1297-L1322
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py
python
pooling_ndhwc_max
( I=TensorDef(T1, S.N, S.OD * S.SD + S.KD * S.DD, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.C), K=TensorDef(T2, S.KD, S.KH, S.KW, index_dims=[D.kd, D.kh, D.kw]), O=TensorDef(U, S.N, S.OD, S.OH, S.OW, S.C, output=True), strides=IndexAttrDef(S.SD, S.SH, S.SW), dilations=IndexAttrDef(S.DD, S.DH, S.DW))
Performs 3D max pooling. Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output.
Performs 3D max pooling.
[ "Performs", "3D", "max", "pooling", "." ]
def pooling_ndhwc_max( I=TensorDef(T1, S.N, S.OD * S.SD + S.KD * S.DD, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.C), K=TensorDef(T2, S.KD, S.KH, S.KW, index_dims=[D.kd, D.kh, D.kw]), O=TensorDef(U, S.N, S.OD, S.OH, S.OW, S.C, output=True), strides=IndexAttrDef(S.SD, S.SH, S.SW), dilations=IndexAttrDef(S.DD, S.DH, S.DW)): """Performs 3D max pooling. Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output. """ implements(ConvolutionOpInterface) domain(D.n, D.od, D.oh, D.ow, D.c, D.kd, D.kh, D.kw) O[D.n, D.od, D.oh, D.ow, D.c] = ReduceFn.max[D.kd, D.kh, D.kw]( TypeFn.cast( U, I[D.n, D.od * S.SD + D.kd * S.DD, D.oh * S.SH + D.kh * S.DH, D.ow * S.SW + D.kw * S.DW, D.c]))
[ "def", "pooling_ndhwc_max", "(", "I", "=", "TensorDef", "(", "T1", ",", "S", ".", "N", ",", "S", ".", "OD", "*", "S", ".", "SD", "+", "S", ".", "KD", "*", "S", ".", "DD", ",", "S", ".", "OH", "*", "S", ".", "SH", "+", "S", ".", "KH", "*...
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L589-L606
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/handlers.py
python
fix_route53_ids
(params, model, **kwargs)
Check for and split apart Route53 resource IDs, setting only the last piece. This allows the output of one operation (e.g. ``'foo/1234'``) to be used as input in another operation (e.g. it expects just ``'1234'``).
Check for and split apart Route53 resource IDs, setting only the last piece. This allows the output of one operation (e.g. ``'foo/1234'``) to be used as input in another operation (e.g. it expects just ``'1234'``).
[ "Check", "for", "and", "split", "apart", "Route53", "resource", "IDs", "setting", "only", "the", "last", "piece", ".", "This", "allows", "the", "output", "of", "one", "operation", "(", "e", ".", "g", ".", "foo", "/", "1234", ")", "to", "be", "used", ...
def fix_route53_ids(params, model, **kwargs): """ Check for and split apart Route53 resource IDs, setting only the last piece. This allows the output of one operation (e.g. ``'foo/1234'``) to be used as input in another operation (e.g. it expects just ``'1234'``). """ input_shape = model.input_shape if not input_shape or not hasattr(input_shape, 'members'): return members = [name for (name, shape) in input_shape.members.items() if shape.name in ['ResourceId', 'DelegationSetId']] for name in members: if name in params: orig_value = params[name] params[name] = orig_value.split('/')[-1] logger.debug('%s %s -> %s', name, orig_value, params[name])
[ "def", "fix_route53_ids", "(", "params", ",", "model", ",", "*", "*", "kwargs", ")", ":", "input_shape", "=", "model", ".", "input_shape", "if", "not", "input_shape", "or", "not", "hasattr", "(", "input_shape", ",", "'members'", ")", ":", "return", "member...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/handlers.py#L549-L567
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py
python
IRBuilder.insert_value
(self, agg, value, idx, name='')
return instr
Insert *value* into member number *idx* from aggregate.
Insert *value* into member number *idx* from aggregate.
[ "Insert", "*", "value", "*", "into", "member", "number", "*", "idx", "*", "from", "aggregate", "." ]
def insert_value(self, agg, value, idx, name=''): """ Insert *value* into member number *idx* from aggregate. """ if not isinstance(idx, (tuple, list)): idx = [idx] instr = instructions.InsertValue(self.block, agg, value, idx, name=name) self._insert(instr) return instr
[ "def", "insert_value", "(", "self", ",", "agg", ",", "value", ",", "idx", ",", "name", "=", "''", ")", ":", "if", "not", "isinstance", "(", "idx", ",", "(", "tuple", ",", "list", ")", ")", ":", "idx", "=", "[", "idx", "]", "instr", "=", "instru...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py#L931-L939
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/util/lib/common/util.py
python
DoesUrlExist
(url)
return response.status == 200
Determines whether a resource exists at the given URL. Args: url: URL to be verified. Returns: True if url exists, otherwise False.
Determines whether a resource exists at the given URL.
[ "Determines", "whether", "a", "resource", "exists", "at", "the", "given", "URL", "." ]
def DoesUrlExist(url): """Determines whether a resource exists at the given URL. Args: url: URL to be verified. Returns: True if url exists, otherwise False. """ parsed = urlparse.urlparse(url) try: conn = httplib.HTTPConnection(parsed.netloc) conn.request('HEAD', parsed.path) response = conn.getresponse() except (socket.gaierror, socket.error): return False finally: conn.close() # Follow both permanent (301) and temporary (302) redirects. if response.status == 302 or response.status == 301: return DoesUrlExist(response.getheader('location')) return response.status == 200
[ "def", "DoesUrlExist", "(", "url", ")", ":", "parsed", "=", "urlparse", ".", "urlparse", "(", "url", ")", "try", ":", "conn", "=", "httplib", ".", "HTTPConnection", "(", "parsed", ".", "netloc", ")", "conn", ".", "request", "(", "'HEAD'", ",", "parsed"...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/util/lib/common/util.py#L130-L151
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/run_benchmark.py
python
CaffeBenchmark.get_local_ip_lists
(self)
get local ip lists
get local ip lists
[ "get", "local", "ip", "lists" ]
def get_local_ip_lists(self): '''get local ip lists''' exec_command = 'ip addr' out = self._exec_command(exec_command) ip_pattern = re.compile(".*inet [0-9]+.*") self.local_ips = [] for line in out.split('\n'): if re.match(ip_pattern, line): ip = line.split()[1].split('/')[0] self.local_ips.append(ip) if len(self.local_ips) == 0: logging.exception("Can't find available ips on local node.") hostname = socket.gethostname() self.local_ips.append(hostname)
[ "def", "get_local_ip_lists", "(", "self", ")", ":", "exec_command", "=", "'ip addr'", "out", "=", "self", ".", "_exec_command", "(", "exec_command", ")", "ip_pattern", "=", "re", ".", "compile", "(", "\".*inet [0-9]+.*\"", ")", "self", ".", "local_ips", "=", ...
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/run_benchmark.py#L353-L366
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/distutils/misc_util.py
python
rel_path
(path, parent_path)
return path
Return path relative to parent_path.
Return path relative to parent_path.
[ "Return", "path", "relative", "to", "parent_path", "." ]
def rel_path(path, parent_path): """Return path relative to parent_path. """ pd = os.path.abspath(parent_path) apath = os.path.abspath(path) if len(apath)<len(pd): return path if apath==pd: return '' if pd == apath[:len(pd)]: assert apath[len(pd)] in [os.sep],repr((path,apath[len(pd)])) path = apath[len(pd)+1:] return path
[ "def", "rel_path", "(", "path", ",", "parent_path", ")", ":", "pd", "=", "os", ".", "path", ".", "abspath", "(", "parent_path", ")", "apath", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "len", "(", "apath", ")", "<", "len", "(...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/misc_util.py#L75-L87
raymondlu/super-animation-samples
04234269112ff0dc32447f27a761dbbb00b8ba17
samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Cursor.is_static_method
(self)
return conf.lib.clang_CXXMethod_isStatic(self)
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "member", "function", "or", "member", "function", "template", "that", "is", "declared", "static", "." ]
def is_static_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'. """ return conf.lib.clang_CXXMethod_isStatic(self)
[ "def", "is_static_method", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXMethod_isStatic", "(", "self", ")" ]
https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1218-L1222
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/colorama/ansitowin32.py
python
AnsiToWin32.write_and_convert
(self, text)
Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.
Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.
[ "Write", "the", "given", "text", "to", "our", "wrapped", "stream", "stripping", "any", "ANSI", "sequences", "from", "the", "text", "and", "optionally", "converting", "them", "into", "win32", "calls", "." ]
def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 text = self.convert_osc(text) for match in self.ANSI_CSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
[ "def", "write_and_convert", "(", "self", ",", "text", ")", ":", "cursor", "=", "0", "text", "=", "self", ".", "convert_osc", "(", "text", ")", "for", "match", "in", "self", ".", "ANSI_CSI_RE", ".", "finditer", "(", "text", ")", ":", "start", ",", "en...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/colorama/ansitowin32.py#L148-L161
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/collections.py
python
OrderedDict.viewitems
(self)
return ItemsView(self)
od.viewitems() -> a set-like object providing a view on od's items
od.viewitems() -> a set-like object providing a view on od's items
[ "od", ".", "viewitems", "()", "-", ">", "a", "set", "-", "like", "object", "providing", "a", "view", "on", "od", "s", "items" ]
def viewitems(self): "od.viewitems() -> a set-like object providing a view on od's items" return ItemsView(self)
[ "def", "viewitems", "(", "self", ")", ":", "return", "ItemsView", "(", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/collections.py#L225-L227
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/google_appengine_cloudstorage/cloudstorage/common.py
python
memory_usage
(method)
return wrapper
Log memory usage before and after a method.
Log memory usage before and after a method.
[ "Log", "memory", "usage", "before", "and", "after", "a", "method", "." ]
def memory_usage(method): """Log memory usage before and after a method.""" def wrapper(*args, **kwargs): logging.info('Memory before method %s is %s.', method.__name__, runtime.memory_usage().current()) result = method(*args, **kwargs) logging.info('Memory after method %s is %s', method.__name__, runtime.memory_usage().current()) return result return wrapper
[ "def", "memory_usage", "(", "method", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "info", "(", "'Memory before method %s is %s.'", ",", "method", ".", "__name__", ",", "runtime", ".", "memory_usage", "("...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/common.py#L384-L393
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
syzygy/build/get_syzygy_binaries.py
python
_BuildActualState
(stored, revision, output_dir)
return state
Builds the actual state using the provided |stored| state as a template. Only examines files listed in the stored state, causing the script to ignore files that have been added to the directories locally. |stored| must be a valid state dictionary.
Builds the actual state using the provided |stored| state as a template. Only examines files listed in the stored state, causing the script to ignore files that have been added to the directories locally. |stored| must be a valid state dictionary.
[ "Builds", "the", "actual", "state", "using", "the", "provided", "|stored|", "state", "as", "a", "template", ".", "Only", "examines", "files", "listed", "in", "the", "stored", "state", "causing", "the", "script", "to", "ignore", "files", "that", "have", "been...
def _BuildActualState(stored, revision, output_dir): """Builds the actual state using the provided |stored| state as a template. Only examines files listed in the stored state, causing the script to ignore files that have been added to the directories locally. |stored| must be a valid state dictionary. """ contents = {} state = { 'revision': revision, 'contents': contents } for relpath, md5 in stored['contents'].iteritems(): abspath = os.path.abspath(os.path.join(output_dir, relpath)) if os.path.isfile(abspath): m = _Md5(abspath) contents[relpath] = m return state
[ "def", "_BuildActualState", "(", "stored", ",", "revision", ",", "output_dir", ")", ":", "contents", "=", "{", "}", "state", "=", "{", "'revision'", ":", "revision", ",", "'contents'", ":", "contents", "}", "for", "relpath", ",", "md5", "in", "stored", "...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/syzygy/build/get_syzygy_binaries.py#L116-L130
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py
python
make_anonymous_struct
(builder, values, struct_type=None)
return struct_val
Create an anonymous struct containing the given LLVM *values*.
Create an anonymous struct containing the given LLVM *values*.
[ "Create", "an", "anonymous", "struct", "containing", "the", "given", "LLVM", "*", "values", "*", "." ]
def make_anonymous_struct(builder, values, struct_type=None): """ Create an anonymous struct containing the given LLVM *values*. """ if struct_type is None: struct_type = ir.LiteralStructType([v.type for v in values]) struct_val = struct_type(ir.Undefined) for i, v in enumerate(values): struct_val = builder.insert_value(struct_val, v, i) return struct_val
[ "def", "make_anonymous_struct", "(", "builder", ",", "values", ",", "struct_type", "=", "None", ")", ":", "if", "struct_type", "is", "None", ":", "struct_type", "=", "ir", ".", "LiteralStructType", "(", "[", "v", ".", "type", "for", "v", "in", "values", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py#L32-L41
bigtreetech/BIGTREETECH-SKR-V1.3
b238aa402753e81d551b7d34a181a262a138ae9e
BTT SKR V1.4/Firmware/Marlin-2.0.x-SKR-V1.4-Turbo/Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/ftdi_eve_lib/extras/svg2cpp.py
python
Parser.process_svg_path_data_cmd
(self, id, cmd, a, b)
Converts the various types of moves into L or M commands and dispatches to process_svg_path_L_or_M for futher processing.
Converts the various types of moves into L or M commands and dispatches to process_svg_path_L_or_M for futher processing.
[ "Converts", "the", "various", "types", "of", "moves", "into", "L", "or", "M", "commands", "and", "dispatches", "to", "process_svg_path_L_or_M", "for", "futher", "processing", "." ]
def process_svg_path_data_cmd(self, id, cmd, a, b): """Converts the various types of moves into L or M commands and dispatches to process_svg_path_L_or_M for futher processing.""" if cmd == "Z" or cmd == "z": self.process_svg_path_L_or_M("L", self.initial_x, self.initial_y) elif cmd == "H": self.process_svg_path_L_or_M("L", a, self.last_y) elif cmd == "V": self.process_svg_path_L_or_M("L", self.last_x, a) elif cmd == "h": self.process_svg_path_L_or_M("L", self.last_x + a, self.last_y) elif cmd == "v": self.process_svg_path_L_or_M("L", self.last_x, self.last_y + a) elif cmd == "L": self.process_svg_path_L_or_M("L", a, b) elif cmd == "l": self.process_svg_path_L_or_M("L", self.last_x + a, self.last_y + b) elif cmd == "M": self.process_svg_path_L_or_M("M", a, b) elif cmd == "m": self.process_svg_path_L_or_M("M", self.last_x + a, self.last_y + b) else: print("Unsupported path data command:", cmd, "in path", id, "\n", file=sys.stderr) quit()
[ "def", "process_svg_path_data_cmd", "(", "self", ",", "id", ",", "cmd", ",", "a", ",", "b", ")", ":", "if", "cmd", "==", "\"Z\"", "or", "cmd", "==", "\"z\"", ":", "self", ".", "process_svg_path_L_or_M", "(", "\"L\"", ",", "self", ".", "initial_x", ",",...
https://github.com/bigtreetech/BIGTREETECH-SKR-V1.3/blob/b238aa402753e81d551b7d34a181a262a138ae9e/BTT SKR V1.4/Firmware/Marlin-2.0.x-SKR-V1.4-Turbo/Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/ftdi_eve_lib/extras/svg2cpp.py#L165-L188
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/ops.py
python
get_stats_for_node_def
(graph, node, statistic_type)
return result
Looks up the node's statistics function in the registry and calls it. This function takes a Graph object and a NodeDef from a GraphDef, and if there's an associated statistics method, calls it and returns a result. If no function has been registered for the particular node type, it returns an empty statistics object. Args: graph: A Graph object that's been set up with the node's graph. node: A NodeDef describing the operator. statistic_type: A string identifying the statistic we're interested in. Returns: An OpStats object containing information about resource usage.
Looks up the node's statistics function in the registry and calls it.
[ "Looks", "up", "the", "node", "s", "statistics", "function", "in", "the", "registry", "and", "calls", "it", "." ]
def get_stats_for_node_def(graph, node, statistic_type): """Looks up the node's statistics function in the registry and calls it. This function takes a Graph object and a NodeDef from a GraphDef, and if there's an associated statistics method, calls it and returns a result. If no function has been registered for the particular node type, it returns an empty statistics object. Args: graph: A Graph object that's been set up with the node's graph. node: A NodeDef describing the operator. statistic_type: A string identifying the statistic we're interested in. Returns: An OpStats object containing information about resource usage. """ try: stats_func = _stats_registry.lookup(node.op + "," + statistic_type) result = stats_func(graph, node) except LookupError: result = OpStats(statistic_type) return result
[ "def", "get_stats_for_node_def", "(", "graph", ",", "node", ",", "statistic_type", ")", ":", "try", ":", "stats_func", "=", "_stats_registry", ".", "lookup", "(", "node", ".", "op", "+", "\",\"", "+", "statistic_type", ")", "result", "=", "stats_func", "(", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L1911-L1932
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/nntplib.py
python
NNTP.newgroups
(self, date, time, file=None)
return self.longcmd('NEWGROUPS ' + date + ' ' + time, file)
Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names
Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names
[ "Process", "a", "NEWGROUPS", "command", ".", "Arguments", ":", "-", "date", ":", "string", "yymmdd", "indicating", "the", "date", "-", "time", ":", "string", "hhmmss", "indicating", "the", "time", "Return", ":", "-", "resp", ":", "server", "response", "if"...
def newgroups(self, date, time, file=None): """Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names""" return self.longcmd('NEWGROUPS ' + date + ' ' + time, file)
[ "def", "newgroups", "(", "self", ",", "date", ",", "time", ",", "file", "=", "None", ")", ":", "return", "self", ".", "longcmd", "(", "'NEWGROUPS '", "+", "date", "+", "' '", "+", "time", ",", "file", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/nntplib.py#L266-L274
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_patharray.py
python
PathArray.Activated
(self, name="Path array")
Execute when the command is called.
Execute when the command is called.
[ "Execute", "when", "the", "command", "is", "called", "." ]
def Activated(self, name="Path array"): """Execute when the command is called.""" super(PathArray, self).Activated(name=name) self.name = name # This was deactivated because it doesn't work correctly; # the selection needs to be made on two objects, but currently # it only selects one. # if not Gui.Selection.getSelectionEx(): # if self.ui: # self.ui.selectUi() # _msg(translate("draft", # "Please select exactly two objects, " # "the base object and the path object, " # "before calling this command.")) # self.call = \ # self.view.addEventCallback("SoEvent", # gui_tool_utils.selectObject) # else: # self.proceed() self.proceed()
[ "def", "Activated", "(", "self", ",", "name", "=", "\"Path array\"", ")", ":", "super", "(", "PathArray", ",", "self", ")", ".", "Activated", "(", "name", "=", "name", ")", "self", ".", "name", "=", "name", "# This was deactivated because it doesn't work corre...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_patharray.py#L76-L96
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/centre_finder.py
python
is_workspace_which_requires_angle
(reducer)
return False
Check if the sample worksapce requires the first coordinate to be an angle @param reducer: the reducer object @returns true if the workspace requires an angle otherwise false
Check if the sample worksapce requires the first coordinate to be an angle
[ "Check", "if", "the", "sample", "worksapce", "requires", "the", "first", "coordinate", "to", "be", "an", "angle" ]
def is_workspace_which_requires_angle(reducer): ''' Check if the sample worksapce requires the first coordinate to be an angle @param reducer: the reducer object @returns true if the workspace requires an angle otherwise false ''' instrument_name = reducer.instrument.name() if instrument_name != LARMOR._NAME: return False workspace_name = reducer.get_sample().wksp_name if workspace_name: ws_ref = mtd[workspace_name] return LARMOR.is_run_new_style_run(ws_ref) return False
[ "def", "is_workspace_which_requires_angle", "(", "reducer", ")", ":", "instrument_name", "=", "reducer", ".", "instrument", ".", "name", "(", ")", "if", "instrument_name", "!=", "LARMOR", ".", "_NAME", ":", "return", "False", "workspace_name", "=", "reducer", "....
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/centre_finder.py#L24-L38
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py
python
get_tcpros_server_address
()
return _tcpros_server.get_address()
get the address of the tcpros server. @raise Exception: if tcpros server has not been started or created
get the address of the tcpros server.
[ "get", "the", "address", "of", "the", "tcpros", "server", "." ]
def get_tcpros_server_address(): """ get the address of the tcpros server. @raise Exception: if tcpros server has not been started or created """ return _tcpros_server.get_address()
[ "def", "get_tcpros_server_address", "(", ")", ":", "return", "_tcpros_server", ".", "get_address", "(", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py#L238-L243
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/motionplanning.py
python
CSpaceInterface.feasibilityCost
(self, name: "char const *")
return _motionplanning.CSpaceInterface_feasibilityCost(self, name)
r""" feasibilityCost(CSpaceInterface self, char const * name) -> double Retrieves the empirical average cost of a given feasibility test.
r""" feasibilityCost(CSpaceInterface self, char const * name) -> double
[ "r", "feasibilityCost", "(", "CSpaceInterface", "self", "char", "const", "*", "name", ")", "-", ">", "double" ]
def feasibilityCost(self, name: "char const *") -> "double": r""" feasibilityCost(CSpaceInterface self, char const * name) -> double Retrieves the empirical average cost of a given feasibility test. """ return _motionplanning.CSpaceInterface_feasibilityCost(self, name)
[ "def", "feasibilityCost", "(", "self", ",", "name", ":", "\"char const *\"", ")", "->", "\"double\"", ":", "return", "_motionplanning", ".", "CSpaceInterface_feasibilityCost", "(", "self", ",", "name", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/motionplanning.py#L755-L763
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
tools/pytorch-quantization/pytorch_quantization/tensor_quant.py
python
_tensor_quant
(inputs, amax, num_bits=8, unsigned=False, narrow_range=True)
return outputs, scale
Shared function body between TensorQuantFunction and FakeTensorQuantFunction
Shared function body between TensorQuantFunction and FakeTensorQuantFunction
[ "Shared", "function", "body", "between", "TensorQuantFunction", "and", "FakeTensorQuantFunction" ]
def _tensor_quant(inputs, amax, num_bits=8, unsigned=False, narrow_range=True): """Shared function body between TensorQuantFunction and FakeTensorQuantFunction""" # Fine scale, per channel scale will be handled by broadcasting, which could be tricky. Pop a warning. if isinstance(amax, torch.Tensor) and inputs.dim() != amax.dim(): logging.debug("amax %s has different shape than inputs %s. Make sure broadcast works as expected!", amax.size(), inputs.size()) logging.debug("{} bits quantization on shape {} tensor.".format(num_bits, inputs.size())) if unsigned: if inputs.min() < 0.: raise TypeError("Negative values encountered in unsigned quantization.") # Computation must be in FP32 to prevent potential over flow. input_dtype = inputs.dtype if inputs.dtype == torch.half: inputs = inputs.float() if amax.dtype == torch.half: amax = amax.float() min_amax = amax.min() if min_amax < 0: raise ValueError("Negative values in amax") max_bound = torch.tensor((2.0**(num_bits - 1 + int(unsigned))) - 1.0, device=amax.device) if unsigned: min_bound = 0 elif narrow_range: min_bound = -max_bound else: min_bound = -max_bound - 1 scale = max_bound / amax epsilon = 1. / (1<<24) if min_amax <= epsilon: # Treat amax smaller than minimum representable of fp16 0 zero_amax_mask = (amax <= epsilon) scale[zero_amax_mask] = 0 # Value quantized with amax=0 should all be 0 outputs = torch.clamp((inputs * scale).round_(), min_bound, max_bound) if min_amax <= epsilon: scale[zero_amax_mask] = 1. # Return 1 makes more sense for values quantized to 0 with amax=0 if input_dtype == torch.half: outputs = outputs.half() return outputs, scale
[ "def", "_tensor_quant", "(", "inputs", ",", "amax", ",", "num_bits", "=", "8", ",", "unsigned", "=", "False", ",", "narrow_range", "=", "True", ")", ":", "# Fine scale, per channel scale will be handled by broadcasting, which could be tricky. Pop a warning.", "if", "isins...
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/pytorch-quantization/pytorch_quantization/tensor_quant.py#L315-L361
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/yaml/__init__.py
python
dump_all
(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None)
Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead.
Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead.
[ "Serialize", "a", "sequence", "of", "Python", "objects", "into", "a", "YAML", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", "." ]
def dump_all(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None): """ Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: if encoding is None: from StringIO import StringIO else: from cStringIO import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, default_style=default_style, default_flow_style=default_flow_style, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, encoding=encoding, version=version, tags=tags, explicit_start=explicit_start, explicit_end=explicit_end) try: dumper.open() for data in documents: dumper.represent(data) dumper.close() finally: dumper.dispose() if getvalue: return getvalue()
[ "def", "dump_all", "(", "documents", ",", "stream", "=", "None", ",", "Dumper", "=", "Dumper", ",", "default_style", "=", "None", ",", "default_flow_style", "=", "None", ",", "canonical", "=", "None", ",", "indent", "=", "None", ",", "width", "=", "None"...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/yaml/__init__.py#L163-L195
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
src/bindings/python/src/openvino/runtime/opset5/ops.py
python
log_softmax
(data: NodeInput, axis: int, name: Optional[str] = None)
return _get_node_factory_opset5().create("LogSoftmax", [as_node(data)], {"axis": axis})
Apply LogSoftmax operation on each element of input tensor. @param data: The tensor providing input data. @param axis: An axis along which LogSoftmax should be calculated @return: The new node with LogSoftmax operation applied on each element.
Apply LogSoftmax operation on each element of input tensor.
[ "Apply", "LogSoftmax", "operation", "on", "each", "element", "of", "input", "tensor", "." ]
def log_softmax(data: NodeInput, axis: int, name: Optional[str] = None) -> Node: """Apply LogSoftmax operation on each element of input tensor. @param data: The tensor providing input data. @param axis: An axis along which LogSoftmax should be calculated @return: The new node with LogSoftmax operation applied on each element. """ return _get_node_factory_opset5().create("LogSoftmax", [as_node(data)], {"axis": axis})
[ "def", "log_softmax", "(", "data", ":", "NodeInput", ",", "axis", ":", "int", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Node", ":", "return", "_get_node_factory_opset5", "(", ")", ".", "create", "(", "\"LogSoftmax\"", ",", ...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset5/ops.py#L90-L97
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/type_checkers.py
python
ToShortestFloat
(original)
return rounded
Returns the shortest float that has same value in wire.
Returns the shortest float that has same value in wire.
[ "Returns", "the", "shortest", "float", "that", "has", "same", "value", "in", "wire", "." ]
def ToShortestFloat(original): """Returns the shortest float that has same value in wire.""" # All 4 byte floats have between 6 and 9 significant digits, so we # start with 6 as the lower bound. # It has to be iterative because use '.9g' directly can not get rid # of the noises for most values. For example if set a float_field=0.9 # use '.9g' will print 0.899999976. precision = 6 rounded = float('{0:.{1}g}'.format(original, precision)) while TruncateToFourByteFloat(rounded) != original: precision += 1 rounded = float('{0:.{1}g}'.format(original, precision)) return rounded
[ "def", "ToShortestFloat", "(", "original", ")", ":", "# All 4 byte floats have between 6 and 9 significant digits, so we", "# start with 6 as the lower bound.", "# It has to be iterative because use '.9g' directly can not get rid", "# of the noises for most values. For example if set a float_field...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/type_checkers.py#L75-L87
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/adidas_utils/solvers/symmetric/ate_anneal.py
python
euc_project
(dist, y)
return dist, y
Project variables onto their feasible sets (euclidean proj for dist). Args: dist: 1-d np.array, current estimate of nash distribution y: 1-d np.array (same shape as dist), current estimate of payoff gradient Returns: projected variables (dist, y) as tuple
Project variables onto their feasible sets (euclidean proj for dist).
[ "Project", "variables", "onto", "their", "feasible", "sets", "(", "euclidean", "proj", "for", "dist", ")", "." ]
def euc_project(dist, y): """Project variables onto their feasible sets (euclidean proj for dist). Args: dist: 1-d np.array, current estimate of nash distribution y: 1-d np.array (same shape as dist), current estimate of payoff gradient Returns: projected variables (dist, y) as tuple """ dist = simplex.euclidean_projection_onto_simplex(dist) y = np.clip(y, 0., np.inf) return dist, y
[ "def", "euc_project", "(", "dist", ",", "y", ")", ":", "dist", "=", "simplex", ".", "euclidean_projection_onto_simplex", "(", "dist", ")", "y", "=", "np", ".", "clip", "(", "y", ",", "0.", ",", "np", ".", "inf", ")", "return", "dist", ",", "y" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/symmetric/ate_anneal.py#L358-L370
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/pyyaml/examples/pygments-lexer/yaml.py
python
reset_indent
(TokenClass)
return callback
Reset the indentation levels.
Reset the indentation levels.
[ "Reset", "the", "indentation", "levels", "." ]
def reset_indent(TokenClass): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), TokenClass, text context.pos = match.end() return callback
[ "def", "reset_indent", "(", "TokenClass", ")", ":", "def", "callback", "(", "lexer", ",", "match", ",", "context", ")", ":", "text", "=", "match", ".", "group", "(", ")", "context", ".", "indent_stack", "=", "[", "]", "context", ".", "indent", "=", "...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/pyyaml/examples/pygments-lexer/yaml.py#L42-L52
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/internal/python_message.py
python
_AddStrMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__
[ "def", "_AddStrMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__str__", "(", "self", ")", ":", "return", "text_format", ".", "MessageToString", "(", "self", ")", "cls", ".", "__str__", "=", "__str__" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/python_message.py#L979-L983
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
python
Standard_Suite_Events.quit
(self, _no_object=None, _attributes={}, **_arguments)
quit: Quit an application Keyword argument saving: specifies whether to save currently open documents Keyword argument _attributes: AppleEvent attribute dictionary
quit: Quit an application Keyword argument saving: specifies whether to save currently open documents Keyword argument _attributes: AppleEvent attribute dictionary
[ "quit", ":", "Quit", "an", "application", "Keyword", "argument", "saving", ":", "specifies", "whether", "to", "save", "currently", "open", "documents", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def quit(self, _no_object=None, _attributes={}, **_arguments): """quit: Quit an application Keyword argument saving: specifies whether to save currently open documents Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'aevt' _subcode = 'quit' aetools.keysubst(_arguments, self._argmap_quit) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'savo', _Enum_savo) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "quit", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'aevt'", "_subcode", "=", "'quit'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py#L339-L358
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typing/context.py
python
BaseContext._get_attribute_templates
(self, typ)
Get matching AttributeTemplates for the Numba type.
Get matching AttributeTemplates for the Numba type.
[ "Get", "matching", "AttributeTemplates", "for", "the", "Numba", "type", "." ]
def _get_attribute_templates(self, typ): """ Get matching AttributeTemplates for the Numba type. """ if typ in self._attributes: for attrinfo in self._attributes[typ]: yield attrinfo else: for cls in type(typ).__mro__: if cls in self._attributes: for attrinfo in self._attributes[cls]: yield attrinfo
[ "def", "_get_attribute_templates", "(", "self", ",", "typ", ")", ":", "if", "typ", "in", "self", ".", "_attributes", ":", "for", "attrinfo", "in", "self", ".", "_attributes", "[", "typ", "]", ":", "yield", "attrinfo", "else", ":", "for", "cls", "in", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typing/context.py#L253-L264
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/graph_editor/edit.py
python
bypass
(sgv)
return sgv, detached_inputs
Bypass the given subgraph by connecting its inputs to its outputs. Args: sgv: the subgraph view to be bypassed. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. Returns: A new subgraph view of the bypassed subgraph. Note that sgv is also modified in place. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view.
Bypass the given subgraph by connecting its inputs to its outputs.
[ "Bypass", "the", "given", "subgraph", "by", "connecting", "its", "inputs", "to", "its", "outputs", "." ]
def bypass(sgv): """Bypass the given subgraph by connecting its inputs to its outputs. Args: sgv: the subgraph view to be bypassed. This argument is converted to a subgraph using the same rules than the function subgraph.make_view. Returns: A new subgraph view of the bypassed subgraph. Note that sgv is also modified in place. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ # TODO(fkp): allows to plug sgv.inputs to individual sgv.outputs consumers sgv = subgraph.make_view(sgv) sgv_inputs = list(sgv.inputs) sgv, detached_inputs = detach_inputs(sgv) reroute.reroute_a2b_ts(sgv_inputs, sgv.outputs) return sgv, detached_inputs
[ "def", "bypass", "(", "sgv", ")", ":", "# TODO(fkp): allows to plug sgv.inputs to individual sgv.outputs consumers", "sgv", "=", "subgraph", ".", "make_view", "(", "sgv", ")", "sgv_inputs", "=", "list", "(", "sgv", ".", "inputs", ")", "sgv", ",", "detached_inputs", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/edit.py#L183-L201
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
python
ScrolledCanvas.reset
(self, canvwidth=None, canvheight=None, bg = None)
Adjust canvas and scrollbars according to given canvas size.
Adjust canvas and scrollbars according to given canvas size.
[ "Adjust", "canvas", "and", "scrollbars", "according", "to", "given", "canvas", "size", "." ]
def reset(self, canvwidth=None, canvheight=None, bg = None): """Adjust canvas and scrollbars according to given canvas size.""" if canvwidth: self.canvwidth = canvwidth if canvheight: self.canvheight = canvheight if bg: self.bg = bg self._canvas.config(bg=bg, scrollregion=(-self.canvwidth//2, -self.canvheight//2, self.canvwidth//2, self.canvheight//2)) self._canvas.xview_moveto(0.5*(self.canvwidth - self.width + 30) / self.canvwidth) self._canvas.yview_moveto(0.5*(self.canvheight- self.height + 30) / self.canvheight) self.adjustScrolls()
[ "def", "reset", "(", "self", ",", "canvwidth", "=", "None", ",", "canvheight", "=", "None", ",", "bg", "=", "None", ")", ":", "if", "canvwidth", ":", "self", ".", "canvwidth", "=", "canvwidth", "if", "canvheight", ":", "self", ".", "canvheight", "=", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L384-L399
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/integrate/python/ops/odes.py
python
_interp_fit_rk
(y0, y1, k, dt, tableau=_DORMAND_PRINCE_TABLEAU)
Fit an interpolating polynomial to the results of a Runge-Kutta step.
Fit an interpolating polynomial to the results of a Runge-Kutta step.
[ "Fit", "an", "interpolating", "polynomial", "to", "the", "results", "of", "a", "Runge", "-", "Kutta", "step", "." ]
def _interp_fit_rk(y0, y1, k, dt, tableau=_DORMAND_PRINCE_TABLEAU): """Fit an interpolating polynomial to the results of a Runge-Kutta step.""" with ops.name_scope('interp_fit_rk'): dt = math_ops.cast(dt, y0.dtype) y_mid = y0 + _scaled_dot_product(dt, tableau.c_mid, k) f0 = k[0] f1 = k[-1] return _interp_fit(y0, y1, y_mid, f0, f1, dt)
[ "def", "_interp_fit_rk", "(", "y0", ",", "y1", ",", "k", ",", "dt", ",", "tableau", "=", "_DORMAND_PRINCE_TABLEAU", ")", ":", "with", "ops", ".", "name_scope", "(", "'interp_fit_rk'", ")", ":", "dt", "=", "math_ops", ".", "cast", "(", "dt", ",", "y0", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/integrate/python/ops/odes.py#L174-L181
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/email/quoprimime.py
python
header_encode
(header_bytes, charset='iso-8859-1')
return '=?%s?q?%s?=' % (charset, encoded)
Encode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use in the RFC 2046 header. It defaults to iso-8859-1.
Encode a single header line with quoted-printable (like) encoding.
[ "Encode", "a", "single", "header", "line", "with", "quoted", "-", "printable", "(", "like", ")", "encoding", "." ]
def header_encode(header_bytes, charset='iso-8859-1'): """Encode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use in the RFC 2046 header. It defaults to iso-8859-1. """ # Return empty headers as an empty string. if not header_bytes: return '' # Iterate over every byte, encoding if necessary. encoded = header_bytes.decode('latin1').translate(_QUOPRI_HEADER_MAP) # Now add the RFC chrome to each encoded chunk and glue the chunks # together. return '=?%s?q?%s?=' % (charset, encoded)
[ "def", "header_encode", "(", "header_bytes", ",", "charset", "=", "'iso-8859-1'", ")", ":", "# Return empty headers as an empty string.", "if", "not", "header_bytes", ":", "return", "''", "# Iterate over every byte, encoding if necessary.", "encoded", "=", "header_bytes", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/quoprimime.py#L127-L145
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/imputil.py
python
ImportManager.install
(self, namespace=vars(__builtin__))
Install this ImportManager into the specified namespace.
Install this ImportManager into the specified namespace.
[ "Install", "this", "ImportManager", "into", "the", "specified", "namespace", "." ]
def install(self, namespace=vars(__builtin__)): "Install this ImportManager into the specified namespace." if isinstance(namespace, _ModuleType): namespace = vars(namespace) # Note: we have no notion of "chaining" # Record the previous import hook, then install our own. self.previous_importer = namespace['__import__'] self.namespace = namespace namespace['__import__'] = self._import_hook
[ "def", "install", "(", "self", ",", "namespace", "=", "vars", "(", "__builtin__", ")", ")", ":", "if", "isinstance", "(", "namespace", ",", "_ModuleType", ")", ":", "namespace", "=", "vars", "(", "namespace", ")", "# Note: we have no notion of \"chaining\"", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/imputil.py#L33-L44
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
InfoBar.GetHideEffect
(*args, **kwargs)
return _controls_.InfoBar_GetHideEffect(*args, **kwargs)
GetHideEffect(self) -> int
GetHideEffect(self) -> int
[ "GetHideEffect", "(", "self", ")", "-", ">", "int" ]
def GetHideEffect(*args, **kwargs): """GetHideEffect(self) -> int""" return _controls_.InfoBar_GetHideEffect(*args, **kwargs)
[ "def", "GetHideEffect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "InfoBar_GetHideEffect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L7785-L7787
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/utils.py
python
check_shape
(shape)
Check shape type and shape elements type before passing it to fill_constant
Check shape type and shape elements type before passing it to fill_constant
[ "Check", "shape", "type", "and", "shape", "elements", "type", "before", "passing", "it", "to", "fill_constant" ]
def check_shape(shape): """ Check shape type and shape elements type before passing it to fill_constant """ if isinstance(shape, Variable): check_dtype(shape.dtype, 'shape', ['int32', 'int64'], 'fill_constant') else: for ele in shape: if not isinstance(ele, Variable): if ele < 0: raise ValueError( "All elements in ``shape`` must be positive when it's a list or tuple" ) if not isinstance(ele, six.integer_types): raise TypeError( "All elements in ``shape`` must be integers when it's a list or tuple" )
[ "def", "check_shape", "(", "shape", ")", ":", "if", "isinstance", "(", "shape", ",", "Variable", ")", ":", "check_dtype", "(", "shape", ".", "dtype", ",", "'shape'", ",", "[", "'int32'", ",", "'int64'", "]", ",", "'fill_constant'", ")", "else", ":", "f...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/utils.py#L373-L389
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PGChoices.Item
(*args)
return _propgrid.PGChoices_Item(*args)
Item(self, int i) Item(self, int i)
Item(self, int i) Item(self, int i)
[ "Item", "(", "self", "int", "i", ")", "Item", "(", "self", "int", "i", ")" ]
def Item(*args): """ Item(self, int i) Item(self, int i) """ return _propgrid.PGChoices_Item(*args)
[ "def", "Item", "(", "*", "args", ")", ":", "return", "_propgrid", ".", "PGChoices_Item", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L308-L313
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pyedbglib/protocols/housekeepingprotocol.py
python
Jtagice3HousekeepingProtocol.start_session
(self)
Starts a session with the debugger (sign-on)
Starts a session with the debugger (sign-on)
[ "Starts", "a", "session", "with", "the", "debugger", "(", "sign", "-", "on", ")" ]
def start_session(self): """Starts a session with the debugger (sign-on)""" self.logger.debug("Housekeeping::start_session") response = self.jtagice3_command_response(bytearray([self.CMD_HOUSEKEEPING_START_SESSION, self.CMD_VERSION0])) self.check_response(response)
[ "def", "start_session", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Housekeeping::start_session\"", ")", "response", "=", "self", ".", "jtagice3_command_response", "(", "bytearray", "(", "[", "self", ".", "CMD_HOUSEKEEPING_START_SESSION", "...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/housekeepingprotocol.py#L79-L83
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/data/experimental/ops/enumerate_ops.py
python
enumerate_dataset
(start=0)
return _apply_fn
A transformation that enumerates the elements of a dataset. It is similar to python's `enumerate`. For example: ```python # NOTE: The following examples use `{ ... }` to represent the # contents of a dataset. a = { 1, 2, 3 } b = { (7, 8), (9, 10) } # The nested structure of the `datasets` argument determines the # structure of elements in the resulting dataset. a.apply(tf.data.experimental.enumerate_dataset(start=5)) => { (5, 1), (6, 2), (7, 3) } b.apply(tf.data.experimental.enumerate_dataset()) => { (0, (7, 8)), (1, (9, 10)) } ``` Args: start: A `tf.int64` scalar `tf.Tensor`, representing the start value for enumeration. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`.
A transformation that enumerates the elements of a dataset.
[ "A", "transformation", "that", "enumerates", "the", "elements", "of", "a", "dataset", "." ]
def enumerate_dataset(start=0): """A transformation that enumerates the elements of a dataset. It is similar to python's `enumerate`. For example: ```python # NOTE: The following examples use `{ ... }` to represent the # contents of a dataset. a = { 1, 2, 3 } b = { (7, 8), (9, 10) } # The nested structure of the `datasets` argument determines the # structure of elements in the resulting dataset. a.apply(tf.data.experimental.enumerate_dataset(start=5)) => { (5, 1), (6, 2), (7, 3) } b.apply(tf.data.experimental.enumerate_dataset()) => { (0, (7, 8)), (1, (9, 10)) } ``` Args: start: A `tf.int64` scalar `tf.Tensor`, representing the start value for enumeration. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`. """ def _apply_fn(dataset): return dataset.enumerate(start) return _apply_fn
[ "def", "enumerate_dataset", "(", "start", "=", "0", ")", ":", "def", "_apply_fn", "(", "dataset", ")", ":", "return", "dataset", ".", "enumerate", "(", "start", ")", "return", "_apply_fn" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/experimental/ops/enumerate_ops.py#L22-L54
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xpathParserContext.xpathFalseFunction
(self, nargs)
Implement the false() XPath function boolean false()
Implement the false() XPath function boolean false()
[ "Implement", "the", "false", "()", "XPath", "function", "boolean", "false", "()" ]
def xpathFalseFunction(self, nargs): """Implement the false() XPath function boolean false() """ libxml2mod.xmlXPathFalseFunction(self._o, nargs)
[ "def", "xpathFalseFunction", "(", "self", ",", "nargs", ")", ":", "libxml2mod", ".", "xmlXPathFalseFunction", "(", "self", ".", "_o", ",", "nargs", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L7514-L7516
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
utils/vim-lldb/python-vim-lldb/vim_panes.py
python
LocalsPane.format_variable
(self, var)
return ("(%s) %s" % (var.GetTypeName(), var.GetName()), "%s" % val)
Returns a Tuple of strings "(Type) Name", "Value" for SBValue var
Returns a Tuple of strings "(Type) Name", "Value" for SBValue var
[ "Returns", "a", "Tuple", "of", "strings", "(", "Type", ")", "Name", "Value", "for", "SBValue", "var" ]
def format_variable(self, var): """ Returns a Tuple of strings "(Type) Name", "Value" for SBValue var """ val = var.GetValue() if val is None: # If the value is too big, SBValue.GetValue() returns None; replace # with ... val = "..." return ("(%s) %s" % (var.GetTypeName(), var.GetName()), "%s" % val)
[ "def", "format_variable", "(", "self", ",", "var", ")", ":", "val", "=", "var", ".", "GetValue", "(", ")", "if", "val", "is", "None", ":", "# If the value is too big, SBValue.GetValue() returns None; replace", "# with ...", "val", "=", "\"...\"", "return", "(", ...
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/vim-lldb/python-vim-lldb/vim_panes.py#L486-L494
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/ndimage/measurements.py
python
find_objects
(input, max_label=0)
return _nd_image.find_objects(input, max_label)
Find objects in a labeled array. Parameters ---------- input : ndarray of ints Array containing objects defined by different labels. Labels with value 0 are ignored. max_label : int, optional Maximum label to be searched for in `input`. If max_label is not given, the positions of all objects are returned. Returns ------- object_slices : list of tuples A list of tuples, with each tuple containing N slices (with N the dimension of the input array). Slices correspond to the minimal parallelepiped that contains the object. If a number is missing, None is returned instead of a slice. See Also -------- label, center_of_mass Notes ----- This function is very useful for isolating a volume of interest inside a 3-D array, that cannot be "seen through". Examples -------- >>> from scipy import ndimage >>> a = np.zeros((6,6), dtype=int) >>> a[2:4, 2:4] = 1 >>> a[4, 4] = 1 >>> a[:2, :3] = 2 >>> a[0, 5] = 3 >>> a array([[2, 2, 2, 0, 0, 3], [2, 2, 2, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]]) >>> ndimage.find_objects(a) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None)), (slice(0, 1, None), slice(5, 6, None))] >>> ndimage.find_objects(a, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))] >>> ndimage.find_objects(a == 1, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), None] >>> loc = ndimage.find_objects(a)[0] >>> a[loc] array([[1, 1, 0], [1, 1, 0], [0, 0, 1]])
Find objects in a labeled array.
[ "Find", "objects", "in", "a", "labeled", "array", "." ]
def find_objects(input, max_label=0): """ Find objects in a labeled array. Parameters ---------- input : ndarray of ints Array containing objects defined by different labels. Labels with value 0 are ignored. max_label : int, optional Maximum label to be searched for in `input`. If max_label is not given, the positions of all objects are returned. Returns ------- object_slices : list of tuples A list of tuples, with each tuple containing N slices (with N the dimension of the input array). Slices correspond to the minimal parallelepiped that contains the object. If a number is missing, None is returned instead of a slice. See Also -------- label, center_of_mass Notes ----- This function is very useful for isolating a volume of interest inside a 3-D array, that cannot be "seen through". Examples -------- >>> from scipy import ndimage >>> a = np.zeros((6,6), dtype=int) >>> a[2:4, 2:4] = 1 >>> a[4, 4] = 1 >>> a[:2, :3] = 2 >>> a[0, 5] = 3 >>> a array([[2, 2, 2, 0, 0, 3], [2, 2, 2, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]]) >>> ndimage.find_objects(a) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None)), (slice(0, 1, None), slice(5, 6, None))] >>> ndimage.find_objects(a, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))] >>> ndimage.find_objects(a == 1, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), None] >>> loc = ndimage.find_objects(a)[0] >>> a[loc] array([[1, 1, 0], [1, 1, 0], [0, 0, 1]]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') if max_label < 1: max_label = input.max() return _nd_image.find_objects(input, max_label)
[ "def", "find_objects", "(", "input", ",", "max_label", "=", "0", ")", ":", "input", "=", "numpy", ".", "asarray", "(", "input", ")", "if", "numpy", ".", "iscomplexobj", "(", "input", ")", ":", "raise", "TypeError", "(", "'Complex type not supported'", ")",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/ndimage/measurements.py#L206-L272
eomahony/Numberjack
53fa9e994a36f881ffd320d8d04158097190aad8
Numberjack/XCSPOut.py
python
XCSPOutput.handle_relations
(self, expr)
Handles conflict and support relations adds relation and constraint to XCSP document
Handles conflict and support relations adds relation and constraint to XCSP document
[ "Handles", "conflict", "and", "support", "relations", "adds", "relation", "and", "constraint", "to", "XCSP", "document" ]
def handle_relations(self, expr): """ Handles conflict and support relations adds relation and constraint to XCSP document """ tuples = expr.parameters[0] semantics = expr.parameters[1] scope = expr.get_children() if semantics == "conflict": semantics = "conflicts" elif semantics == "support": semantics = "supports" relation = "\t<relation name=\"R%d\"" % self.__local_rel_idx relation += " arity=\"%d\"" % len(scope) relation += " nbTuples=\"%d\"" % len(tuples) relation += " semantics=\"%s\">\n\t\t" % semantics relation += "|".join([" ".join([str(t) for t in tuple]) for tuple in tuples]) relation += "\n\t</relation>\n" self.__relations.append(relation) constraint = "\n\t<constraint name=\"C%d\" arity=\"%d\" scope=\"%s\" reference=\"R%d\" />\n" % ( self.__local_con_idx, len(scope), " ".join(["V%d" % var.ident for var in scope]), self.__local_rel_idx ) self.__constraints.append(constraint) if self.__maxConstraintArity < len(scope): self.__maxConstraintArity = len(scope) self.__local_rel_idx += 1 self.__local_con_idx += 1
[ "def", "handle_relations", "(", "self", ",", "expr", ")", ":", "tuples", "=", "expr", ".", "parameters", "[", "0", "]", "semantics", "=", "expr", ".", "parameters", "[", "1", "]", "scope", "=", "expr", ".", "get_children", "(", ")", "if", "semantics", ...
https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/XCSPOut.py#L577-L611
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
cmake/developer_package/cpplint/cpplint.py
python
NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/cmake/developer_package/cpplint/cpplint.py#L2673-L2679
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/cpplint.py
python
FlagCxx11Features
(filename, clean_lines, linenum, error)
Flag those c++11 features that we only allow in certain places. 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.
Flag those c++11 features that we only allow in certain places.
[ "Flag", "those", "c", "++", "11", "features", "that", "we", "only", "allow", "in", "certain", "places", "." ]
def FlagCxx11Features(filename, clean_lines, linenum, error): """Flag those c++11 features that we only allow in certain places. 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] include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) # Flag unapproved C++ TR1 headers. if include and include.group(1).startswith('tr1/'): error(filename, linenum, 'build/c++tr1', 5, ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1)) # Flag unapproved C++11 headers. if include and include.group(1) in ('cfenv', 'condition_variable', 'fenv.h', 'future', 'mutex', 'thread', 'chrono', 'ratio', 'regex', 'system_error', ): error(filename, linenum, 'build/c++11', 5, ('<%s> is an unapproved C++11 header.') % include.group(1)) # The only place where we need to worry about C++11 keywords and library # features in preprocessor directives is in macro definitions. if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return # These are classes and free functions. The classes are always # mentioned as std::*, but we only catch the free functions if # they're not found by ADL. They're alphabetical by header. for top_name in ( # type_traits 'alignment_of', 'aligned_union', ): if Search(r'\bstd::%s\b' % top_name, line): error(filename, linenum, 'build/c++11', 5, ('std::%s is an unapproved C++11 class or function. Send c-style ' 'an example of where it would make your code more readable, and ' 'they may let you use it.') % top_name)
[ "def", "FlagCxx11Features", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "include", "=", "Match", "(", "r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]'", ",", "line", ")",...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L6475-L6524
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/BASIC/basparse.py
python
p_plist
(p)
plist : plist COMMA pitem | pitem
plist : plist COMMA pitem | pitem
[ "plist", ":", "plist", "COMMA", "pitem", "|", "pitem" ]
def p_plist(p): '''plist : plist COMMA pitem | pitem''' if len(p) > 3: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]]
[ "def", "p_plist", "(", "p", ")", ":", "if", "len", "(", "p", ")", ">", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "p", "[", "0", "]", ".", "append", "(", "p", "[", "3", "]", ")", "else", ":", "p", "[", "0", "]", "=", "["...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/BASIC/basparse.py#L373-L380
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
utils/indigo-service/service/v2/indigo_api.py
python
check
()
return result, 200, {"Content-Type": "application/json"}
Check chemical structure --- tags: - indigo parameters: - name: json_request in: body required: true schema: id: IndigoCheckRequest properties: struct: type: string required: true examples: C1=CC=CC=C1 types: type: array default: ["valence", "ambiguous_h", "query", "pseudoatoms", "radicals", "stereo", "overlapping_atoms", "overlapping_bonds", "3d", "sgroups", "v3000", "rgroups"] enum: - valence - ambiguous_h - query - pseudoatoms - radicals - stereo - overlapping_atoms - overlapping_bonds - 3d - sgroups - v3000 - rgroups example: struct: "[C+5]" types: ["valence", "ambiguous_h"] responses: 200: description: JSON with errors for given types if errors present schema: id: IndigoCheckResponse 400: description: 'A problem with supplied client data' schema: $ref: "#/definitions/ClientError" 500: description: 'A problem on server side' schema: $ref: "#/definitions/ServerError"
Check chemical structure --- tags: - indigo parameters: - name: json_request in: body required: true schema: id: IndigoCheckRequest properties: struct: type: string required: true examples: C1=CC=CC=C1 types: type: array default: ["valence", "ambiguous_h", "query", "pseudoatoms", "radicals", "stereo", "overlapping_atoms", "overlapping_bonds", "3d", "sgroups", "v3000", "rgroups"] enum: - valence - ambiguous_h - query - pseudoatoms - radicals - stereo - overlapping_atoms - overlapping_bonds - 3d - sgroups - v3000 - rgroups example: struct: "[C+5]" types: ["valence", "ambiguous_h"] responses: 200: description: JSON with errors for given types if errors present schema: id: IndigoCheckResponse 400: description: 'A problem with supplied client data' schema: $ref: "#/definitions/ClientError" 500: description: 'A problem on server side' schema: $ref: "#/definitions/ServerError"
[ "Check", "chemical", "structure", "---", "tags", ":", "-", "indigo", "parameters", ":", "-", "name", ":", "json_request", "in", ":", "body", "required", ":", "true", "schema", ":", "id", ":", "IndigoCheckRequest", "properties", ":", "struct", ":", "type", ...
def check(): """ Check chemical structure --- tags: - indigo parameters: - name: json_request in: body required: true schema: id: IndigoCheckRequest properties: struct: type: string required: true examples: C1=CC=CC=C1 types: type: array default: ["valence", "ambiguous_h", "query", "pseudoatoms", "radicals", "stereo", "overlapping_atoms", "overlapping_bonds", "3d", "sgroups", "v3000", "rgroups"] enum: - valence - ambiguous_h - query - pseudoatoms - radicals - stereo - overlapping_atoms - overlapping_bonds - 3d - sgroups - v3000 - rgroups example: struct: "[C+5]" types: ["valence", "ambiguous_h"] responses: 200: description: JSON with errors for given types if errors present schema: id: IndigoCheckResponse 400: description: 'A problem with supplied client data' schema: $ref: "#/definitions/ClientError" 500: description: 'A problem on server side' schema: $ref: "#/definitions/ServerError" """ data = IndigoCheckSchema().load(get_request_data(request)) try: indigo = indigo_init(data["options"]) except Exception as e: raise HttpException( "Problem with Indigo initialization: {0}".format(e), 501 ) LOG_DATA( "[REQUEST] /check", data["types"], data["struct"], data["options"] ) result = indigo.check(data["struct"], json.dumps(data["types"])) return result, 200, {"Content-Type": "application/json"}
[ "def", "check", "(", ")", ":", "data", "=", "IndigoCheckSchema", "(", ")", ".", "load", "(", "get_request_data", "(", "request", ")", ")", "try", ":", "indigo", "=", "indigo_init", "(", "data", "[", "\"options\"", "]", ")", "except", "Exception", "as", ...
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/utils/indigo-service/service/v2/indigo_api.py#L1091-L1152