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
GeometryCollective/boundary-first-flattening
8250e5a0e85980ec50b5e8aa8f49dd6519f915cd
deps/nanogui/docs/exhale.py
python
ExhaleRoot.sortInternals
(self)
Sort all internal lists (``class_like``, ``namespaces``, ``variables``, etc) mostly how doxygen would, alphabetical but also hierarchical (e.g. structs appear before classes in listings). Some internal lists are just sorted, and some are deep sorted (:func:`exhale.ExhaleRoot.deepSortList`).
Sort all internal lists (``class_like``, ``namespaces``, ``variables``, etc) mostly how doxygen would, alphabetical but also hierarchical (e.g. structs appear before classes in listings). Some internal lists are just sorted, and some are deep sorted (:func:`exhale.ExhaleRoot.deepSortList`).
[ "Sort", "all", "internal", "lists", "(", "class_like", "namespaces", "variables", "etc", ")", "mostly", "how", "doxygen", "would", "alphabetical", "but", "also", "hierarchical", "(", "e", ".", "g", ".", "structs", "appear", "before", "classes", "in", "listings...
def sortInternals(self): ''' Sort all internal lists (``class_like``, ``namespaces``, ``variables``, etc) mostly how doxygen would, alphabetical but also hierarchical (e.g. structs appear before classes in listings). Some internal lists are just sorted, and some are deep sorted (:func:`exhale.ExhaleRoot.deepSortList`). ''' # some of the lists only need to be sorted, some of them need to be sorted and # have each node sort its children # leaf-like lists: no child sort self.defines.sort() self.enums.sort() self.enum_values.sort() self.functions.sort() self.groups.sort() self.typedefs.sort() self.variables.sort() # hierarchical lists: sort children self.deepSortList(self.class_like) self.deepSortList(self.namespaces) self.deepSortList(self.unions) self.deepSortList(self.files) self.deepSortList(self.dirs)
[ "def", "sortInternals", "(", "self", ")", ":", "# some of the lists only need to be sorted, some of them need to be sorted and", "# have each node sort its children", "# leaf-like lists: no child sort", "self", ".", "defines", ".", "sort", "(", ")", "self", ".", "enums", ".", ...
https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/docs/exhale.py#L1954-L1977
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py
python
_Tokenizer.ConsumeFloat
(self)
return result
Consumes an floating point number. Returns: The number parsed. Raises: ParseError: If a floating point number couldn't be consumed.
Consumes an floating point number.
[ "Consumes", "an", "floating", "point", "number", "." ]
def ConsumeFloat(self): """Consumes an floating point number. Returns: The number parsed. Raises: ParseError: If a floating point number couldn't be consumed. """ try: result = ParseFloat(self.token) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result
[ "def", "ConsumeFloat", "(", "self", ")", ":", "try", ":", "result", "=", "ParseFloat", "(", "self", ".", "token", ")", "except", "ValueError", ",", "e", ":", "raise", "self", ".", "_ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken...
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py#L459-L473
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py
python
Graph._topo_sort
(self, forward=True)
return (valid, topo_list)
Topological sort. Returns a list of nodes where the successors (based on outgoing and incoming edges selected by the forward parameter) of any given node appear in the sequence after that node.
Topological sort.
[ "Topological", "sort", "." ]
def _topo_sort(self, forward=True): """ Topological sort. Returns a list of nodes where the successors (based on outgoing and incoming edges selected by the forward parameter) of any given node appear in the sequence after that node. """ topo_list = [] queue = deque() indeg = {} # select the operation that will be performed if forward: get_edges = self.out_edges get_degree = self.inc_degree get_next = self.tail else: get_edges = self.inc_edges get_degree = self.out_degree get_next = self.head for node in self.node_list(): degree = get_degree(node) if degree: indeg[node] = degree else: queue.append(node) while queue: curr_node = queue.popleft() topo_list.append(curr_node) for edge in get_edges(curr_node): tail_id = get_next(edge) if tail_id in indeg: indeg[tail_id] -= 1 if indeg[tail_id] == 0: queue.append(tail_id) if len(topo_list) == len(self.node_list()): valid = True else: # the graph has cycles, invalid topological sort valid = False return (valid, topo_list)
[ "def", "_topo_sort", "(", "self", ",", "forward", "=", "True", ")", ":", "topo_list", "=", "[", "]", "queue", "=", "deque", "(", ")", "indeg", "=", "{", "}", "# select the operation that will be performed", "if", "forward", ":", "get_edges", "=", "self", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py#L383-L428
tensorflow/io
92b44e180674a8af0e12e405530f7343e3e693e4
tensorflow_io/python/ops/bigtable/bigtable_row_range.py
python
closed_range
(start: str, end: str)
return RowRange(core_ops.bigtable_row_range(start, False, end, False))
Create a row range inclusive at both the start and the end. Args: start (str): The start of the row range (inclusive). end (str): The end of the row range (inclusive). Returns: RowRange: The row range between the `start` and `end`.
Create a row range inclusive at both the start and the end.
[ "Create", "a", "row", "range", "inclusive", "at", "both", "the", "start", "and", "the", "end", "." ]
def closed_range(start: str, end: str) -> RowRange: """Create a row range inclusive at both the start and the end. Args: start (str): The start of the row range (inclusive). end (str): The end of the row range (inclusive). Returns: RowRange: The row range between the `start` and `end`. """ return RowRange(core_ops.bigtable_row_range(start, False, end, False))
[ "def", "closed_range", "(", "start", ":", "str", ",", "end", ":", "str", ")", "->", "RowRange", ":", "return", "RowRange", "(", "core_ops", ".", "bigtable_row_range", "(", "start", ",", "False", ",", "end", ",", "False", ")", ")" ]
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/ops/bigtable/bigtable_row_range.py#L114-L123
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/parsing_ops.py
python
parse_example
(serialized, features, name=None, example_names=None)
return _parse_example_raw( serialized, example_names, sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults, dense_shapes, name)
Parses `Example` protos into a `dict` of tensors. Parses a number of serialized [`Example`] (https://www.tensorflow.org/code/tensorflow/core/example/example.proto) protos given in `serialized`. `example_names` may contain descriptive names for the corresponding serialized protos. These may be useful for debugging purposes, but they have no effect on the output. If not `None`, `example_names` must be the same length as `serialized`. This op parses serialized examples into a dictionary mapping keys to `Tensor` and `SparseTensor` objects. `features` is a dict from keys to `VarLenFeature` and `FixedLenFeature` objects. Each `VarLenFeature` is mapped to a `SparseTensor`, and each `FixedLenFeature` is mapped to a `Tensor`. Each `VarLenFeature` maps to a `SparseTensor` of the specified type representing a ragged matrix. Its indices are `[batch, index]` where `batch` is the batch entry the value is from in `serialized`, and `index` is the value's index in the list of values associated with that feature and example. Each `FixedLenFeature` `df` maps to a `Tensor` of the specified type (or `tf.float32` if not specified) and shape `(serialized.size(),) + df.shape`. `FixedLenFeature` entries with a `default_value` are optional. With no default value, we will fail if that `Feature` is missing from any example in `serialized`. Examples: For example, if one expects a `tf.float32` sparse feature `ft` and three serialized `Example`s are provided: ``` serialized = [ features { feature { key: "ft" value { float_list { value: [1.0, 2.0] } } } }, features { feature []}, features { feature { key: "ft" value { float_list { value: [3.0] } } } ] ``` then the output will look like: ``` {"ft": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]], values=[1.0, 2.0, 3.0], shape=(3, 2)) } ``` Given two `Example` input protos in `serialized`: ``` [ features { feature { key: "kw" value { bytes_list { value: [ "knit", "big" ] } } } feature { key: "gps" value { float_list { value: [] } } } }, features { feature { key: "kw" value { bytes_list { value: [ "emmy" ] } } } feature { key: "dank" value { int64_list { value: [ 42 ] } } } feature { key: "gps" value { } } } ] ``` And arguments ``` example_names: ["input0", "input1"], features: { "kw": VarLenFeature(tf.string), "dank": VarLenFeature(tf.int64), "gps": VarLenFeature(tf.float32), } ``` Then the output is a dictionary: ```python { "kw": SparseTensor( indices=[[0, 0], [0, 1], [1, 0]], values=["knit", "big", "emmy"] shape=[2, 2]), "dank": SparseTensor( indices=[[1, 0]], values=[42], shape=[2, 1]), "gps": SparseTensor( indices=[], values=[], shape=[2, 0]), } ``` For dense results in two serialized `Example`s: ``` [ features { feature { key: "age" value { int64_list { value: [ 0 ] } } } feature { key: "gender" value { bytes_list { value: [ "f" ] } } } }, features { feature { key: "age" value { int64_list { value: [] } } } feature { key: "gender" value { bytes_list { value: [ "f" ] } } } } ] ``` We can use arguments: ``` example_names: ["input0", "input1"], features: { "age": FixedLenFeature([], dtype=tf.int64, default_value=-1), "gender": FixedLenFeature([], dtype=tf.string), } ``` And the expected output is: ```python { "age": [[0], [-1]], "gender": [["f"], ["f"]], } ``` Args: serialized: A vector (1-D Tensor) of strings, a batch of binary serialized `Example` protos. features: A `dict` mapping feature keys to `FixedLenFeature` or `VarLenFeature` values. name: A name for this operation (optional). example_names: A vector (1-D Tensor) of strings (optional), the names of the serialized protos in the batch. Returns: A `dict` mapping feature keys to `Tensor` and `SparseTensor` values. Raises: ValueError: if any feature is invalid.
Parses `Example` protos into a `dict` of tensors.
[ "Parses", "Example", "protos", "into", "a", "dict", "of", "tensors", "." ]
def parse_example(serialized, features, name=None, example_names=None): # pylint: disable=line-too-long """Parses `Example` protos into a `dict` of tensors. Parses a number of serialized [`Example`] (https://www.tensorflow.org/code/tensorflow/core/example/example.proto) protos given in `serialized`. `example_names` may contain descriptive names for the corresponding serialized protos. These may be useful for debugging purposes, but they have no effect on the output. If not `None`, `example_names` must be the same length as `serialized`. This op parses serialized examples into a dictionary mapping keys to `Tensor` and `SparseTensor` objects. `features` is a dict from keys to `VarLenFeature` and `FixedLenFeature` objects. Each `VarLenFeature` is mapped to a `SparseTensor`, and each `FixedLenFeature` is mapped to a `Tensor`. Each `VarLenFeature` maps to a `SparseTensor` of the specified type representing a ragged matrix. Its indices are `[batch, index]` where `batch` is the batch entry the value is from in `serialized`, and `index` is the value's index in the list of values associated with that feature and example. Each `FixedLenFeature` `df` maps to a `Tensor` of the specified type (or `tf.float32` if not specified) and shape `(serialized.size(),) + df.shape`. `FixedLenFeature` entries with a `default_value` are optional. With no default value, we will fail if that `Feature` is missing from any example in `serialized`. Examples: For example, if one expects a `tf.float32` sparse feature `ft` and three serialized `Example`s are provided: ``` serialized = [ features { feature { key: "ft" value { float_list { value: [1.0, 2.0] } } } }, features { feature []}, features { feature { key: "ft" value { float_list { value: [3.0] } } } ] ``` then the output will look like: ``` {"ft": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]], values=[1.0, 2.0, 3.0], shape=(3, 2)) } ``` Given two `Example` input protos in `serialized`: ``` [ features { feature { key: "kw" value { bytes_list { value: [ "knit", "big" ] } } } feature { key: "gps" value { float_list { value: [] } } } }, features { feature { key: "kw" value { bytes_list { value: [ "emmy" ] } } } feature { key: "dank" value { int64_list { value: [ 42 ] } } } feature { key: "gps" value { } } } ] ``` And arguments ``` example_names: ["input0", "input1"], features: { "kw": VarLenFeature(tf.string), "dank": VarLenFeature(tf.int64), "gps": VarLenFeature(tf.float32), } ``` Then the output is a dictionary: ```python { "kw": SparseTensor( indices=[[0, 0], [0, 1], [1, 0]], values=["knit", "big", "emmy"] shape=[2, 2]), "dank": SparseTensor( indices=[[1, 0]], values=[42], shape=[2, 1]), "gps": SparseTensor( indices=[], values=[], shape=[2, 0]), } ``` For dense results in two serialized `Example`s: ``` [ features { feature { key: "age" value { int64_list { value: [ 0 ] } } } feature { key: "gender" value { bytes_list { value: [ "f" ] } } } }, features { feature { key: "age" value { int64_list { value: [] } } } feature { key: "gender" value { bytes_list { value: [ "f" ] } } } } ] ``` We can use arguments: ``` example_names: ["input0", "input1"], features: { "age": FixedLenFeature([], dtype=tf.int64, default_value=-1), "gender": FixedLenFeature([], dtype=tf.string), } ``` And the expected output is: ```python { "age": [[0], [-1]], "gender": [["f"], ["f"]], } ``` Args: serialized: A vector (1-D Tensor) of strings, a batch of binary serialized `Example` protos. features: A `dict` mapping feature keys to `FixedLenFeature` or `VarLenFeature` values. name: A name for this operation (optional). example_names: A vector (1-D Tensor) of strings (optional), the names of the serialized protos in the batch. Returns: A `dict` mapping feature keys to `Tensor` and `SparseTensor` values. Raises: ValueError: if any feature is invalid. """ if not features: raise ValueError("Missing: features was %s." % features) (sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults, dense_shapes) = _features_to_raw_params( features, [VarLenFeature, FixedLenFeature]) return _parse_example_raw( serialized, example_names, sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults, dense_shapes, name)
[ "def", "parse_example", "(", "serialized", ",", "features", ",", "name", "=", "None", ",", "example_names", "=", "None", ")", ":", "# pylint: disable=line-too-long", "if", "not", "features", ":", "raise", "ValueError", "(", "\"Missing: features was %s.\"", "%", "f...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/parsing_ops.py#L152-L307
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiToolBarItem.GetWindow
(*args, **kwargs)
return _aui.AuiToolBarItem_GetWindow(*args, **kwargs)
GetWindow(self) -> Window
GetWindow(self) -> Window
[ "GetWindow", "(", "self", ")", "-", ">", "Window" ]
def GetWindow(*args, **kwargs): """GetWindow(self) -> Window""" return _aui.AuiToolBarItem_GetWindow(*args, **kwargs)
[ "def", "GetWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBarItem_GetWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1733-L1735
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/PharLapCommon.py
python
getPharLapPath
()
Reads the registry to find the installed path of the Phar Lap ETS development kit. Raises UserError if no installed version of Phar Lap can be found.
Reads the registry to find the installed path of the Phar Lap ETS development kit.
[ "Reads", "the", "registry", "to", "find", "the", "installed", "path", "of", "the", "Phar", "Lap", "ETS", "development", "kit", "." ]
def getPharLapPath(): """Reads the registry to find the installed path of the Phar Lap ETS development kit. Raises UserError if no installed version of Phar Lap can be found.""" if not SCons.Util.can_read_reg: raise SCons.Errors.InternalError("No Windows registry module was found") try: k=SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Pharlap\\ETS') val, type = SCons.Util.RegQueryValueEx(k, 'BaseDir') # The following is a hack...there is (not surprisingly) # an odd issue in the Phar Lap plug in that inserts # a bunch of junk data after the phar lap path in the # registry. We must trim it. idx=val.find('\0') if idx >= 0: val = val[:idx] return os.path.normpath(val) except SCons.Util.RegError: raise SCons.Errors.UserError("Cannot find Phar Lap ETS path in the registry. Is it installed properly?")
[ "def", "getPharLapPath", "(", ")", ":", "if", "not", "SCons", ".", "Util", ".", "can_read_reg", ":", "raise", "SCons", ".", "Errors", ".", "InternalError", "(", "\"No Windows registry module was found\"", ")", "try", ":", "k", "=", "SCons", ".", "Util", ".",...
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/PharLapCommon.py#L40-L64
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.MergeFrom
(self, other)
Appends the contents of another repeated field of the same type to this one. We do not check the types of the individual fields.
Appends the contents of another repeated field of the same type to this one. We do not check the types of the individual fields.
[ "Appends", "the", "contents", "of", "another", "repeated", "field", "of", "the", "same", "type", "to", "this", "one", ".", "We", "do", "not", "check", "the", "types", "of", "the", "individual", "fields", "." ]
def MergeFrom(self, other): """Appends the contents of another repeated field of the same type to this one. We do not check the types of the individual fields. """ self._values.extend(other._values) self._message_listener.Modified()
[ "def", "MergeFrom", "(", "self", ",", "other", ")", ":", "self", ".", "_values", ".", "extend", "(", "other", ".", "_values", ")", "self", ".", "_message_listener", ".", "Modified", "(", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/containers.py#L280-L285
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py
python
TarInfo._block
(self, count)
return blocks * BLOCKSIZE
Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024.
Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024.
[ "Round", "up", "a", "byte", "count", "by", "BLOCKSIZE", "and", "return", "it", "e", ".", "g", ".", "_block", "(", "834", ")", "=", ">", "1024", "." ]
def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks, remainder = divmod(count, BLOCKSIZE) if remainder: blocks += 1 return blocks * BLOCKSIZE
[ "def", "_block", "(", "self", ",", "count", ")", ":", "blocks", ",", "remainder", "=", "divmod", "(", "count", ",", "BLOCKSIZE", ")", "if", "remainder", ":", "blocks", "+=", "1", "return", "blocks", "*", "BLOCKSIZE" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L1358-L1365
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGrid.SetMarginColour
(*args, **kwargs)
return _propgrid.PropertyGrid_SetMarginColour(*args, **kwargs)
SetMarginColour(self, Colour col)
SetMarginColour(self, Colour col)
[ "SetMarginColour", "(", "self", "Colour", "col", ")" ]
def SetMarginColour(*args, **kwargs): """SetMarginColour(self, Colour col)""" return _propgrid.PropertyGrid_SetMarginColour(*args, **kwargs)
[ "def", "SetMarginColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_SetMarginColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2264-L2266
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
api/ctpx/ctptd.py
python
CtpTd.onRspQryInstrumentMarginRate
(self, InstrumentMarginRateField, RspInfoField, requestId, final)
请求查询合约保证金率响应
请求查询合约保证金率响应
[ "请求查询合约保证金率响应" ]
def onRspQryInstrumentMarginRate(self, InstrumentMarginRateField, RspInfoField, requestId, final): """请求查询合约保证金率响应""" pass
[ "def", "onRspQryInstrumentMarginRate", "(", "self", ",", "InstrumentMarginRateField", ",", "RspInfoField", ",", "requestId", ",", "final", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L217-L219
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
python
HistGradientBoostingRegressor.predict
(self, X)
return self._raw_predict(X).ravel()
Predict values for X. Parameters ---------- X : array-like, shape (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape (n_samples,) The predicted values.
Predict values for X.
[ "Predict", "values", "for", "X", "." ]
def predict(self, X): """Predict values for X. Parameters ---------- X : array-like, shape (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape (n_samples,) The predicted values. """ # Return raw predictions after converting shape # (n_samples, 1) to (n_samples,) return self._raw_predict(X).ravel()
[ "def", "predict", "(", "self", ",", "X", ")", ":", "# Return raw predictions after converting shape", "# (n_samples, 1) to (n_samples,)", "return", "self", ".", "_raw_predict", "(", "X", ")", ".", "ravel", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py#L798-L813
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMT_SIG_SCHEME.fromTpm
(buf)
return buf.createObj(TPMT_SIG_SCHEME)
Returns new TPMT_SIG_SCHEME object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new TPMT_SIG_SCHEME object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "TPMT_SIG_SCHEME", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new TPMT_SIG_SCHEME object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(TPMT_SIG_SCHEME)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "TPMT_SIG_SCHEME", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6643-L6647
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/module/python_module.py
python
PythonModule._compute_output_shapes
(self)
The subclass should implement this method to compute the shape of outputs. This method can assume that the ``data_shapes`` and ``label_shapes`` are already initialized.
The subclass should implement this method to compute the shape of outputs. This method can assume that the ``data_shapes`` and ``label_shapes`` are already initialized.
[ "The", "subclass", "should", "implement", "this", "method", "to", "compute", "the", "shape", "of", "outputs", ".", "This", "method", "can", "assume", "that", "the", "data_shapes", "and", "label_shapes", "are", "already", "initialized", "." ]
def _compute_output_shapes(self): """The subclass should implement this method to compute the shape of outputs. This method can assume that the ``data_shapes`` and ``label_shapes`` are already initialized. """ raise NotImplementedError()
[ "def", "_compute_output_shapes", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/module/python_module.py#L212-L217
opengauss-mirror/openGauss-server
e383f1b77720a00ddbe4c0655bc85914d9b02a2b
src/gausskernel/dbmind/tools/ai_manager/module/index_advisor/uninstall.py
python
UnInstaller.clean_remote_module_dir
(self)
Clean install path before unpack.
Clean install path before unpack.
[ "Clean", "install", "path", "before", "unpack", "." ]
def clean_remote_module_dir(self): """ Clean install path before unpack. """ for node in self.install_nodes: ip = node.get(Constant.NODE_IP) uname = node.get(Constant.NODE_USER) pwd = node.get(Constant.NODE_PWD) _, output = CommonTools.retry_remote_clean_dir(self.module_path, ip, uname, pwd) g.logger.info('Result of clean module path on node:[%s], output:%s' % (ip, output))
[ "def", "clean_remote_module_dir", "(", "self", ")", ":", "for", "node", "in", "self", ".", "install_nodes", ":", "ip", "=", "node", ".", "get", "(", "Constant", ".", "NODE_IP", ")", "uname", "=", "node", ".", "get", "(", "Constant", ".", "NODE_USER", "...
https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/ai_manager/module/index_advisor/uninstall.py#L56-L65
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/models.py
python
Response.text
(self)
return content
Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property.
Content of the response, in unicode.
[ "Content", "of", "the", "response", "in", "unicode", "." ]
def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return str('') # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors='replace') return content
[ "def", "text", "(", "self", ")", ":", "# Try charset from content-type", "content", "=", "None", "encoding", "=", "self", ".", "encoding", "if", "not", "self", ".", "content", ":", "return", "str", "(", "''", ")", "# Fallback to auto-detected encoding.", "if", ...
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/requests/models.py#L839-L874
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pydoc.py
python
HTMLDoc.markup
(self, text, escape=None, funcs={}, classes={}, methods={})
return join(results, '')
Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.
Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.
[ "Mark", "up", "some", "plain", "text", "given", "a", "context", "of", "symbols", "to", "look", "for", ".", "Each", "context", "dictionary", "maps", "object", "names", "to", "anchor", "names", "." ]
def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?(\w+))') while True: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) elif selfdot: results.append('self.<strong>%s</strong>' % name) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return join(results, '')
[ "def", "markup", "(", "self", ",", "text", ",", "escape", "=", "None", ",", "funcs", "=", "{", "}", ",", "classes", "=", "{", "}", ",", "methods", "=", "{", "}", ")", ":", "escape", "=", "escape", "or", "self", ".", "escape", "results", "=", "[...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pydoc.py#L526-L560
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
qatools/qatoolspython/qatoolspython.py
python
_do_qatools
(subjects_dir, output_dir, subjects, shape=False, screenshots=False, fornix=False, outlier=False, outlier_table=None)
an internal function to run the qatools submodules
an internal function to run the qatools submodules
[ "an", "internal", "function", "to", "run", "the", "qatools", "submodules" ]
def _do_qatools(subjects_dir, output_dir, subjects, shape=False, screenshots=False, fornix=False, outlier=False, outlier_table=None): """ an internal function to run the qatools submodules """ # ------------------------------------------------------------------------------ # imports import os import csv import time from qatoolspython.checkSNR import checkSNR from qatoolspython.checkCCSize import checkCCSize from qatoolspython.checkTopology import checkTopology from qatoolspython.checkContrast import checkContrast from qatoolspython.checkRotation import checkRotation from qatoolspython.evaluateFornixSegmentation import evaluateFornixSegmentation from qatoolspython.createScreenshots import createScreenshots from qatoolspython.outlierDetection import outlierTable from qatoolspython.outlierDetection import outlierDetection # ------------------------------------------------------------------------------ # internal settings (might be turned into command-line arguments in the future) SNR_AMOUT_EROSION = 3 FORNIX_SCREENSHOT = True FORNIX_SHAPE = False FORNIX_N_EIGEN = 15 OUTLIER_N_MIN = 5 # -------------------------------------------------------------------------- # process # start the processing with a message print("") print("-----------------------------") # create dict for this subject metricsDict = dict() # loop through the specified subjects for subject in subjects: # print("Starting qatools-python for subject", subject, "at", time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(time.time()))) print("") # ---------------------------------------------------------------------- # compute core metrics # get WM and GM SNR for orig.mgz wm_snr_orig, gm_snr_orig = checkSNR(subjects_dir, subject, SNR_AMOUT_EROSION, ref_image="orig.mgz") # get WM and GM SNR for norm.mgz wm_snr_norm, gm_snr_norm = checkSNR(subjects_dir, subject, SNR_AMOUT_EROSION, ref_image="norm.mgz") # check CC size cc_size = checkCCSize(subjects_dir, subject) # check topology holes_lh, holes_rh, defects_lh, defects_rh, topo_lh, topo_rh = checkTopology(subjects_dir, subject) # check contrast con_snr_lh, con_snr_rh = checkContrast(subjects_dir, subject) # check rotation rot_tal_x, rot_tal_y, rot_tal_z = checkRotation(subjects_dir, subject) # store data metricsDict.update( { subject : { 'subject' : subject, 'wm_snr_orig': wm_snr_orig, 'gm_snr_orig' : gm_snr_orig, 'wm_snr_norm' : wm_snr_norm, 'gm_snr_norm' : gm_snr_norm, 'cc_size' : cc_size, 'holes_lh' : holes_lh, 'holes_rh' : holes_rh, 'defects_lh' : defects_lh, 'defects_rh' : defects_rh, 'topo_lh' : topo_lh, 'topo_rh' : topo_rh, 'con_snr_lh' : con_snr_lh, 'con_snr_rh' : con_snr_rh, 'rot_tal_x' : rot_tal_x, 'rot_tal_y' : rot_tal_y , 'rot_tal_z' : rot_tal_z }}) # print("") # ---------------------------------------------------------------------- # run optional modules: shape analysis if shape is True: # message print("-----------------------------") print("Running brainPrint analysis ...") print("") # compute brainprint (will also compute shapeDNA) from brainprintpython import pyBrainPrint from brainprintpython import pyPostProc # check / create subject-specific brainprint_outdir brainprint_outdir = os.path.join(output_dir,'brainprint',subject) if not os.path.isdir(brainprint_outdir): os.mkdir(brainprint_outdir) # set options class options: sdir = subjects_dir sid = subject outdir = brainprint_outdir evec = True skipcortex = True num = 15 bcond = 1 brainprint = os.path.join(brainprint_outdir, subject+'.brainprint.csv') class optionsPostProc: file = os.path.join(brainprint_outdir, subject+'.brainprint.csv') csvfiles = [ os.path.join(brainprint_outdir, subject+'.brainprint.csv') ] out = brainprint_outdir outcov = None vol = 1 lin = True asy = "euc" # run brainPrint structures, evmat = pyBrainPrint.compute_brainprint(options) # write EVs pyBrainPrint.write_ev(options, structures, evmat) # run postProc postProcDict = pyPostProc.compute_postproc(optionsPostProc) # get a subset of the brainprint results distDict = { subject : postProcDict[os.path.join(brainprint_outdir, subject+".brainprint.csv")]['dist'] } # store data metricsDict[subject].update(distDict[subject]) # ---------------------------------------------------------------------- # run optional modules: screenshots if screenshots is True: # message print("-----------------------------") print("Creating screenshots ...") print("") # check / create subject-specific screenshots_outdir screenshots_outdir = os.path.join(output_dir,'screenshots',subject) if not os.path.isdir(screenshots_outdir): os.mkdir(screenshots_outdir) outfile = os.path.join(screenshots_outdir,subject+'.png') # process createScreenshots(SUBJECT=subject, SUBJECTS_DIR=subjects_dir, OUTFILE=outfile, INTERACTIVE=False) # ---------------------------------------------------------------------- # run optional modules: fornix if fornix is True: # message print("-----------------------------") print("Checking fornix segmentation ...") print("") # check / create subject-specific fornix_outdir fornix_outdir = os.path.join(output_dir,'fornix',subject) if not os.path.isdir(fornix_outdir): os.mkdir(fornix_outdir) # process fornixShapeOutput = evaluateFornixSegmentation(SUBJECT=subject,SUBJECTS_DIR=subjects_dir,OUTPUT_DIR=fornix_outdir,CREATE_SCREENSHOT=FORNIX_SCREENSHOT,RUN_SHAPEDNA=FORNIX_SHAPE,N_EIGEN=FORNIX_N_EIGEN) # create a dictionary from fornix shape ouput fornixShapeDict = { subject : dict(zip(map("fornixShapeEV{:0>3}".format,range(FORNIX_N_EIGEN)), fornixShapeOutput)) } # store data if FORNIX_SHAPE: metricsDict[subject].update(fornixShapeDict[subject]) # message print("Finished subject", subject, "at", time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(time.time()))) print("") # -------------------------------------------------------------------------- # run optional modules: outlier detection if outlier is True: # message print("---------------------------------------") print("Running outlier detection module ...") print("") # determine outlier-table and get data if outlier_table is None: outlierDict = outlierTable() else: outlierDict = dict() with open(outlier_table, newline='') as csvfile: outlierCsv = csv.DictReader(csvfile, delimiter=',') for row in outlierCsv: outlierDict.update({row['label']: {'lower': float(row['lower']), 'upper': float(row['upper'])}}) # process outlier_outdir = os.path.join(output_dir, 'outliers') n_outlier_sample_nonpar, n_outlier_sample_param, n_outlier_norms = outlierDetection(subjects, subjects_dir, outlier_outdir, outlierDict, min_no_subjects=OUTLIER_N_MIN) # create a dictionary from outlier module ouput outlierDict = dict() for subject in subjects: outlierDict.update({subject : { 'n_outlier_sample_nonpar' : n_outlier_sample_nonpar[subject], 'n_outlier_sample_param': n_outlier_sample_param[subject], 'n_outlier_norms': n_outlier_norms[subject] } }) # store data for subject in subjects: metricsDict[subject].update(outlierDict[subject]) # message print("Done") print("") # -------------------------------------------------------------------------- # generate output # we pre-specify the fieldnames because we want to have this particular order metricsFieldnames = ['subject','wm_snr_orig','gm_snr_orig','wm_snr_norm','gm_snr_norm','cc_size','holes_lh','holes_rh','defects_lh','defects_rh','topo_lh','topo_rh','con_snr_lh','con_snr_rh','rot_tal_x', 'rot_tal_y', 'rot_tal_z'] if shape is True: metricsFieldnames.extend(distDict[subject].keys()) if fornix is True and FORNIX_SHAPE is True: metricsFieldnames.extend(sorted(fornixShapeDict[subject].keys())) if outlier is True: metricsFieldnames.extend(sorted(outlierDict[subject].keys())) # determine output file names path_data_file = os.path.join(output_dir,'qatools-results.csv') # write csv with open(path_data_file, 'w') as datafile: csvwriter = csv.DictWriter(datafile, fieldnames=metricsFieldnames, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL) csvwriter.writeheader() for subject in sorted(list(metricsDict.keys())): csvwriter.writerow(metricsDict[subject])
[ "def", "_do_qatools", "(", "subjects_dir", ",", "output_dir", ",", "subjects", ",", "shape", "=", "False", ",", "screenshots", "=", "False", ",", "fornix", "=", "False", ",", "outlier", "=", "False", ",", "outlier_table", "=", "None", ")", ":", "# --------...
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/qatools/qatoolspython/qatoolspython.py#L610-L861
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
EmptyImage
(*args, **kwargs)
return val
EmptyImage(int width=0, int height=0, bool clear=True) -> Image Construct an empty image of a given size, optionally setting all pixels to black.
EmptyImage(int width=0, int height=0, bool clear=True) -> Image
[ "EmptyImage", "(", "int", "width", "=", "0", "int", "height", "=", "0", "bool", "clear", "=", "True", ")", "-", ">", "Image" ]
def EmptyImage(*args, **kwargs): """ EmptyImage(int width=0, int height=0, bool clear=True) -> Image Construct an empty image of a given size, optionally setting all pixels to black. """ val = _core_.new_EmptyImage(*args, **kwargs) return val
[ "def", "EmptyImage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_core_", ".", "new_EmptyImage", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L3734-L3742
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/email/_header_value_parser.py
python
_refold_parse_tree
(parse_tree, *, policy)
return policy.linesep.join(lines) + policy.linesep
Return string of contents of parse_tree folded according to RFC rules.
Return string of contents of parse_tree folded according to RFC rules.
[ "Return", "string", "of", "contents", "of", "parse_tree", "folded", "according", "to", "RFC", "rules", "." ]
def _refold_parse_tree(parse_tree, *, policy): """Return string of contents of parse_tree folded according to RFC rules. """ # max_line_length 0/None means no limit, ie: infinitely long. maxlen = policy.max_line_length or sys.maxsize encoding = 'utf-8' if policy.utf8 else 'us-ascii' lines = [''] last_ew = None wrap_as_ew_blocked = 0 want_encoding = False end_ew_not_allowed = Terminal('', 'wrap_as_ew_blocked') parts = list(parse_tree) while parts: part = parts.pop(0) if part is end_ew_not_allowed: wrap_as_ew_blocked -= 1 continue tstr = str(part) if part.token_type == 'ptext' and set(tstr) & SPECIALS: # Encode if tstr contains special characters. want_encoding = True try: tstr.encode(encoding) charset = encoding except UnicodeEncodeError: if any(isinstance(x, errors.UndecodableBytesDefect) for x in part.all_defects): charset = 'unknown-8bit' else: # If policy.utf8 is false this should really be taken from a # 'charset' property on the policy. charset = 'utf-8' want_encoding = True if part.token_type == 'mime-parameters': # Mime parameter folding (using RFC2231) is extra special. _fold_mime_parameters(part, lines, maxlen, encoding) continue if want_encoding and not wrap_as_ew_blocked: if not part.as_ew_allowed: want_encoding = False last_ew = None if part.syntactic_break: encoded_part = part.fold(policy=policy)[:-len(policy.linesep)] if policy.linesep not in encoded_part: # It fits on a single line if len(encoded_part) > maxlen - len(lines[-1]): # But not on this one, so start a new one. newline = _steal_trailing_WSP_if_exists(lines) # XXX what if encoded_part has no leading FWS? lines.append(newline) lines[-1] += encoded_part continue # Either this is not a major syntactic break, so we don't # want it on a line by itself even if it fits, or it # doesn't fit on a line by itself. Either way, fall through # to unpacking the subparts and wrapping them. if not hasattr(part, 'encode'): # It's not a Terminal, do each piece individually. parts = list(part) + parts else: # It's a terminal, wrap it as an encoded word, possibly # combining it with previously encoded words if allowed. last_ew = _fold_as_ew(tstr, lines, maxlen, last_ew, part.ew_combine_allowed, charset) want_encoding = False continue if len(tstr) <= maxlen - len(lines[-1]): lines[-1] += tstr continue # This part is too long to fit. The RFC wants us to break at # "major syntactic breaks", so unless we don't consider this # to be one, check if it will fit on the next line by itself. if (part.syntactic_break and len(tstr) + 1 <= maxlen): newline = _steal_trailing_WSP_if_exists(lines) if newline or part.startswith_fws(): lines.append(newline + tstr) last_ew = None continue if not hasattr(part, 'encode'): # It's not a terminal, try folding the subparts. newparts = list(part) if not part.as_ew_allowed: wrap_as_ew_blocked += 1 newparts.append(end_ew_not_allowed) parts = newparts + parts continue if part.as_ew_allowed and not wrap_as_ew_blocked: # It doesn't need CTE encoding, but encode it anyway so we can # wrap it. parts.insert(0, part) want_encoding = True continue # We can't figure out how to wrap, it, so give up. newline = _steal_trailing_WSP_if_exists(lines) if newline or part.startswith_fws(): lines.append(newline + tstr) else: # We can't fold it onto the next line either... lines[-1] += tstr return policy.linesep.join(lines) + policy.linesep
[ "def", "_refold_parse_tree", "(", "parse_tree", ",", "*", ",", "policy", ")", ":", "# max_line_length 0/None means no limit, ie: infinitely long.", "maxlen", "=", "policy", ".", "max_line_length", "or", "sys", ".", "maxsize", "encoding", "=", "'utf-8'", "if", "policy"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/_header_value_parser.py#L2762-L2863
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
transpose
(a, axes=None)
return _mx_nd_np.transpose(a, axes)
Permute the dimensions of an array. Parameters ---------- a : ndarray Input array. axes : list of ints, optional By default, reverse the dimensions, otherwise permute the axes according to the values given. Returns ------- p : ndarray a with its axes permuted. .. note:: This function differs from the original `numpy.transpose <https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html>`_ in the following way(s): * only ndarray is accepted as valid input, python iterables are not supported * the operator always returns an `ndarray` that does not share the memory with the input Examples -------- >>> x = np.arange(4).reshape((2,2)) >>> x array([[0., 1.], [2., 3.]]) >>> np.transpose(x) array([[0., 2.], [1., 3.]]) >>> x = np.ones((1, 2, 3)) >>> np.transpose(x, (1, 0, 2)).shape (2, 1, 3)
Permute the dimensions of an array.
[ "Permute", "the", "dimensions", "of", "an", "array", "." ]
def transpose(a, axes=None): """ Permute the dimensions of an array. Parameters ---------- a : ndarray Input array. axes : list of ints, optional By default, reverse the dimensions, otherwise permute the axes according to the values given. Returns ------- p : ndarray a with its axes permuted. .. note:: This function differs from the original `numpy.transpose <https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html>`_ in the following way(s): * only ndarray is accepted as valid input, python iterables are not supported * the operator always returns an `ndarray` that does not share the memory with the input Examples -------- >>> x = np.arange(4).reshape((2,2)) >>> x array([[0., 1.], [2., 3.]]) >>> np.transpose(x) array([[0., 2.], [1., 3.]]) >>> x = np.ones((1, 2, 3)) >>> np.transpose(x, (1, 0, 2)).shape (2, 1, 3) """ return _mx_nd_np.transpose(a, axes)
[ "def", "transpose", "(", "a", ",", "axes", "=", "None", ")", ":", "return", "_mx_nd_np", ".", "transpose", "(", "a", ",", "axes", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L6591-L6630
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/docs/utils.py
python
py_default
(type_name)
return { 'double': '123.0', 'long': '123', 'integer': '123', 'string': "'string'", 'blob': "b'bytes'", 'boolean': 'True|False', 'list': '[...]', 'map': '{...}', 'structure': '{...}', 'timestamp': 'datetime(2015, 1, 1)', }.get(type_name, '...')
Get the Python default value for a given model type. >>> py_default('string') '\'string\'' >>> py_default('list') '[...]' >>> py_default('unknown') '...' :rtype: string
Get the Python default value for a given model type.
[ "Get", "the", "Python", "default", "value", "for", "a", "given", "model", "type", "." ]
def py_default(type_name): """Get the Python default value for a given model type. >>> py_default('string') '\'string\'' >>> py_default('list') '[...]' >>> py_default('unknown') '...' :rtype: string """ return { 'double': '123.0', 'long': '123', 'integer': '123', 'string': "'string'", 'blob': "b'bytes'", 'boolean': 'True|False', 'list': '[...]', 'map': '{...}', 'structure': '{...}', 'timestamp': 'datetime(2015, 1, 1)', }.get(type_name, '...')
[ "def", "py_default", "(", "type_name", ")", ":", "return", "{", "'double'", ":", "'123.0'", ",", "'long'", ":", "'123'", ",", "'integer'", ":", "'123'", ",", "'string'", ":", "\"'string'\"", ",", "'blob'", ":", "\"b'bytes'\"", ",", "'boolean'", ":", "'True...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/docs/utils.py#L38-L61
lyxok1/Tiny-DSOD
94d15450699bea0dd3720e75e2d273e476174fba
scripts/cpp_lint.py
python
CheckPosixThreading
(filename, clean_lines, linenum, error)
Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). 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 for calls to thread-unsafe functions.
[ "Checks", "for", "calls", "to", "thread", "-", "unsafe", "functions", "." ]
def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). 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] for single_thread_function, multithread_safe_function in threading_list: ix = line.find(single_thread_function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_function + '...) instead of ' + single_thread_function + '...) for improved thread safety.')
[ "def", "CheckPosixThreading", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "single_thread_function", ",", "multithread_safe_function", "in", "threading_list", ":...
https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/scripts/cpp_lint.py#L1685-L1709
pybox2d/pybox2d
09643321fd363f0850087d1bde8af3f4afd82163
library/Box2D/examples/backends/pyglet_framework.py
python
PygletFramework.SimulationLoop
(self, dt)
The main simulation loop. Don't override this, override Step instead. And be sure to call super(classname, self).Step(settings) at the end of your Step function.
The main simulation loop. Don't override this, override Step instead. And be sure to call super(classname, self).Step(settings) at the end of your Step function.
[ "The", "main", "simulation", "loop", ".", "Don", "t", "override", "this", "override", "Step", "instead", ".", "And", "be", "sure", "to", "call", "super", "(", "classname", "self", ")", ".", "Step", "(", "settings", ")", "at", "the", "end", "of", "your"...
def SimulationLoop(self, dt): """ The main simulation loop. Don't override this, override Step instead. And be sure to call super(classname, self).Step(settings) at the end of your Step function. """ # Check the input and clear the screen self.CheckKeys() self.window.clear() # Update the keyboard status self.window.push_handlers(self.keys) # Create a new batch for drawing self.renderer.batch = pyglet.graphics.Batch() # Reset the text position self.textLine = 15 # Draw the title of the test at the top self.Print(self.name) # Step the physics self.Step(self.settings) self.renderer.batch.draw() self.window.invalid = True self.fps = pyglet.clock.get_fps()
[ "def", "SimulationLoop", "(", "self", ",", "dt", ")", ":", "# Check the input and clear the screen", "self", ".", "CheckKeys", "(", ")", "self", ".", "window", ".", "clear", "(", ")", "# Update the keyboard status", "self", ".", "window", ".", "push_handlers", "...
https://github.com/pybox2d/pybox2d/blob/09643321fd363f0850087d1bde8af3f4afd82163/library/Box2D/examples/backends/pyglet_framework.py#L569-L597
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
GraphicsPath.UnGetNativePath
(*args, **kwargs)
return _gdi_.GraphicsPath_UnGetNativePath(*args, **kwargs)
UnGetNativePath(self, void p) Gives back the native path returned by GetNativePath() because there might be some deallocations necessary (eg on cairo the native path returned by GetNativePath is newly allocated each time).
UnGetNativePath(self, void p)
[ "UnGetNativePath", "(", "self", "void", "p", ")" ]
def UnGetNativePath(*args, **kwargs): """ UnGetNativePath(self, void p) Gives back the native path returned by GetNativePath() because there might be some deallocations necessary (eg on cairo the native path returned by GetNativePath is newly allocated each time). """ return _gdi_.GraphicsPath_UnGetNativePath(*args, **kwargs)
[ "def", "UnGetNativePath", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "GraphicsPath_UnGetNativePath", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L6000-L6008
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/xgboost/python-package/xgboost/core.py
python
DMatrix.feature_names
(self)
return self._feature_names
Get feature names (column labels). Returns ------- feature_names : list or None
Get feature names (column labels).
[ "Get", "feature", "names", "(", "column", "labels", ")", "." ]
def feature_names(self): """Get feature names (column labels). Returns ------- feature_names : list or None """ return self._feature_names
[ "def", "feature_names", "(", "self", ")", ":", "return", "self", ".", "_feature_names" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/xgboost/python-package/xgboost/core.py#L486-L493
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/data_flow_ops.py
python
BaseStagingArea._check_put_dtypes
(self, vals, indices=None)
return tensors, indices
Validate and convert `vals` to a list of `Tensor`s. The `vals` argument can be a Tensor, a list or tuple of tensors, or a dictionary with tensor values. If `vals` is a list, then the appropriate indices associated with the values must be provided. If it is a dictionary, the staging area must have been constructed with a `names` attribute and the dictionary keys must match the staging area names. `indices` will be inferred from the dictionary keys. If the staging area was constructed with a `names` attribute, `vals` must be a dictionary. Checks that the dtype and shape of each value matches that of the staging area. Args: vals: A tensor, a list or tuple of tensors, or a dictionary.. Returns: A (tensors, indices) tuple where `tensors` is a list of `Tensor` objects and `indices` is a list of indices associed with the tensors. Raises: ValueError: If `vals` or `indices` is invalid.
Validate and convert `vals` to a list of `Tensor`s.
[ "Validate", "and", "convert", "vals", "to", "a", "list", "of", "Tensor", "s", "." ]
def _check_put_dtypes(self, vals, indices=None): """Validate and convert `vals` to a list of `Tensor`s. The `vals` argument can be a Tensor, a list or tuple of tensors, or a dictionary with tensor values. If `vals` is a list, then the appropriate indices associated with the values must be provided. If it is a dictionary, the staging area must have been constructed with a `names` attribute and the dictionary keys must match the staging area names. `indices` will be inferred from the dictionary keys. If the staging area was constructed with a `names` attribute, `vals` must be a dictionary. Checks that the dtype and shape of each value matches that of the staging area. Args: vals: A tensor, a list or tuple of tensors, or a dictionary.. Returns: A (tensors, indices) tuple where `tensors` is a list of `Tensor` objects and `indices` is a list of indices associed with the tensors. Raises: ValueError: If `vals` or `indices` is invalid. """ if isinstance(vals, dict): if not self._names: raise ValueError( "Staging areas must have names to enqueue a dictionary") if not set(vals.keys()).issubset(self._names): raise ValueError("Keys in dictionary to put do not match names " "of staging area. Dictionary: (%s), Queue: (%s)" % (sorted(vals.keys()), sorted(self._names))) # The order of values in `self._names` indicates the order in which the # tensors in the dictionary `vals` must be listed. vals, indices, n = zip(*[(vals[k], i, k) for i, k in enumerate(self._names) if k in vals]) else: if self._names: raise ValueError("You must enqueue a dictionary in a staging area " "with names") if indices is None: raise ValueError("Indices must be supplied when inserting a list " "of tensors") if len(indices) != len(vals): raise ValueError("Number of indices '%s' doesn't match " "number of values '%s'") if not isinstance(vals, (list, tuple)): vals = [vals] indices = [0] # Sanity check number of values if not len(vals) <= len(self._dtypes): raise ValueError("Unexpected number of inputs '%s' vs '%s'" % ( len(values), len(self._dtypes))) tensors = [] for val, i in zip(vals, indices): dtype, shape = self._dtypes[i], self._shapes[i] # Check dtype if not val.dtype == dtype: raise ValueError("Datatypes do not match. '%s' != '%s'" %( str(val.dtype), str(dtype))) # Check shape val.get_shape().assert_is_compatible_with(shape) tensors.append(ops.convert_to_tensor(val, dtype=dtype, name="component_%d" % i)) return tensors, indices
[ "def", "_check_put_dtypes", "(", "self", ",", "vals", ",", "indices", "=", "None", ")", ":", "if", "isinstance", "(", "vals", ",", "dict", ")", ":", "if", "not", "self", ".", "_names", ":", "raise", "ValueError", "(", "\"Staging areas must have names to enqu...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_ops.py#L1434-L1511
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/image_ops_impl.py
python
_is_png
(contents, name=None)
r"""Convenience function to check if the 'contents' encodes a PNG image. Args: contents: 0-D `string`. The encoded image bytes. name: A name for the operation (optional) Returns: A scalar boolean tensor indicating if 'contents' may be a PNG image. is_png is susceptible to false positives.
r"""Convenience function to check if the 'contents' encodes a PNG image.
[ "r", "Convenience", "function", "to", "check", "if", "the", "contents", "encodes", "a", "PNG", "image", "." ]
def _is_png(contents, name=None): r"""Convenience function to check if the 'contents' encodes a PNG image. Args: contents: 0-D `string`. The encoded image bytes. name: A name for the operation (optional) Returns: A scalar boolean tensor indicating if 'contents' may be a PNG image. is_png is susceptible to false positives. """ with ops.name_scope(name, 'is_png'): substr = string_ops.substr(contents, 0, 3) return math_ops.equal(substr, b'\211PN', name=name)
[ "def", "_is_png", "(", "contents", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'is_png'", ")", ":", "substr", "=", "string_ops", ".", "substr", "(", "contents", ",", "0", ",", "3", ")", "return", "math_ops...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/image_ops_impl.py#L3066-L3079
facebook/rocksdb
073ac547391870f464fae324a19a6bc6a70188dc
buckifier/util.py
python
run_shell_command
(shell_cmd, cmd_dir=None)
return p.returncode, stdout, stderr
Run a single shell command. @returns a tuple of shell command return code, stdout, stderr
Run a single shell command.
[ "Run", "a", "single", "shell", "command", "." ]
def run_shell_command(shell_cmd, cmd_dir=None): """ Run a single shell command. @returns a tuple of shell command return code, stdout, stderr """ if cmd_dir is not None and not os.path.exists(cmd_dir): run_shell_command("mkdir -p %s" % cmd_dir) start = time.time() print("\t>>> Running: " + shell_cmd) p = subprocess.Popen(shell_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cmd_dir) stdout, stderr = p.communicate() end = time.time() # Report time if we spent more than 5 minutes executing a command execution_time = end - start if execution_time > (60 * 5): mins = (execution_time / 60) secs = (execution_time % 60) print("\t>time spent: %d minutes %d seconds" % (mins, secs)) return p.returncode, stdout, stderr
[ "def", "run_shell_command", "(", "shell_cmd", ",", "cmd_dir", "=", "None", ")", ":", "if", "cmd_dir", "is", "not", "None", "and", "not", "os", ".", "path", ".", "exists", "(", "cmd_dir", ")", ":", "run_shell_command", "(", "\"mkdir -p %s\"", "%", "cmd_dir"...
https://github.com/facebook/rocksdb/blob/073ac547391870f464fae324a19a6bc6a70188dc/buckifier/util.py#L70-L95
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
third_party/cpplint.py
python
ExpectingFunctionArgs
(clean_lines, linenum)
return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or (linenum >= 2 and (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]) or Search(r'\bstd::m?function\s*\<\s*$', clean_lines.elided[linenum - 1]))))
Checks whether where function type arguments are expected. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if the line at 'linenum' is inside something that expects arguments of function types.
Checks whether where function type arguments are expected.
[ "Checks", "whether", "where", "function", "type", "arguments", "are", "expected", "." ]
def ExpectingFunctionArgs(clean_lines, linenum): """Checks whether where function type arguments are expected. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if the line at 'linenum' is inside something that expects arguments of function types. """ line = clean_lines.elided[linenum] return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or (linenum >= 2 and (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]) or Search(r'\bstd::m?function\s*\<\s*$', clean_lines.elided[linenum - 1]))))
[ "def", "ExpectingFunctionArgs", "(", "clean_lines", ",", "linenum", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "return", "(", "Match", "(", "r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('", ",", "line", ")", "or", "(", "linenum", ">=", ...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/third_party/cpplint.py#L5324-L5343
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/graph_util_impl.py
python
_is_variable_op
(op)
return op in _VARIABLE_OPS
Returns true if 'op' refers to a Variable node.
Returns true if 'op' refers to a Variable node.
[ "Returns", "true", "if", "op", "refers", "to", "a", "Variable", "node", "." ]
def _is_variable_op(op): """Returns true if 'op' refers to a Variable node.""" return op in _VARIABLE_OPS
[ "def", "_is_variable_op", "(", "op", ")", ":", "return", "op", "in", "_VARIABLE_OPS" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/graph_util_impl.py#L62-L64
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/summary/impl/reservoir.py
python
_ReservoirBucket.Items
(self)
Get all the items in the bucket.
Get all the items in the bucket.
[ "Get", "all", "the", "items", "in", "the", "bucket", "." ]
def Items(self): """Get all the items in the bucket.""" with self._mutex: return self.items
[ "def", "Items", "(", "self", ")", ":", "with", "self", ".", "_mutex", ":", "return", "self", ".", "items" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/summary/impl/reservoir.py#L231-L234
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmMarshaler.py
python
TpmBuffer.writeInt
(self, val)
Marshals the given 32-bit integer to this buffer. Args: val: 32-bit integer value to marshal
Marshals the given 32-bit integer to this buffer. Args: val: 32-bit integer value to marshal
[ "Marshals", "the", "given", "32", "-", "bit", "integer", "to", "this", "buffer", ".", "Args", ":", "val", ":", "32", "-", "bit", "integer", "value", "to", "marshal" ]
def writeInt(self, val): """ Marshals the given 32-bit integer to this buffer. Args: val: 32-bit integer value to marshal """ self.writeNum(val, 4)
[ "def", "writeInt", "(", "self", ",", "val", ")", ":", "self", ".", "writeNum", "(", "val", ",", "4", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmMarshaler.py#L172-L177
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/aoc/upgrade_attribute_subprocessor.py
python
AoCUpgradeAttributeSubprocessor.cost_stone_upgrade
(converter_group, line, value, operator, team=False)
return patches
Creates a patch for the stone cost modify effect (ID: 106). :param converter_group: Tech/Civ that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param line: Unit/Building line that has the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :param value: Value used for patching the member. :type value: MemberOperator :param operator: Operator used for patching the member. :type operator: MemberOperator :returns: The forward references for the generated patches. :rtype: list
Creates a patch for the stone cost modify effect (ID: 106).
[ "Creates", "a", "patch", "for", "the", "stone", "cost", "modify", "effect", "(", "ID", ":", "106", ")", "." ]
def cost_stone_upgrade(converter_group, line, value, operator, team=False): """ Creates a patch for the stone cost modify effect (ID: 106). :param converter_group: Tech/Civ that gets the patch. :type converter_group: ...dataformat.converter_object.ConverterObjectGroup :param line: Unit/Building line that has the ability. :type line: ...dataformat.converter_object.ConverterObjectGroup :param value: Value used for patching the member. :type value: MemberOperator :param operator: Operator used for patching the member. :type operator: MemberOperator :returns: The forward references for the generated patches. :rtype: list """ head_unit = line.get_head_unit() head_unit_id = line.get_head_unit_id() dataset = line.data patches = [] # Check if the unit line actually costs stone for resource_amount in head_unit["resource_cost"].get_value(): resource_id = resource_amount["type_id"].get_value() if resource_id == 2: break else: # Skip patch generation if no stone cost was found return patches obj_id = converter_group.get_id() if isinstance(converter_group, GenieTechEffectBundleGroup): tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) obj_name = tech_lookup_dict[obj_id][0] else: civ_lookup_dict = internal_name_lookups.get_civ_lookups(dataset.game_version) obj_name = civ_lookup_dict[obj_id][0] name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) game_entity_name = name_lookup_dict[head_unit_id][0] patch_target_ref = "%s.CreatableGameEntity.%sCost.StoneAmount" % (game_entity_name, game_entity_name) patch_target_forward_ref = ForwardRef(line, patch_target_ref) # Wrapper wrapper_name = f"Change{game_entity_name}StoneCostWrapper" wrapper_ref = f"{obj_name}.{wrapper_name}" wrapper_location = ForwardRef(converter_group, obj_name) wrapper_raw_api_object = RawAPIObject(wrapper_ref, wrapper_name, dataset.nyan_api_objects, wrapper_location) wrapper_raw_api_object.add_raw_parent("engine.util.patch.Patch") # Nyan patch nyan_patch_name = f"Change{game_entity_name}StoneCost" nyan_patch_ref = f"{obj_name}.{wrapper_name}.{nyan_patch_name}" nyan_patch_location = ForwardRef(converter_group, wrapper_ref) nyan_patch_raw_api_object = RawAPIObject(nyan_patch_ref, nyan_patch_name, dataset.nyan_api_objects, nyan_patch_location) nyan_patch_raw_api_object.add_raw_parent("engine.util.patch.NyanPatch") nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) nyan_patch_raw_api_object.add_raw_patch_member("amount", value, "engine.util.resource.ResourceAmount", operator) patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) wrapper_raw_api_object.add_raw_member("patch", patch_forward_ref, "engine.util.patch.Patch") if team: team_property = dataset.pregen_nyan_objects["util.patch.property.types.Team"].get_nyan_object() properties = { dataset.nyan_api_objects["engine.util.patch.property.type.Diplomatic"]: team_property } wrapper_raw_api_object.add_raw_member("properties", properties, "engine.util.patch.Patch") converter_group.add_raw_api_object(wrapper_raw_api_object) converter_group.add_raw_api_object(nyan_patch_raw_api_object) wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) patches.append(wrapper_forward_ref) return patches
[ "def", "cost_stone_upgrade", "(", "converter_group", ",", "line", ",", "value", ",", "operator", ",", "team", "=", "False", ")", ":", "head_unit", "=", "line", ".", "get_head_unit", "(", ")", "head_unit_id", "=", "line", ".", "get_head_unit_id", "(", ")", ...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/upgrade_attribute_subprocessor.py#L816-L911
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Memoize.py
python
CountDict.count
(self, *args, **kw)
Counts whether the computed key value is already present in the memoization dictionary (a hit) or not (a miss).
Counts whether the computed key value is already present in the memoization dictionary (a hit) or not (a miss).
[ "Counts", "whether", "the", "computed", "key", "value", "is", "already", "present", "in", "the", "memoization", "dictionary", "(", "a", "hit", ")", "or", "not", "(", "a", "miss", ")", "." ]
def count(self, *args, **kw): """ Counts whether the computed key value is already present in the memoization dictionary (a hit) or not (a miss). """ obj = args[0] try: memo_dict = obj._memo[self.method_name] except KeyError: self.miss = self.miss + 1 else: key = self.keymaker(*args, **kw) if key in memo_dict: self.hit = self.hit + 1 else: self.miss = self.miss + 1
[ "def", "count", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "obj", "=", "args", "[", "0", "]", "try", ":", "memo_dict", "=", "obj", ".", "_memo", "[", "self", ".", "method_name", "]", "except", "KeyError", ":", "self", ".", "m...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Memoize.py#L167-L181
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/llvm/utils/lit/lit/ShUtil.py
python
ShLexer.lex_one_token
(self)
return self.lex_arg(c)
lex_one_token - Lex a single 'sh' token.
lex_one_token - Lex a single 'sh' token.
[ "lex_one_token", "-", "Lex", "a", "single", "sh", "token", "." ]
def lex_one_token(self): """ lex_one_token - Lex a single 'sh' token. """ c = self.eat() if c == ';': return (c,) if c == '|': if self.maybe_eat('|'): return ('||',) return (c,) if c == '&': if self.maybe_eat('&'): return ('&&',) if self.maybe_eat('>'): return ('&>',) return (c,) if c == '>': if self.maybe_eat('&'): return ('>&',) if self.maybe_eat('>'): return ('>>',) return (c,) if c == '<': if self.maybe_eat('&'): return ('<&',) if self.maybe_eat('>'): return ('<<',) return (c,) return self.lex_arg(c)
[ "def", "lex_one_token", "(", "self", ")", ":", "c", "=", "self", ".", "eat", "(", ")", "if", "c", "==", "';'", ":", "return", "(", "c", ",", ")", "if", "c", "==", "'|'", ":", "if", "self", ".", "maybe_eat", "(", "'|'", ")", ":", "return", "("...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/llvm/utils/lit/lit/ShUtil.py#L130-L160
stepcode/stepcode
2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39
src/exp2python/python/SCL/Part21.py
python
Parser.p_parameter_empty_list
(self, p)
parameter : '(' ')
parameter : '(' ')
[ "parameter", ":", "(", ")" ]
def p_parameter_empty_list(self, p): """parameter : '(' ')'""" p[0] = []
[ "def", "p_parameter_empty_list", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "[", "]" ]
https://github.com/stepcode/stepcode/blob/2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39/src/exp2python/python/SCL/Part21.py#L382-L384
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py
python
Expecter.expect_loop
(self, timeout=-1)
Blocking expect
Blocking expect
[ "Blocking", "expect" ]
def expect_loop(self, timeout=-1): """Blocking expect""" spawn = self.spawn if timeout is not None: end_time = time.time() + timeout try: incoming = spawn.buffer spawn._buffer = spawn.buffer_type() spawn._before = spawn.buffer_type() while True: idx = self.new_data(incoming) # Keep reading until exception or return. if idx is not None: return idx # No match at this point if (timeout is not None) and (timeout < 0): return self.timeout() # Still have time left, so read more data incoming = spawn.read_nonblocking(spawn.maxread, timeout) if self.spawn.delayafterread is not None: time.sleep(self.spawn.delayafterread) if timeout is not None: timeout = end_time - time.time() except EOF as e: return self.eof(e) except TIMEOUT as e: return self.timeout(e) except: self.errored() raise
[ "def", "expect_loop", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "spawn", "=", "self", ".", "spawn", "if", "timeout", "is", "not", "None", ":", "end_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "try", ":", "incoming", "=", ...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py#L91-L122
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/mock_ocsp_responder/mock_ocsp_responder.py
python
OCSPResponder.__init__
(self, issuer_cert: str, responder_cert: str, responder_key: str, fault: str, next_update_seconds: int, response_delay_seconds: int, include_extraneous_status: bool, issuer_hash_algorithm: str)
Create a new OCSPResponder instance. :param issuer_cert: Path to the issuer certificate. :param responder_cert: Path to the certificate of the OCSP responder with the `OCSP Signing` extension. :param responder_key: Path to the private key belonging to the responder cert. :param validate_func: A function that - given a certificate serial - will return the appropriate :class:`CertificateStatus` and - depending on the status - a revocation datetime. :param cert_retrieve_func: A function that - given a certificate serial - will return the corresponding certificate as a string. :param next_update_seconds: The ``nextUpdate`` value that will be written into the response. Default: 9 hours. :param response_delay_seconds: Delays the HTTP response by this many seconds. :param include_extraneous_status: Include status of irrelevant certs in the response. :param issuer_hash_algorithm: Algorithm to use when hashing the issuer name & key.
Create a new OCSPResponder instance.
[ "Create", "a", "new", "OCSPResponder", "instance", "." ]
def __init__(self, issuer_cert: str, responder_cert: str, responder_key: str, fault: str, next_update_seconds: int, response_delay_seconds: int, include_extraneous_status: bool, issuer_hash_algorithm: str): """ Create a new OCSPResponder instance. :param issuer_cert: Path to the issuer certificate. :param responder_cert: Path to the certificate of the OCSP responder with the `OCSP Signing` extension. :param responder_key: Path to the private key belonging to the responder cert. :param validate_func: A function that - given a certificate serial - will return the appropriate :class:`CertificateStatus` and - depending on the status - a revocation datetime. :param cert_retrieve_func: A function that - given a certificate serial - will return the corresponding certificate as a string. :param next_update_seconds: The ``nextUpdate`` value that will be written into the response. Default: 9 hours. :param response_delay_seconds: Delays the HTTP response by this many seconds. :param include_extraneous_status: Include status of irrelevant certs in the response. :param issuer_hash_algorithm: Algorithm to use when hashing the issuer name & key. """ # Certs and keys self._issuer_cert = asymmetric.load_certificate(issuer_cert) self._responder_cert = asymmetric.load_certificate(responder_cert) self._responder_key = asymmetric.load_private_key(responder_key) # Next update self._next_update_seconds = next_update_seconds self._fault = fault self._response_delay_seconds = response_delay_seconds self._include_extraneous_status = include_extraneous_status self._issuer_hash_algorithm = issuer_hash_algorithm
[ "def", "__init__", "(", "self", ",", "issuer_cert", ":", "str", ",", "responder_cert", ":", "str", ",", "responder_key", ":", "str", ",", "fault", ":", "str", ",", "next_update_seconds", ":", "int", ",", "response_delay_seconds", ":", "int", ",", "include_ex...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/mock_ocsp_responder/mock_ocsp_responder.py#L471-L507
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
python/caffe/classifier.py
python
Classifier.predict
(self, inputs, oversample=True)
return predictions
Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes.
Predict classification probabilities of inputs.
[ "Predict", "classification", "probabilities", "of", "inputs", "." ]
def predict(self, inputs, oversample=True): """ Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes. """ # Scale to standardize input dimensions. input_ = np.zeros((len(inputs), self.image_dims[0], self.image_dims[1], inputs[0].shape[2]), dtype=np.float32) for ix, in_ in enumerate(inputs): input_[ix] = caffe.io.resize_image(in_, self.image_dims) if oversample: # Generate center, corner, and mirrored crops. input_ = caffe.io.oversample(input_, self.crop_dims) else: # Take center crop. center = np.array(self.image_dims) / 2.0 crop = np.tile(center, (1, 2))[0] + np.concatenate([ -self.crop_dims / 2.0, self.crop_dims / 2.0 ]) crop = crop.astype(int) input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :] # Classify caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]], dtype=np.float32) for ix, in_ in enumerate(input_): caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_) out = self.forward_all(**{self.inputs[0]: caffe_in}) predictions = out[self.outputs[0]] # For oversampling, average predictions across crops. if oversample: predictions = predictions.reshape((len(predictions) / 10, 10, -1)) predictions = predictions.mean(1) return predictions
[ "def", "predict", "(", "self", ",", "inputs", ",", "oversample", "=", "True", ")", ":", "# Scale to standardize input dimensions.", "input_", "=", "np", ".", "zeros", "(", "(", "len", "(", "inputs", ")", ",", "self", ".", "image_dims", "[", "0", "]", ","...
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/python/caffe/classifier.py#L47-L98
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/eager/python/metrics_impl.py
python
Metric.init_variables
(self)
return control_flow_ops.group([v.initializer for v in self._vars])
Return an op for initializing this Metric's variables. Only for graph execution. Should be called after variables are created in the first execution of __call__(). Returns: An op to run.
Return an op for initializing this Metric's variables.
[ "Return", "an", "op", "for", "initializing", "this", "Metric", "s", "variables", "." ]
def init_variables(self): """Return an op for initializing this Metric's variables. Only for graph execution. Should be called after variables are created in the first execution of __call__(). Returns: An op to run. """ assert context.in_graph_mode() return control_flow_ops.group([v.initializer for v in self._vars])
[ "def", "init_variables", "(", "self", ")", ":", "assert", "context", ".", "in_graph_mode", "(", ")", "return", "control_flow_ops", ".", "group", "(", "[", "v", ".", "initializer", "for", "v", "in", "self", ".", "_vars", "]", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/eager/python/metrics_impl.py#L111-L121
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_tstutils.py
python
aps07_f
(x, n)
return (1 + (1 - n)**2) * x - (1 - n * x)**2
r"""Upside down parabola with parametrizable height
r"""Upside down parabola with parametrizable height
[ "r", "Upside", "down", "parabola", "with", "parametrizable", "height" ]
def aps07_f(x, n): r"""Upside down parabola with parametrizable height""" return (1 + (1 - n)**2) * x - (1 - n * x)**2
[ "def", "aps07_f", "(", "x", ",", "n", ")", ":", "return", "(", "1", "+", "(", "1", "-", "n", ")", "**", "2", ")", "*", "x", "-", "(", "1", "-", "n", "*", "x", ")", "**", "2" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_tstutils.py#L242-L244
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/estimators/logistic_regressor.py
python
_get_model_fn_with_logistic_metrics
(model_fn)
return _model_fn
Returns a model_fn with additional logistic metrics. Args: model_fn: Model function with the signature: `(features, labels, mode) -> (predictions, loss, train_op)`. Expects the returned predictions to be probabilities in [0.0, 1.0]. Returns: model_fn that can be used with Estimator.
Returns a model_fn with additional logistic metrics.
[ "Returns", "a", "model_fn", "with", "additional", "logistic", "metrics", "." ]
def _get_model_fn_with_logistic_metrics(model_fn): """Returns a model_fn with additional logistic metrics. Args: model_fn: Model function with the signature: `(features, labels, mode) -> (predictions, loss, train_op)`. Expects the returned predictions to be probabilities in [0.0, 1.0]. Returns: model_fn that can be used with Estimator. """ def _model_fn(features, labels, mode, params): """Model function that appends logistic evaluation metrics.""" thresholds = params.get('thresholds') or [.5] predictions, loss, train_op = model_fn(features, labels, mode) if mode == model_fn_lib.ModeKeys.EVAL: eval_metric_ops = _make_logistic_eval_metric_ops( labels=labels, predictions=predictions, thresholds=thresholds) else: eval_metric_ops = None return model_fn_lib.ModelFnOps( mode=mode, predictions=predictions, loss=loss, train_op=train_op, eval_metric_ops=eval_metric_ops, output_alternatives={ 'head': (constants.ProblemType.LOGISTIC_REGRESSION, { 'predictions': predictions }) }) return _model_fn
[ "def", "_get_model_fn_with_logistic_metrics", "(", "model_fn", ")", ":", "def", "_model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "\"\"\"Model function that appends logistic evaluation metrics.\"\"\"", "thresholds", "=", "params", ".", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/estimators/logistic_regressor.py#L33-L69
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/graph_editor/select.py
python
get_within_boundary_ops
(ops, seed_ops, boundary_ops, inclusive=True, control_inputs=False, control_outputs=None, control_ios=None)
return [op for op in ops if op in res]
Return all the tf.Operation within the given boundary. Args: ops: an object convertible to a list of tf.Operation. those ops define the set in which to perform the operation (if a tf.Graph is given, it will be converted to the list of all its operations). seed_ops: the operations from which to start expanding. boundary_ops: the ops forming the boundary. inclusive: if True, the result will also include the boundary ops. control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of util.ControlOutputs or None. If not None, control outputs are enabled. control_ios: An instance of util.ControlOutputs or None. If not None, both control inputs and control outputs are enabled. This is equivalent to set control_inputs to True and control_outputs to the util.ControlOutputs instance. Returns: All the tf.Operation surrounding the given ops. Raises: TypeError: if ops or seed_ops cannot be converted to a list of tf.Operation. ValueError: if the boundary is intersecting with the seeds.
Return all the tf.Operation within the given boundary.
[ "Return", "all", "the", "tf", ".", "Operation", "within", "the", "given", "boundary", "." ]
def get_within_boundary_ops(ops, seed_ops, boundary_ops, inclusive=True, control_inputs=False, control_outputs=None, control_ios=None): """Return all the tf.Operation within the given boundary. Args: ops: an object convertible to a list of tf.Operation. those ops define the set in which to perform the operation (if a tf.Graph is given, it will be converted to the list of all its operations). seed_ops: the operations from which to start expanding. boundary_ops: the ops forming the boundary. inclusive: if True, the result will also include the boundary ops. control_inputs: A boolean indicating whether control inputs are enabled. control_outputs: An instance of util.ControlOutputs or None. If not None, control outputs are enabled. control_ios: An instance of util.ControlOutputs or None. If not None, both control inputs and control outputs are enabled. This is equivalent to set control_inputs to True and control_outputs to the util.ControlOutputs instance. Returns: All the tf.Operation surrounding the given ops. Raises: TypeError: if ops or seed_ops cannot be converted to a list of tf.Operation. ValueError: if the boundary is intersecting with the seeds. """ control_inputs, control_outputs = check_cios(control_inputs, control_outputs, control_ios) ops = util.make_list_of_op(ops) seed_ops = util.make_list_of_op(seed_ops, allow_graph=False) boundary_ops = set(util.make_list_of_op(boundary_ops)) res = set(seed_ops) if boundary_ops & res: raise ValueError("Boundary is intersecting with the seeds.") wave = set(seed_ops) while wave: new_wave = set() ops_io = get_ops_ios(wave, control_inputs, control_outputs) for op in ops_io: if op in res: continue if op in boundary_ops: if inclusive: res.add(op) else: new_wave.add(op) res.update(new_wave) wave = new_wave return [op for op in ops if op in res]
[ "def", "get_within_boundary_ops", "(", "ops", ",", "seed_ops", ",", "boundary_ops", ",", "inclusive", "=", "True", ",", "control_inputs", "=", "False", ",", "control_outputs", "=", "None", ",", "control_ios", "=", "None", ")", ":", "control_inputs", ",", "cont...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/select.py#L300-L351
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/GeoMechanicsApplication/python_scripts/geomechanics_analysis.py
python
GeoMechanicsAnalysis.RunSolutionLoop
(self)
This function executes the solution loop of the AnalysisStage It can be overridden by derived classes
This function executes the solution loop of the AnalysisStage It can be overridden by derived classes
[ "This", "function", "executes", "the", "solution", "loop", "of", "the", "AnalysisStage", "It", "can", "be", "overridden", "by", "derived", "classes" ]
def RunSolutionLoop(self): """This function executes the solution loop of the AnalysisStage It can be overridden by derived classes """ if self._GetSolver().settings["reset_displacements"].GetBool(): old_total_displacements = [node.GetSolutionStepValue(KratosGeo.TOTAL_DISPLACEMENT) for node in self._GetSolver().GetComputingModelPart().Nodes] while self.KeepAdvancingSolutionLoop(): if (self.delta_time > self.max_delta_time): self.delta_time = self.max_delta_time KratosMultiphysics.Logger.PrintInfo(self._GetSimulationName(), "reducing delta_time to max_delta_time: ", self.max_delta_time) t = self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.TIME] new_time = t + self.delta_time if (new_time > self.end_time): new_time = self.end_time self.delta_time = new_time - t self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.STEP] += 1 self._GetSolver().main_model_part.CloneTimeStep(new_time) KratosMultiphysics.Logger.PrintInfo(self._GetSimulationName(), "--------------------------------------", " ") converged = False number_cycle = 0 while (not converged and number_cycle < self.number_cycles): number_cycle +=1 KratosMultiphysics.Logger.PrintInfo(self._GetSimulationName(), "cycle: ", number_cycle) t = self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.TIME] new_time = t - self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.DELTA_TIME] + self.delta_time self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.TIME] = new_time self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.DELTA_TIME] = self.delta_time self.InitializeSolutionStep() self._GetSolver().Predict() converged = self._GetSolver().SolveSolutionStep() if (self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.NL_ITERATION_NUMBER] >= self.max_iterations or not converged): KratosMultiphysics.Logger.PrintInfo(self._GetSimulationName(), "Down-scaling with factor: ", self.reduction_factor) self.delta_time *= self.reduction_factor #converged = False # Reset displacements to the initial KratosMultiphysics.VariableUtils().UpdateCurrentPosition(self._GetSolver().GetComputingModelPart().Nodes, KratosMultiphysics.DISPLACEMENT,1) for node in self._GetSolver().GetComputingModelPart().Nodes: dold = node.GetSolutionStepValue(KratosMultiphysics.DISPLACEMENT,1) node.SetSolutionStepValue(KratosMultiphysics.DISPLACEMENT,0,dold) elif (self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.NL_ITERATION_NUMBER] < self.min_iterations): KratosMultiphysics.Logger.PrintInfo(self._GetSimulationName(), "Up-scaling with factor: ", self.increase_factor) #converged = True self.delta_time *= self.increase_factor t = self._GetSolver().GetComputingModelPart().ProcessInfo[KratosMultiphysics.TIME] new_time = t + self.delta_time if (new_time > self.end_time): new_time = self.end_time self.delta_time = new_time - t if (not converged): raise Exception('The maximum number of cycles is reached without convergence!') if self._GetSolver().settings["reset_displacements"].GetBool() and converged: for idx, node in enumerate(self._GetSolver().GetComputingModelPart().Nodes): self._CalculateTotalDisplacement(node, old_total_displacements[idx]) self.FinalizeSolutionStep() self.OutputSolutionStep()
[ "def", "RunSolutionLoop", "(", "self", ")", ":", "if", "self", ".", "_GetSolver", "(", ")", ".", "settings", "[", "\"reset_displacements\"", "]", ".", "GetBool", "(", ")", ":", "old_total_displacements", "=", "[", "node", ".", "GetSolutionStepValue", "(", "K...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/GeoMechanicsApplication/python_scripts/geomechanics_analysis.py#L129-L195
facebook/folly
744a0a698074d1b013813065fe60f545aa2c9b94
build/fbcode_builder/getdeps/load.py
python
Loader._list_manifests
(self, build_opts)
Returns a generator that iterates all the available manifests
Returns a generator that iterates all the available manifests
[ "Returns", "a", "generator", "that", "iterates", "all", "the", "available", "manifests" ]
def _list_manifests(self, build_opts): """Returns a generator that iterates all the available manifests""" for (path, _, files) in os.walk(build_opts.manifests_dir): for name in files: # skip hidden files if name.startswith("."): continue yield os.path.join(path, name)
[ "def", "_list_manifests", "(", "self", ",", "build_opts", ")", ":", "for", "(", "path", ",", "_", ",", "files", ")", "in", "os", ".", "walk", "(", "build_opts", ".", "manifests_dir", ")", ":", "for", "name", "in", "files", ":", "# skip hidden files", "...
https://github.com/facebook/folly/blob/744a0a698074d1b013813065fe60f545aa2c9b94/build/fbcode_builder/getdeps/load.py#L19-L27
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
urllib3/packages/ordered_dict.py
python
OrderedDict.__delitem__
(self, key, dict_delitem=dict.__delitem__)
od.__delitem__(y) <==> del od[y]
od.__delitem__(y) <==> del od[y]
[ "od", ".", "__delitem__", "(", "y", ")", "<", "==", ">", "del", "od", "[", "y", "]" ]
def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which is # then removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link_prev, link_next, key = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev
[ "def", "__delitem__", "(", "self", ",", "key", ",", "dict_delitem", "=", "dict", ".", "__delitem__", ")", ":", "# Deleting an existing item uses self.__map to find the link which is", "# then removed by updating the links in the predecessor and successor nodes.", "dict_delitem", "(...
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/packages/ordered_dict.py#L55-L62
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py
python
get_meth_class_inst
(obj)
Return method class instance
Return method class instance
[ "Return", "method", "class", "instance" ]
def get_meth_class_inst(obj): """Return method class instance""" if PY2: # Python 2 return obj.im_self else: # Python 3 return obj.__self__
[ "def", "get_meth_class_inst", "(", "obj", ")", ":", "if", "PY2", ":", "# Python 2", "return", "obj", ".", "im_self", "else", ":", "# Python 3", "return", "obj", ".", "__self__" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py#L187-L194
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile._load
(self)
Read through the entire archive file and look for readable members.
Read through the entire archive file and look for readable members.
[ "Read", "through", "the", "entire", "archive", "file", "and", "look", "for", "readable", "members", "." ]
def _load(self): """Read through the entire archive file and look for readable members. """ while True: tarinfo = self.next() if tarinfo is None: break self._loaded = True
[ "def", "_load", "(", "self", ")", ":", "while", "True", ":", "tarinfo", "=", "self", ".", "next", "(", ")", "if", "tarinfo", "is", "None", ":", "break", "self", ".", "_loaded", "=", "True" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L2486-L2494
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/extras/cython.py
python
cython.scan
(self)
return (found, missing)
Return the dependent files (.pxd) by looking in the include folders. Put the headers to generate in the custom list "bld.raw_deps". To inspect the scanne results use:: $ waf clean build --zones=deps
Return the dependent files (.pxd) by looking in the include folders. Put the headers to generate in the custom list "bld.raw_deps". To inspect the scanne results use::
[ "Return", "the", "dependent", "files", "(", ".", "pxd", ")", "by", "looking", "in", "the", "include", "folders", ".", "Put", "the", "headers", "to", "generate", "in", "the", "custom", "list", "bld", ".", "raw_deps", ".", "To", "inspect", "the", "scanne",...
def scan(self): """ Return the dependent files (.pxd) by looking in the include folders. Put the headers to generate in the custom list "bld.raw_deps". To inspect the scanne results use:: $ waf clean build --zones=deps """ txt = self.inputs[0].read() mods = [] for m in re_cyt.finditer(txt): if m.group(1): # matches "from foo import bar" mods.append(m.group(1)) else: mods.append(m.group(2)) _msg.debug("cython: mods %r" % mods) incs = getattr(self.generator, 'cython_includes', []) incs = [self.generator.path.find_dir(x) for x in incs] incs.append(self.inputs[0].parent) found = [] missing = [] for x in mods: for y in incs: k = y.find_resource(x + '.pxd') if k: found.append(k) break else: missing.append(x) _msg.debug("cython: found %r" % found) # Now the .h created - store them in bld.raw_deps for later use has_api = False has_public = False for l in txt.splitlines(): if cy_api_pat.match(l): if ' api ' in l: has_api = True if ' public ' in l: has_public = True name = self.inputs[0].name.replace('.pyx', '') if has_api: missing.append('header:%s_api.h' % name) if has_public: missing.append('header:%s.h' % name) return (found, missing)
[ "def", "scan", "(", "self", ")", ":", "txt", "=", "self", ".", "inputs", "[", "0", "]", ".", "read", "(", ")", "mods", "=", "[", "]", "for", "m", "in", "re_cyt", ".", "finditer", "(", "txt", ")", ":", "if", "m", ".", "group", "(", "1", ")",...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/extras/cython.py#L71-L120
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/websocket-client/websocket.py
python
enableTrace
(tracable)
turn on/off the tracability. tracable: boolean value. if set True, tracability is enabled.
turn on/off the tracability.
[ "turn", "on", "/", "off", "the", "tracability", "." ]
def enableTrace(tracable): """ turn on/off the tracability. tracable: boolean value. if set True, tracability is enabled. """ global traceEnabled traceEnabled = tracable if tracable: if not logger.handlers: logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG)
[ "def", "enableTrace", "(", "tracable", ")", ":", "global", "traceEnabled", "traceEnabled", "=", "tracable", "if", "tracable", ":", "if", "not", "logger", ".", "handlers", ":", "logger", ".", "addHandler", "(", "logging", ".", "StreamHandler", "(", ")", ")", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/websocket-client/websocket.py#L102-L113
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/inspect.py
python
walktree
(classes, children, parent)
return results
Recursive helper function for getclasstree().
Recursive helper function for getclasstree().
[ "Recursive", "helper", "function", "for", "getclasstree", "()", "." ]
def walktree(classes, children, parent): """Recursive helper function for getclasstree().""" results = [] classes.sort(key=attrgetter('__module__', '__name__')) for c in classes: results.append((c, c.__bases__)) if c in children: results.append(walktree(children[c], children, c)) return results
[ "def", "walktree", "(", "classes", ",", "children", ",", "parent", ")", ":", "results", "=", "[", "]", "classes", ".", "sort", "(", "key", "=", "attrgetter", "(", "'__module__'", ",", "'__name__'", ")", ")", "for", "c", "in", "classes", ":", "results",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/inspect.py#L1028-L1036
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/estimators/head.py
python
binary_svm_head
( label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None, thresholds=None,)
return _BinarySvmHead( label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name, thresholds=thresholds)
Creates a `Head` for binary classification with SVMs. The head uses binary hinge loss. Args: label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: name of the head. If provided, predictions, summary and metrics keys will be suffixed by `"/" + head_name` and the default variable scope will be `head_name`. thresholds: thresholds for eval metrics, defaults to [.5] Returns: An instance of `Head` for binary classification with SVM.
Creates a `Head` for binary classification with SVMs.
[ "Creates", "a", "Head", "for", "binary", "classification", "with", "SVMs", "." ]
def binary_svm_head( label_name=None, weight_column_name=None, enable_centered_bias=False, head_name=None, thresholds=None,): """Creates a `Head` for binary classification with SVMs. The head uses binary hinge loss. Args: label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. head_name: name of the head. If provided, predictions, summary and metrics keys will be suffixed by `"/" + head_name` and the default variable scope will be `head_name`. thresholds: thresholds for eval metrics, defaults to [.5] Returns: An instance of `Head` for binary classification with SVM. """ return _BinarySvmHead( label_name=label_name, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias, head_name=head_name, thresholds=thresholds)
[ "def", "binary_svm_head", "(", "label_name", "=", "None", ",", "weight_column_name", "=", "None", ",", "enable_centered_bias", "=", "False", ",", "head_name", "=", "None", ",", "thresholds", "=", "None", ",", ")", ":", "return", "_BinarySvmHead", "(", "label_n...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/estimators/head.py#L337-L369
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/dtypes/base.py
python
Registry.register
(self, dtype: type[ExtensionDtype])
Parameters ---------- dtype : ExtensionDtype class
Parameters ---------- dtype : ExtensionDtype class
[ "Parameters", "----------", "dtype", ":", "ExtensionDtype", "class" ]
def register(self, dtype: type[ExtensionDtype]) -> None: """ Parameters ---------- dtype : ExtensionDtype class """ if not issubclass(dtype, ExtensionDtype): raise ValueError("can only register pandas extension dtypes") self.dtypes.append(dtype)
[ "def", "register", "(", "self", ",", "dtype", ":", "type", "[", "ExtensionDtype", "]", ")", "->", "None", ":", "if", "not", "issubclass", "(", "dtype", ",", "ExtensionDtype", ")", ":", "raise", "ValueError", "(", "\"can only register pandas extension dtypes\"", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/base.py#L414-L423
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Show/mTempoVis.py
python
TempoVis.restore_all_dependent
(self, doc_obj)
show_all_dependent(doc_obj): restores original visibilities of all dependent objects.
show_all_dependent(doc_obj): restores original visibilities of all dependent objects.
[ "show_all_dependent", "(", "doc_obj", ")", ":", "restores", "original", "visibilities", "of", "all", "dependent", "objects", "." ]
def restore_all_dependent(self, doc_obj): '''show_all_dependent(doc_obj): restores original visibilities of all dependent objects.''' from .DepGraphTools import getAllDependencies, getAllDependent self.restoreVPProperty( getAllDependent(doc_obj), ('Visibility', 'LinkVisibility') )
[ "def", "restore_all_dependent", "(", "self", ",", "doc_obj", ")", ":", "from", ".", "DepGraphTools", "import", "getAllDependencies", ",", "getAllDependent", "self", ".", "restoreVPProperty", "(", "getAllDependent", "(", "doc_obj", ")", ",", "(", "'Visibility'", ",...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Show/mTempoVis.py#L348-L351
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/module/executor_group.py
python
_merge_multi_context
(outputs, major_axis)
return rets
Merge outputs that lives on multiple context into one, so that they look like living on one context.
Merge outputs that lives on multiple context into one, so that they look like living on one context.
[ "Merge", "outputs", "that", "lives", "on", "multiple", "context", "into", "one", "so", "that", "they", "look", "like", "living", "on", "one", "context", "." ]
def _merge_multi_context(outputs, major_axis): """Merge outputs that lives on multiple context into one, so that they look like living on one context. """ rets = [] for tensors, axis in zip(outputs, major_axis): if axis >= 0: # pylint: disable=no-member,protected-access if len(tensors) == 1: rets.append(tensors[0]) else: # Concatenate if necessary rets.append(nd.concat(*[tensor.as_in_context(tensors[0].context) for tensor in tensors], dim=axis)) # pylint: enable=no-member,protected-access else: # negative axis means the there is no batch_size axis, and all the # results should be the same on each device. We simply take the # first one, without checking they are actually the same rets.append(tensors[0]) return rets
[ "def", "_merge_multi_context", "(", "outputs", ",", "major_axis", ")", ":", "rets", "=", "[", "]", "for", "tensors", ",", "axis", "in", "zip", "(", "outputs", ",", "major_axis", ")", ":", "if", "axis", ">=", "0", ":", "# pylint: disable=no-member,protected-a...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/module/executor_group.py#L89-L110
HeYijia/PL-VIO
ddec7f3995cae0c90ba216861ad7cd784e7004cf
sim_data_pub/Myimg2bag/img2bag_PennCOSYVIO.py
python
ReadIMU
(filename)
return timestamp,imu_data
return IMU data and timestamp of IMU
return IMU data and timestamp of IMU
[ "return", "IMU", "data", "and", "timestamp", "of", "IMU" ]
def ReadIMU(filename): '''return IMU data and timestamp of IMU''' file = open(filename,'r') all = file.readlines() timestamp = [] imu_data = [] for f in all: s = f.rstrip('\n') # print s # print s.split() s = ' '.join(s.split()); line = s.split(' ') print line timestamp.append(line[0]) imu_data.append(line[1:]) return timestamp,imu_data
[ "def", "ReadIMU", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "'r'", ")", "all", "=", "file", ".", "readlines", "(", ")", "timestamp", "=", "[", "]", "imu_data", "=", "[", "]", "for", "f", "in", "all", ":", "s", "=", "...
https://github.com/HeYijia/PL-VIO/blob/ddec7f3995cae0c90ba216861ad7cd784e7004cf/sim_data_pub/Myimg2bag/img2bag_PennCOSYVIO.py#L41-L56
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py
python
SetVariable
(output, variable_name, value)
Sets a CMake variable.
Sets a CMake variable.
[ "Sets", "a", "CMake", "variable", "." ]
def SetVariable(output, variable_name, value): """Sets a CMake variable.""" output.write('set(') output.write(variable_name) output.write(' "') output.write(CMakeStringEscape(value)) output.write('")\n')
[ "def", "SetVariable", "(", "output", ",", "variable_name", ",", "value", ")", ":", "output", ".", "write", "(", "'set('", ")", "output", ".", "write", "(", "variable_name", ")", "output", ".", "write", "(", "' \"'", ")", "output", ".", "write", "(", "C...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py#L179-L185
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/python_gflags/gflags.py
python
_ArgumentParserCache.__call__
(mcs, *args, **kwargs)
Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or the values in args are not hashable, this method always returns a new instance of cls. Args: args: Positional initializer arguments. kwargs: Initializer keyword arguments. Returns: An instance of cls, shared or new.
Returns an instance of the argument parser cls.
[ "Returns", "an", "instance", "of", "the", "argument", "parser", "cls", "." ]
def __call__(mcs, *args, **kwargs): """Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or the values in args are not hashable, this method always returns a new instance of cls. Args: args: Positional initializer arguments. kwargs: Initializer keyword arguments. Returns: An instance of cls, shared or new. """ if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = (mcs,) + tuple(args) try: return instances[key] except KeyError: # No cache entry for key exists, create a new one. return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: # An object in args cannot be hashed, always return # a new instance. return type.__call__(mcs, *args)
[ "def", "__call__", "(", "mcs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "return", "type", ".", "__call__", "(", "mcs", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "instances", "=", "mcs", ".", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L1998-L2030
ros/geometry
63c3c7b404b8f390061bdadc5bc675e7ae5808be
tf/src/tf/transformations.py
python
quaternion_matrix
(quaternion)
return numpy.array(( (1.0-q[1, 1]-q[2, 2], q[0, 1]-q[2, 3], q[0, 2]+q[1, 3], 0.0), ( q[0, 1]+q[2, 3], 1.0-q[0, 0]-q[2, 2], q[1, 2]-q[0, 3], 0.0), ( q[0, 2]-q[1, 3], q[1, 2]+q[0, 3], 1.0-q[0, 0]-q[1, 1], 0.0), ( 0.0, 0.0, 0.0, 1.0) ), dtype=numpy.float64)
Return homogeneous rotation matrix from quaternion. >>> R = quaternion_matrix([0.06146124, 0, 0, 0.99810947]) >>> numpy.allclose(R, rotation_matrix(0.123, (1, 0, 0))) True
Return homogeneous rotation matrix from quaternion.
[ "Return", "homogeneous", "rotation", "matrix", "from", "quaternion", "." ]
def quaternion_matrix(quaternion): """Return homogeneous rotation matrix from quaternion. >>> R = quaternion_matrix([0.06146124, 0, 0, 0.99810947]) >>> numpy.allclose(R, rotation_matrix(0.123, (1, 0, 0))) True """ q = numpy.array(quaternion[:4], dtype=numpy.float64, copy=True) nq = numpy.dot(q, q) if nq < _EPS: return numpy.identity(4) q *= math.sqrt(2.0 / nq) q = numpy.outer(q, q) return numpy.array(( (1.0-q[1, 1]-q[2, 2], q[0, 1]-q[2, 3], q[0, 2]+q[1, 3], 0.0), ( q[0, 1]+q[2, 3], 1.0-q[0, 0]-q[2, 2], q[1, 2]-q[0, 3], 0.0), ( q[0, 2]-q[1, 3], q[1, 2]+q[0, 3], 1.0-q[0, 0]-q[1, 1], 0.0), ( 0.0, 0.0, 0.0, 1.0) ), dtype=numpy.float64)
[ "def", "quaternion_matrix", "(", "quaternion", ")", ":", "q", "=", "numpy", ".", "array", "(", "quaternion", "[", ":", "4", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "nq", "=", "numpy", ".", "dot", "(", "q", ...
https://github.com/ros/geometry/blob/63c3c7b404b8f390061bdadc5bc675e7ae5808be/tf/src/tf/transformations.py#L1174-L1193
area1/stpyv8
5ae7dc502957c10a6115adf080304261a8e36722
STPyV8.py
python
JSClass.__lookupGetter__
(self, name)
return self.__properties__.get(name, (None, None))[0]
Return the function bound as a getter to the specified property
Return the function bound as a getter to the specified property
[ "Return", "the", "function", "bound", "as", "a", "getter", "to", "the", "specified", "property" ]
def __lookupGetter__(self, name): """ Return the function bound as a getter to the specified property """ return self.__properties__.get(name, (None, None))[0]
[ "def", "__lookupGetter__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "__properties__", ".", "get", "(", "name", ",", "(", "None", ",", "None", ")", ")", "[", "0", "]" ]
https://github.com/area1/stpyv8/blob/5ae7dc502957c10a6115adf080304261a8e36722/STPyV8.py#L215-L219
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/flatnotebook.py
python
FlatNotebook.GetPageCount
(self)
return self._pages.GetPageCount()
Returns the number of pages in the L{FlatNotebook} control.
Returns the number of pages in the L{FlatNotebook} control.
[ "Returns", "the", "number", "of", "pages", "in", "the", "L", "{", "FlatNotebook", "}", "control", "." ]
def GetPageCount(self): """ Returns the number of pages in the L{FlatNotebook} control. """ return self._pages.GetPageCount()
[ "def", "GetPageCount", "(", "self", ")", ":", "return", "self", ".", "_pages", ".", "GetPageCount", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L3441-L3444
wangkuiyi/mapreduce-lite
1bb92fe094dc47480ef9163c34070a3199feead6
src/mapreduce_lite/scheduler/mrlite_options.py
python
IndentedHelpFormatterWithNL.format_option
(self, option)
return "".join(result)
Keep newline in option message
Keep newline in option message
[ "Keep", "newline", "in", "option", "message" ]
def format_option(self, option): """ Keep newline in option message """ result = [] opts = self.option_strings[option] opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: opts = "%*s%s\n" % (self.current_indent, "", opts) indent_first = self.help_position else: opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) indent_first = 0 result.append(opts) if option.help: help_text = self.expand_default(option) help_lines = [] for para in help_text.split("\n"): help_lines.extend(textwrap.wrap(para, self.help_width)) result.append("%*s%s\n" % ( indent_first, "", help_lines[0])) result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]]) elif opts[-1] != "\n": result.append("\n") return "".join(result)
[ "def", "format_option", "(", "self", ",", "option", ")", ":", "result", "=", "[", "]", "opts", "=", "self", ".", "option_strings", "[", "option", "]", "opt_width", "=", "self", ".", "help_position", "-", "self", ".", "current_indent", "-", "2", "if", "...
https://github.com/wangkuiyi/mapreduce-lite/blob/1bb92fe094dc47480ef9163c34070a3199feead6/src/mapreduce_lite/scheduler/mrlite_options.py#L155-L179
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/fake_quant_with_min_max_vars_per_channel_gradient.py
python
_fake_quant_with_min_max_vars_per_channel_gradient_tbe
()
return
FakeQuantWithMinMaxVarsPerChannelGradient TBE register
FakeQuantWithMinMaxVarsPerChannelGradient TBE register
[ "FakeQuantWithMinMaxVarsPerChannelGradient", "TBE", "register" ]
def _fake_quant_with_min_max_vars_per_channel_gradient_tbe(): """FakeQuantWithMinMaxVarsPerChannelGradient TBE register""" return
[ "def", "_fake_quant_with_min_max_vars_per_channel_gradient_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/fake_quant_with_min_max_vars_per_channel_gradient.py#L41-L43
plaidml/plaidml
f3c6681db21460e5fdc11ae651d6d7b6c27f8262
mlperf/pycoco.py
python
COCO.loadAnns
(self, ids=[])
Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects
Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects
[ "Load", "anns", "with", "the", "specified", "ids", ".", ":", "param", "ids", "(", "int", "array", ")", ":", "integer", "ids", "specifying", "anns", ":", "return", ":", "anns", "(", "object", "array", ")", ":", "loaded", "ann", "objects" ]
def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects """ if _isArrayLike(ids): return [self.anns[id] for id in ids] elif type(ids) == int: return [self.anns[ids]]
[ "def", "loadAnns", "(", "self", ",", "ids", "=", "[", "]", ")", ":", "if", "_isArrayLike", "(", "ids", ")", ":", "return", "[", "self", ".", "anns", "[", "id", "]", "for", "id", "in", "ids", "]", "elif", "type", "(", "ids", ")", "==", "int", ...
https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/mlperf/pycoco.py#L208-L217
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/summary/_writer_pool.py
python
WriterPool.close
(self)
Close the writer.
Close the writer.
[ "Close", "the", "writer", "." ]
def close(self) -> None: """Close the writer.""" self._queue.put(('END', None))
[ "def", "close", "(", "self", ")", "->", "None", ":", "self", ".", "_queue", ".", "put", "(", "(", "'END'", ",", "None", ")", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/summary/_writer_pool.py#L183-L185
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/nativetypes.py
python
NativeCodeGenerator.visit_Output
(self, node, frame)
Same as :meth:`CodeGenerator.visit_Output`, but do not call ``to_string`` on output nodes in generated code.
Same as :meth:`CodeGenerator.visit_Output`, but do not call ``to_string`` on output nodes in generated code.
[ "Same", "as", ":", "meth", ":", "CodeGenerator", ".", "visit_Output", "but", "do", "not", "call", "to_string", "on", "output", "nodes", "in", "generated", "code", "." ]
def visit_Output(self, node, frame): """Same as :meth:`CodeGenerator.visit_Output`, but do not call ``to_string`` on output nodes in generated code. """ if self.has_known_extends and frame.require_output_check: return finalize = self.environment.finalize finalize_context = getattr(finalize, 'contextfunction', False) finalize_eval = getattr(finalize, 'evalcontextfunction', False) finalize_env = getattr(finalize, 'environmentfunction', False) if finalize is not None: if finalize_context or finalize_eval: const_finalize = None elif finalize_env: def const_finalize(x): return finalize(self.environment, x) else: const_finalize = finalize else: def const_finalize(x): return x # If we are inside a frame that requires output checking, we do so. outdent_later = False if frame.require_output_check: self.writeline('if parent_template is None:') self.indent() outdent_later = True # Try to evaluate as many chunks as possible into a static string at # compile time. body = [] for child in node.nodes: try: if const_finalize is None: raise nodes.Impossible() const = child.as_const(frame.eval_ctx) if not has_safe_repr(const): raise nodes.Impossible() except nodes.Impossible: body.append(child) continue # the frame can't be volatile here, because otherwise the as_const # function would raise an Impossible exception at that point try: if frame.eval_ctx.autoescape: if hasattr(const, '__html__'): const = const.__html__() else: const = escape(const) const = const_finalize(const) except Exception: # if something goes wrong here we evaluate the node at runtime # for easier debugging body.append(child) continue if body and isinstance(body[-1], list): body[-1].append(const) else: body.append([const]) # if we have less than 3 nodes or a buffer we yield or extend/append if len(body) < 3 or frame.buffer is not None: if frame.buffer is not None: # for one item we append, for more we extend if len(body) == 1: self.writeline('%s.append(' % frame.buffer) else: self.writeline('%s.extend((' % frame.buffer) self.indent() for item in body: if isinstance(item, list): val = repr(native_concat(item)) if frame.buffer is None: self.writeline('yield ' + val) else: self.writeline(val + ',') else: if frame.buffer is None: self.writeline('yield ', item) else: self.newline(item) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') close += 1 self.visit(item, frame) if close > 0: self.write(')' * close) if frame.buffer is not None: self.write(',') if frame.buffer is not None: # close the open parentheses self.outdent() self.writeline(len(body) == 1 and ')' or '))') # otherwise we create a format string as this is faster in that case else: format = [] arguments = [] for item in body: if isinstance(item, list): format.append(native_concat(item).replace('%', '%%')) else: format.append('%s') arguments.append(item) self.writeline('yield ') self.write(repr(concat(format)) + ' % (') self.indent() for argument in arguments: self.newline(argument) close = 0 if finalize is not None: self.write('environment.finalize(') if finalize_context: self.write('context, ') elif finalize_eval: self.write('context.eval_ctx, ') elif finalize_env: self.write('environment, ') close += 1 self.visit(argument, frame) self.write(')' * close + ', ') self.outdent() self.writeline(')') if outdent_later: self.outdent()
[ "def", "visit_Output", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "self", ".", "has_known_extends", "and", "frame", ".", "require_output_check", ":", "return", "finalize", "=", "self", ".", "environment", ".", "finalize", "finalize_context", "=", ...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/nativetypes.py#L39-L195
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/rfc822.py
python
mktime_tz
(data)
Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.
Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.
[ "Turn", "a", "10", "-", "tuple", "as", "returned", "by", "parsedate_tz", "()", "into", "a", "UTC", "timestamp", "." ]
def mktime_tz(data): """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.""" if data[9] is None: # No zone info, so localtime is better assumption than GMT return time.mktime(data[:8] + (-1,)) else: t = time.mktime(data[:8] + (0,)) return t - data[9] - time.timezone
[ "def", "mktime_tz", "(", "data", ")", ":", "if", "data", "[", "9", "]", "is", "None", ":", "# No zone info, so localtime is better assumption than GMT", "return", "time", ".", "mktime", "(", "data", "[", ":", "8", "]", "+", "(", "-", "1", ",", ")", ")", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/rfc822.py#L943-L950
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozpack/packager/__init__.py
python
SimplePackager.add
(self, path, file)
Add the given BaseFile instance with the given path.
Add the given BaseFile instance with the given path.
[ "Add", "the", "given", "BaseFile", "instance", "with", "the", "given", "path", "." ]
def add(self, path, file): ''' Add the given BaseFile instance with the given path. ''' assert not self._closed if is_manifest(path): self._add_manifest_file(path, file) elif path.endswith('.xpt'): self._queue.append(self.formatter.add_interfaces, path, file) else: self._file_queue.append(self.formatter.add, path, file)
[ "def", "add", "(", "self", ",", "path", ",", "file", ")", ":", "assert", "not", "self", ".", "_closed", "if", "is_manifest", "(", "path", ")", ":", "self", ".", "_add_manifest_file", "(", "path", ",", "file", ")", "elif", "path", ".", "endswith", "("...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/packager/__init__.py#L243-L253
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
IconBundle.GetIconCount
(*args, **kwargs)
return _gdi_.IconBundle_GetIconCount(*args, **kwargs)
GetIconCount(self) -> size_t return the number of available icons
GetIconCount(self) -> size_t
[ "GetIconCount", "(", "self", ")", "-", ">", "size_t" ]
def GetIconCount(*args, **kwargs): """ GetIconCount(self) -> size_t return the number of available icons """ return _gdi_.IconBundle_GetIconCount(*args, **kwargs)
[ "def", "GetIconCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "IconBundle_GetIconCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1439-L1445
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/client/session.py
python
SessionInterface.partial_run
(self, handle, fetches, feed_dict=None)
Continues the execution with additional feeds and fetches.
Continues the execution with additional feeds and fetches.
[ "Continues", "the", "execution", "with", "additional", "feeds", "and", "fetches", "." ]
def partial_run(self, handle, fetches, feed_dict=None): """Continues the execution with additional feeds and fetches.""" raise NotImplementedError('partial_run')
[ "def", "partial_run", "(", "self", ",", "handle", ",", "fetches", ",", "feed_dict", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'partial_run'", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/session.py#L58-L60
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/header.py
python
Header.append
(self, s, charset=None, errors='strict')
Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is false), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In either case, when producing an RFC 2822 compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded to the output codec, a UnicodeError will be raised. Optional `errors' is passed as the errors argument to the decode call if s is a byte string.
Append a string to the MIME header.
[ "Append", "a", "string", "to", "the", "MIME", "header", "." ]
def append(self, s, charset=None, errors='strict'): """Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is false), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In either case, when producing an RFC 2822 compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded to the output codec, a UnicodeError will be raised. Optional `errors' is passed as the errors argument to the decode call if s is a byte string. """ if charset is None: charset = self._charset elif not isinstance(charset, Charset): charset = Charset(charset) if not isinstance(s, str): input_charset = charset.input_codec or 'us-ascii' if input_charset == _charset.UNKNOWN8BIT: s = s.decode('us-ascii', 'surrogateescape') else: s = s.decode(input_charset, errors) # Ensure that the bytes we're storing can be decoded to the output # character set, otherwise an early error is raised. output_charset = charset.output_codec or 'us-ascii' if output_charset != _charset.UNKNOWN8BIT: try: s.encode(output_charset, errors) except UnicodeEncodeError: if output_charset!='us-ascii': raise charset = UTF8 self._chunks.append((s, charset))
[ "def", "append", "(", "self", ",", "s", ",", "charset", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "if", "charset", "is", "None", ":", "charset", "=", "self", ".", "_charset", "elif", "not", "isinstance", "(", "charset", ",", "Charset", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/header.py#L265-L306
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/graph_editor/select.py
python
select_ops
(*args, **kwargs)
return ops
Helper to select operations. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) `tf.Operation`. `tf.Tensor` instances are silently ignored. **kwargs: 'graph': `tf.Graph` in which to perform the regex query.This is required when using regex. 'positive_filter': an elem if selected only if `positive_filter(elem)` is `True`. This is optional. 'restrict_ops_regex': a regular expression is ignored if it doesn't start with the substring "(?#ops)". Returns: A list of `tf.Operation`. Raises: TypeError: if the optional keyword argument graph is not a `tf.Graph` or if an argument in args is not an (array of) `tf.Operation` or an (array of) `tf.Tensor` (silently ignored) or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected or if a regular expression is used without passing a graph as a keyword argument.
Helper to select operations.
[ "Helper", "to", "select", "operations", "." ]
def select_ops(*args, **kwargs): """Helper to select operations. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) `tf.Operation`. `tf.Tensor` instances are silently ignored. **kwargs: 'graph': `tf.Graph` in which to perform the regex query.This is required when using regex. 'positive_filter': an elem if selected only if `positive_filter(elem)` is `True`. This is optional. 'restrict_ops_regex': a regular expression is ignored if it doesn't start with the substring "(?#ops)". Returns: A list of `tf.Operation`. Raises: TypeError: if the optional keyword argument graph is not a `tf.Graph` or if an argument in args is not an (array of) `tf.Operation` or an (array of) `tf.Tensor` (silently ignored) or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected or if a regular expression is used without passing a graph as a keyword argument. """ # get keywords arguments graph = None positive_filter = None restrict_ops_regex = False for k, v in iteritems(kwargs): if k == "graph": graph = v if graph is not None and not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got: {}".format(type(graph))) elif k == "positive_filter": positive_filter = v elif k == "restrict_ops_regex": restrict_ops_regex = v elif k == "restrict_ts_regex": pass else: raise ValueError("Wrong keywords argument: {}.".format(k)) ops = [] for arg in args: if can_be_regex(arg): if graph is None: raise ValueError("Use the keyword argument 'graph' to use regex.") regex = make_regex(arg) if regex.pattern.startswith("(?#ts)"): continue if restrict_ops_regex and not regex.pattern.startswith("(?#ops)"): continue ops_ = filter_ops_from_regex(graph, regex) for op_ in ops_: if op_ not in ops: if positive_filter is None or positive_filter(op_): ops.append(op_) else: ops_aux = util.make_list_of_op(arg, ignore_ts=True) if positive_filter is not None: ops_aux = [op for op in ops_aux if positive_filter(op)] ops_aux = [op for op in ops_aux if op not in ops] ops += ops_aux return ops
[ "def", "select_ops", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# get keywords arguments", "graph", "=", "None", "positive_filter", "=", "None", "restrict_ops_regex", "=", "False", "for", "k", ",", "v", "in", "iteritems", "(", "kwargs", ")", ":"...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/select.py#L614-L677
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/xcodeproj_file.py
python
XCConfigurationList.GetBuildSetting
(self, key)
return value
Gets the build setting for key. All child XCConfiguration objects must have the same value set for the setting, or a ValueError will be raised.
Gets the build setting for key.
[ "Gets", "the", "build", "setting", "for", "key", "." ]
def GetBuildSetting(self, key): """Gets the build setting for key. All child XCConfiguration objects must have the same value set for the setting, or a ValueError will be raised. """ # TODO(mark): This is wrong for build settings that are lists. The list # contents should be compared (and a list copy returned?) value = None for configuration in self._properties['buildConfigurations']: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value else: if value != configuration_value: raise ValueError('Variant values for ' + key) return value
[ "def", "GetBuildSetting", "(", "self", ",", "key", ")", ":", "# TODO(mark): This is wrong for build settings that are lists. The list", "# contents should be compared (and a list copy returned?)", "value", "=", "None", "for", "configuration", "in", "self", ".", "_properties", ...
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/xcodeproj_file.py#L1651-L1670
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/intelhex/__init__.py
python
IntelHex._decode_record
(self, s, line=0)
Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered.
Decode one record of HEX file.
[ "Decode", "one", "record", "of", "HEX", "file", "." ]
def _decode_record(self, s, line=0): '''Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. ''' s = s.rstrip('\r\n') if not s: return # empty line if s[0] == ':': try: bin = array('B', unhexlify(asbytes(s[1:]))) except (TypeError, ValueError): # this might be raised by unhexlify when odd hexascii digits raise HexRecordError(line=line) length = len(bin) if length < 5: raise HexRecordError(line=line) else: raise HexRecordError(line=line) record_length = bin[0] if length != (5 + record_length): raise RecordLengthError(line=line) addr = bin[1]*256 + bin[2] record_type = bin[3] if not (0 <= record_type <= 5): raise RecordTypeError(line=line) crc = sum(bin) crc &= 0x0FF if crc != 0: raise RecordChecksumError(line=line) if record_type == 0: # data record addr += self._offset for i in range_g(4, 4+record_length): if not self._buf.get(addr, None) is None: raise AddressOverlapError(address=addr, line=line) self._buf[addr] = bin[i] addr += 1 # FIXME: addr should be wrapped # BUT after 02 record (at 64K boundary) # and after 04 record (at 4G boundary) elif record_type == 1: # end of file record if record_length != 0: raise EOFRecordError(line=line) raise _EndOfFile elif record_type == 2: # Extended 8086 Segment Record if record_length != 2 or addr != 0: raise ExtendedSegmentAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 16 elif record_type == 4: # Extended Linear Address Record if record_length != 2 or addr != 0: raise ExtendedLinearAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 65536 elif record_type == 3: # Start Segment Address Record if record_length != 4 or addr != 0: raise StartSegmentAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'CS': bin[4]*256 + bin[5], 'IP': bin[6]*256 + bin[7], } elif record_type == 5: # Start Linear Address Record if record_length != 4 or addr != 0: raise StartLinearAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'EIP': (bin[4]*16777216 + bin[5]*65536 + bin[6]*256 + bin[7]), }
[ "def", "_decode_record", "(", "self", ",", "s", ",", "line", "=", "0", ")", ":", "s", "=", "s", ".", "rstrip", "(", "'\\r\\n'", ")", "if", "not", "s", ":", "return", "# empty line", "if", "s", "[", "0", "]", "==", "':'", ":", "try", ":", "bin",...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/intelhex/__init__.py#L101-L189
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBHostOS_ThreadCreate
(name, arg3, thread_arg, err)
return _lldb.SBHostOS_ThreadCreate(name, arg3, thread_arg, err)
SBHostOS_ThreadCreate(char const * name, lldb::thread_func_t arg3, void * thread_arg, SBError err) -> lldb::thread_t
SBHostOS_ThreadCreate(char const * name, lldb::thread_func_t arg3, void * thread_arg, SBError err) -> lldb::thread_t
[ "SBHostOS_ThreadCreate", "(", "char", "const", "*", "name", "lldb", "::", "thread_func_t", "arg3", "void", "*", "thread_arg", "SBError", "err", ")", "-", ">", "lldb", "::", "thread_t" ]
def SBHostOS_ThreadCreate(name, arg3, thread_arg, err): """SBHostOS_ThreadCreate(char const * name, lldb::thread_func_t arg3, void * thread_arg, SBError err) -> lldb::thread_t""" return _lldb.SBHostOS_ThreadCreate(name, arg3, thread_arg, err)
[ "def", "SBHostOS_ThreadCreate", "(", "name", ",", "arg3", ",", "thread_arg", ",", "err", ")", ":", "return", "_lldb", ".", "SBHostOS_ThreadCreate", "(", "name", ",", "arg3", ",", "thread_arg", ",", "err", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6124-L6126
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/groupby/generic.py
python
PanelGroupBy.aggregate
(self, arg, *args, **kwargs)
return self._aggregate_generic(arg, *args, **kwargs)
Aggregate using input function or dict of {column -> function} Parameters ---------- arg : function or dict Function to use for aggregating groups. If a function, must either work when passed a Panel or when passed to Panel.apply. If pass a dict, the keys must be DataFrame column names Returns ------- aggregated : Panel
Aggregate using input function or dict of {column -> function}
[ "Aggregate", "using", "input", "function", "or", "dict", "of", "{", "column", "-", ">", "function", "}" ]
def aggregate(self, arg, *args, **kwargs): """ Aggregate using input function or dict of {column -> function} Parameters ---------- arg : function or dict Function to use for aggregating groups. If a function, must either work when passed a Panel or when passed to Panel.apply. If pass a dict, the keys must be DataFrame column names Returns ------- aggregated : Panel """ if isinstance(arg, compat.string_types): return getattr(self, arg)(*args, **kwargs) return self._aggregate_generic(arg, *args, **kwargs)
[ "def", "aggregate", "(", "self", ",", "arg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "arg", ",", "compat", ".", "string_types", ")", ":", "return", "getattr", "(", "self", ",", "arg", ")", "(", "*", "args", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/groupby/generic.py#L1613-L1631
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozpack/files.py
python
BaseFinder.__iter__
(self)
return self.find('')
Iterates over all files under the base directory (excluding files starting with a '.' and files at any level under a directory starting with a '.'). for path, file in finder: ...
Iterates over all files under the base directory (excluding files starting with a '.' and files at any level under a directory starting with a '.'). for path, file in finder: ...
[ "Iterates", "over", "all", "files", "under", "the", "base", "directory", "(", "excluding", "files", "starting", "with", "a", ".", "and", "files", "at", "any", "level", "under", "a", "directory", "starting", "with", "a", ".", ")", ".", "for", "path", "fil...
def __iter__(self): ''' Iterates over all files under the base directory (excluding files starting with a '.' and files at any level under a directory starting with a '.'). for path, file in finder: ... ''' return self.find('')
[ "def", "__iter__", "(", "self", ")", ":", "return", "self", ".", "find", "(", "''", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/files.py#L684-L692
nnrg/opennero
43e12a1bcba6e228639db3886fec1dc47ddc24cb
mods/Roomba/agent_handler.py
python
AgentState.initialize
(self)
add more parameters here (optional)
add more parameters here (optional)
[ "add", "more", "parameters", "here", "(", "optional", ")" ]
def initialize(self): """ add more parameters here (optional) """ self.initial_velocity = Vector3f(0, 0, 0) self.is_out = False
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "initial_velocity", "=", "Vector3f", "(", "0", ",", "0", ",", "0", ")", "self", ".", "is_out", "=", "False" ]
https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Roomba/agent_handler.py#L25-L28
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py
python
ParserElement.__call__
(self, name=None)
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}.
[ "Shortcut", "for", "C", "{", "L", "{", "setResultsName", "}}", "with", "C", "{", "listAllMatches", "=", "False", "}", ".", "If", "C", "{", "name", "}", "is", "given", "with", "a", "trailing", "C", "{", "*", "}", "character", "then", "C", "{", "list...
def __call__(self, name=None): """ Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") """ if name is not None: return self.setResultsName(name) else: return self.copy()
[ "def", "__call__", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "not", "None", ":", "return", "self", ".", "setResultsName", "(", "name", ")", "else", ":", "return", "self", ".", "copy", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L2026-L2043
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/procrouting/proc.py
python
run_mcscf
(name, **kwargs)
return core.mcscf(new_wfn)
Function encoding sequence of PSI module calls for a multiconfigurational self-consistent-field calculation.
Function encoding sequence of PSI module calls for a multiconfigurational self-consistent-field calculation.
[ "Function", "encoding", "sequence", "of", "PSI", "module", "calls", "for", "a", "multiconfigurational", "self", "-", "consistent", "-", "field", "calculation", "." ]
def run_mcscf(name, **kwargs): """Function encoding sequence of PSI module calls for a multiconfigurational self-consistent-field calculation. """ # Make sure the molecule the user provided is the active one mcscf_molecule = kwargs.get('molecule', core.get_active_molecule()) mcscf_molecule.update_geometry() if 'ref_wfn' in kwargs: raise ValidationError("It is not possible to pass run_mcscf a reference wavefunction") new_wfn = core.Wavefunction.build(mcscf_molecule, core.get_global_option('BASIS')) return core.mcscf(new_wfn)
[ "def", "run_mcscf", "(", "name", ",", "*", "*", "kwargs", ")", ":", "# Make sure the molecule the user provided is the active one", "mcscf_molecule", "=", "kwargs", ".", "get", "(", "'molecule'", ",", "core", ".", "get_active_molecule", "(", ")", ")", "mcscf_molecul...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/proc.py#L2593-L2605
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py
python
TFAsymmetryFittingModel._toggle_fix_normalisation_in_tf_asymmetry_simultaneous_mode
(self, dataset_index: int, is_fixed: bool)
Fixes the current normalisation to its current value in simultaneous mode, or unfixes it.
Fixes the current normalisation to its current value in simultaneous mode, or unfixes it.
[ "Fixes", "the", "current", "normalisation", "to", "its", "current", "value", "in", "simultaneous", "mode", "or", "unfixes", "it", "." ]
def _toggle_fix_normalisation_in_tf_asymmetry_simultaneous_mode(self, dataset_index: int, is_fixed: bool) -> None: """Fixes the current normalisation to its current value in simultaneous mode, or unfixes it.""" tf_simultaneous_function = self.fitting_context.tf_asymmetry_simultaneous_function if tf_simultaneous_function is not None: if self.fitting_context.number_of_datasets > 1: full_parameter = self._get_normalisation_function_parameter_for_simultaneous_domain(dataset_index) else: full_parameter = NORMALISATION_PARAMETER if is_fixed: tf_simultaneous_function.fixParameter(full_parameter) else: tf_simultaneous_function.freeParameter(full_parameter)
[ "def", "_toggle_fix_normalisation_in_tf_asymmetry_simultaneous_mode", "(", "self", ",", "dataset_index", ":", "int", ",", "is_fixed", ":", "bool", ")", "->", "None", ":", "tf_simultaneous_function", "=", "self", ".", "fitting_context", ".", "tf_asymmetry_simultaneous_func...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py#L514-L526
lmb-freiburg/flownet2
b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc
tools/extra/parse_log.py
python
save_csv_files
(logfile_path, output_dir, train_dict_list, test_dict_list, delimiter=',', verbose=False)
Save CSV files to output_dir If the input log file is, e.g., caffe.INFO, the names will be caffe.INFO.train and caffe.INFO.test
Save CSV files to output_dir
[ "Save", "CSV", "files", "to", "output_dir" ]
def save_csv_files(logfile_path, output_dir, train_dict_list, test_dict_list, delimiter=',', verbose=False): """Save CSV files to output_dir If the input log file is, e.g., caffe.INFO, the names will be caffe.INFO.train and caffe.INFO.test """ log_basename = os.path.basename(logfile_path) train_filename = os.path.join(output_dir, log_basename + '.train') write_csv(train_filename, train_dict_list, delimiter, verbose) test_filename = os.path.join(output_dir, log_basename + '.test') write_csv(test_filename, test_dict_list, delimiter, verbose)
[ "def", "save_csv_files", "(", "logfile_path", ",", "output_dir", ",", "train_dict_list", ",", "test_dict_list", ",", "delimiter", "=", "','", ",", "verbose", "=", "False", ")", ":", "log_basename", "=", "os", ".", "path", ".", "basename", "(", "logfile_path", ...
https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/tools/extra/parse_log.py#L132-L145
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
parserCtxt.ctxtUseOptions
(self, options)
return ret
Applies the options to the parser context
Applies the options to the parser context
[ "Applies", "the", "options", "to", "the", "parser", "context" ]
def ctxtUseOptions(self, options): """Applies the options to the parser context """ ret = libxml2mod.xmlCtxtUseOptions(self._o, options) return ret
[ "def", "ctxtUseOptions", "(", "self", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCtxtUseOptions", "(", "self", ".", "_o", ",", "options", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L4301-L4304
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_eager.py
python
_model_loss
(model, inputs, targets, output_loss_metrics=None, sample_weights=None, training=False)
return outs, total_loss, output_losses, masks
Calculates the loss for a given model. Arguments: model: The model on which metrics are being calculated. inputs: Either a dictionary of inputs to the model or a list of input arrays. targets: List of target arrays. output_loss_metrics: List of metrics that are used to aggregated output loss values. sample_weights: Optional list of sample weight arrays. training: Whether the model should be run in inference or training mode. Returns: Returns the model output, total loss, loss value calculated using the specified loss function and masks for each output. The total loss includes regularization losses and applies masking and sample weighting to the loss value.
Calculates the loss for a given model.
[ "Calculates", "the", "loss", "for", "a", "given", "model", "." ]
def _model_loss(model, inputs, targets, output_loss_metrics=None, sample_weights=None, training=False): """Calculates the loss for a given model. Arguments: model: The model on which metrics are being calculated. inputs: Either a dictionary of inputs to the model or a list of input arrays. targets: List of target arrays. output_loss_metrics: List of metrics that are used to aggregated output loss values. sample_weights: Optional list of sample weight arrays. training: Whether the model should be run in inference or training mode. Returns: Returns the model output, total loss, loss value calculated using the specified loss function and masks for each output. The total loss includes regularization losses and applies masking and sample weighting to the loss value. """ # TODO(psv): Dedup code here with graph mode prepare_total_loss() fn. # Used to keep track of the total loss value (stateless). # eg., total_loss = loss_weight_1 * output_1_loss_fn(...) + # loss_weight_2 * output_2_loss_fn(...) + # layer losses. total_loss = 0 kwargs = {} if model._expects_training_arg: kwargs['training'] = training if len(inputs) == 1 and not isinstance(inputs, dict): inputs = inputs[0] # Allow mixed `NumPy` and `EagerTensor` input here. if any( isinstance(input_t, (np.ndarray, float, int)) for input_t in nest.flatten(inputs)): inputs = nest.map_structure(ops.convert_to_tensor, inputs) outs = model(inputs, **kwargs) outs = nest.flatten(outs) if targets: targets = training_utils.cast_if_floating_dtype_and_mismatch(targets, outs) # TODO(sallymatson/psv): check if we should do same mismatch fix for weights if sample_weights: sample_weights = [ training_utils.cast_if_floating_dtype(ops.convert_to_tensor(val)) if val is not None else None for val in sample_weights ] masks = [getattr(t, '_keras_mask', None) for t in outs] targets = nest.flatten(targets) # Used to keep track of individual output losses. output_losses = [] with backend.name_scope('loss'): loss_fns = [ loss_fn for loss_fn in model.loss_functions if loss_fn is not None ] for i, loss_fn in enumerate(loss_fns): weights = sample_weights[i] if sample_weights else None mask = masks[i] with backend.name_scope(model.output_names[i] + '_loss'): if mask is not None: mask = math_ops.cast(mask, outs[i].dtype) # Update weights with mask. if weights is None: weights = mask else: # Update dimensions of weights to match with mask if possible. mask, _, weights = ( tf_losses_utils.squeeze_or_expand_dimensions( mask, sample_weight=weights)) weights *= mask if hasattr(loss_fn, 'reduction'): per_sample_losses = loss_fn.call(targets[i], outs[i]) weighted_losses = losses_utils.compute_weighted_loss( per_sample_losses, sample_weight=weights, reduction=losses_utils.ReductionV2.NONE) loss_reduction = loss_fn.reduction # `AUTO` loss reduction defaults to `SUM_OVER_BATCH_SIZE` for all # compile use cases. if loss_reduction == losses_utils.ReductionV2.AUTO: loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE # Compute the stateless loss value. output_loss = losses_utils.reduce_weighted_loss( weighted_losses, reduction=loss_reduction) else: # Compute the stateless loss value for a custom loss class. # Here we assume that the class takes care of loss reduction # because if this class returns a vector value we cannot # differentiate between use case where a custom optimizer # expects a vector loss value vs unreduced per-sample loss value. output_loss = loss_fn(targets[i], outs[i], sample_weight=weights) loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE # If the number of outputs is 1 then we don't append the loss metric # associated with each model output. When there are multiple outputs # associated with a model, each output's loss is calculated and returned # as part of the loss_metrics. if len(model.outputs) > 1: # Keep track of the stateful output loss result. output_losses.append(output_loss_metrics[i](output_loss)) # Scale output loss for distribution. For custom losses we assume # reduction was mean. if loss_reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE: output_loss = losses_utils.scale_loss_for_distribution(output_loss) total_loss += model._loss_weights_list[i] * output_loss # Add regularization losses custom_losses = model.losses if custom_losses: total_loss += losses_utils.scale_loss_for_distribution( math_ops.add_n(custom_losses)) return outs, total_loss, output_losses, masks
[ "def", "_model_loss", "(", "model", ",", "inputs", ",", "targets", ",", "output_loss_metrics", "=", "None", ",", "sample_weights", "=", "None", ",", "training", "=", "False", ")", ":", "# TODO(psv): Dedup code here with graph mode prepare_total_loss() fn.", "# Used to k...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_eager.py#L85-L210
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/xml/dom/expatbuilder.py
python
FragmentBuilder._getDeclarations
(self)
return s
Re-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string.
Re-create the internal subset from the DocumentType node.
[ "Re", "-", "create", "the", "internal", "subset", "from", "the", "DocumentType", "node", "." ]
def _getDeclarations(self): """Re-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string. """ doctype = self.context.ownerDocument.doctype s = "" if doctype: for i in range(doctype.notations.length): notation = doctype.notations.item(i) if s: s = s + "\n " s = "%s<!NOTATION %s" % (s, notation.nodeName) if notation.publicId: s = '%s PUBLIC "%s"\n "%s">' \ % (s, notation.publicId, notation.systemId) else: s = '%s SYSTEM "%s">' % (s, notation.systemId) for i in range(doctype.entities.length): entity = doctype.entities.item(i) if s: s = s + "\n " s = "%s<!ENTITY %s" % (s, entity.nodeName) if entity.publicId: s = '%s PUBLIC "%s"\n "%s"' \ % (s, entity.publicId, entity.systemId) elif entity.systemId: s = '%s SYSTEM "%s"' % (s, entity.systemId) else: s = '%s "%s"' % (s, entity.firstChild.data) if entity.notationName: s = "%s NOTATION %s" % (s, entity.notationName) s = s + ">" return s
[ "def", "_getDeclarations", "(", "self", ")", ":", "doctype", "=", "self", ".", "context", ".", "ownerDocument", ".", "doctype", "s", "=", "\"\"", "if", "doctype", ":", "for", "i", "in", "range", "(", "doctype", ".", "notations", ".", "length", ")", ":"...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/xml/dom/expatbuilder.py#L656-L690
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
vendor/pybind11/tools/clang/cindex.py
python
CompilationDatabase.fromDirectory
(buildDir)
return cdb
Builds a CompilationDatabase from the database found in buildDir
Builds a CompilationDatabase from the database found in buildDir
[ "Builds", "a", "CompilationDatabase", "from", "the", "database", "found", "in", "buildDir" ]
def fromDirectory(buildDir): """Builds a CompilationDatabase from the database found in buildDir""" errorCode = c_uint() try: cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir, byref(errorCode)) except CompilationDatabaseError as e: raise CompilationDatabaseError(int(errorCode.value), "CompilationDatabase loading failed") return cdb
[ "def", "fromDirectory", "(", "buildDir", ")", ":", "errorCode", "=", "c_uint", "(", ")", "try", ":", "cdb", "=", "conf", ".", "lib", ".", "clang_CompilationDatabase_fromDirectory", "(", "buildDir", ",", "byref", "(", "errorCode", ")", ")", "except", "Compila...
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L2950-L2959
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozbuild/base.py
python
MozbuildObject.config_environment
(self)
return self._config_environment
Returns the ConfigEnvironment for the current build configuration. This property is only available once configure has executed. If configure's output is not available, this will raise.
Returns the ConfigEnvironment for the current build configuration.
[ "Returns", "the", "ConfigEnvironment", "for", "the", "current", "build", "configuration", "." ]
def config_environment(self): """Returns the ConfigEnvironment for the current build configuration. This property is only available once configure has executed. If configure's output is not available, this will raise. """ if self._config_environment: return self._config_environment config_status = os.path.join(self.topobjdir, 'config.status') if not os.path.exists(config_status): raise Exception('config.status not available. Run configure.') self._config_environment = \ ConfigEnvironment.from_config_status(config_status) return self._config_environment
[ "def", "config_environment", "(", "self", ")", ":", "if", "self", ".", "_config_environment", ":", "return", "self", ".", "_config_environment", "config_status", "=", "os", ".", "path", ".", "join", "(", "self", ".", "topobjdir", ",", "'config.status'", ")", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/base.py#L243-L261
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/sets.py
python
Set.add
(self, element)
Add an element to a set. This has no effect if the element is already present.
Add an element to a set.
[ "Add", "an", "element", "to", "a", "set", "." ]
def add(self, element): """Add an element to a set. This has no effect if the element is already present. """ try: self._data[element] = True except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught self._data[transform()] = True
[ "def", "add", "(", "self", ",", "element", ")", ":", "try", ":", "self", ".", "_data", "[", "element", "]", "=", "True", "except", "TypeError", ":", "transform", "=", "getattr", "(", "element", ",", "\"__as_immutable__\"", ",", "None", ")", "if", "tran...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/sets.py#L521-L532
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_NV_UndefineSpaceSpecial_REQUEST.fromTpm
(buf)
return buf.createObj(TPM2_NV_UndefineSpaceSpecial_REQUEST)
Returns new TPM2_NV_UndefineSpaceSpecial_REQUEST object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new TPM2_NV_UndefineSpaceSpecial_REQUEST object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "TPM2_NV_UndefineSpaceSpecial_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new TPM2_NV_UndefineSpaceSpecial_REQUEST object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(TPM2_NV_UndefineSpaceSpecial_REQUEST)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "TPM2_NV_UndefineSpaceSpecial_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16663-L16667
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/boost/tools/build/src/build/targets.py
python
ProjectTarget.has_main_target
(self, name)
return name in self.main_target_
Tells if a main target with the specified name exists.
Tells if a main target with the specified name exists.
[ "Tells", "if", "a", "main", "target", "with", "the", "specified", "name", "exists", "." ]
def has_main_target (self, name): """Tells if a main target with the specified name exists.""" assert isinstance(name, basestring) if not self.built_main_targets_: self.build_main_targets() return name in self.main_target_
[ "def", "has_main_target", "(", "self", ",", "name", ")", ":", "assert", "isinstance", "(", "name", ",", "basestring", ")", "if", "not", "self", ".", "built_main_targets_", ":", "self", ".", "build_main_targets", "(", ")", "return", "name", "in", "self", "....
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/targets.py#L500-L506
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
txjsonrpc/jsonrpclib.py
python
ServerProxy.__request
(self, *args)
return response
Call a method on the remote server. XXX Is there any way to indicate that we'd want a notification request instead of a regular request?
Call a method on the remote server.
[ "Call", "a", "method", "on", "the", "remote", "server", "." ]
def __request(self, *args): """ Call a method on the remote server. XXX Is there any way to indicate that we'd want a notification request instead of a regular request? """ request = self._getVersionedRequest(*args) # XXX do a check here for id; if null, skip the response # XXX in order to do this effectively, we might have to change the # request functions to objects, so that we can get at an id attribute response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if len(response) == 1: response = response[0] return response
[ "def", "__request", "(", "self", ",", "*", "args", ")", ":", "request", "=", "self", ".", "_getVersionedRequest", "(", "*", "args", ")", "# XXX do a check here for id; if null, skip the response", "# XXX in order to do this effectively, we might have to change the", "# reques...
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/txjsonrpc/jsonrpclib.py#L164-L183
lhmRyan/deep-supervised-hashing-DSH
631901f82e2ab031fbac33f914a5b08ef8e21d57
python/caffe/detector.py
python
Detector.crop
(self, im, window)
return crop
Crop a window from the image for detection. Include surrounding context according to the `context_pad` configuration. Parameters ---------- im: H x W x K image ndarray to crop. window: bounding box coordinates as ymin, xmin, ymax, xmax. Returns ------- crop: cropped window.
Crop a window from the image for detection. Include surrounding context according to the `context_pad` configuration.
[ "Crop", "a", "window", "from", "the", "image", "for", "detection", ".", "Include", "surrounding", "context", "according", "to", "the", "context_pad", "configuration", "." ]
def crop(self, im, window): """ Crop a window from the image for detection. Include surrounding context according to the `context_pad` configuration. Parameters ---------- im: H x W x K image ndarray to crop. window: bounding box coordinates as ymin, xmin, ymax, xmax. Returns ------- crop: cropped window. """ # Crop window from the image. crop = im[window[0]:window[2], window[1]:window[3]] if self.context_pad: box = window.copy() crop_size = self.blobs[self.inputs[0]].width # assumes square scale = crop_size / (1. * crop_size - self.context_pad * 2) # Crop a box + surrounding context. half_h = (box[2] - box[0] + 1) / 2. half_w = (box[3] - box[1] + 1) / 2. center = (box[0] + half_h, box[1] + half_w) scaled_dims = scale * np.array((-half_h, -half_w, half_h, half_w)) box = np.round(np.tile(center, 2) + scaled_dims) full_h = box[2] - box[0] + 1 full_w = box[3] - box[1] + 1 scale_h = crop_size / full_h scale_w = crop_size / full_w pad_y = round(max(0, -box[0]) * scale_h) # amount out-of-bounds pad_x = round(max(0, -box[1]) * scale_w) # Clip box to image dimensions. im_h, im_w = im.shape[:2] box = np.clip(box, 0., [im_h, im_w, im_h, im_w]) clip_h = box[2] - box[0] + 1 clip_w = box[3] - box[1] + 1 assert(clip_h > 0 and clip_w > 0) crop_h = round(clip_h * scale_h) crop_w = round(clip_w * scale_w) if pad_y + crop_h > crop_size: crop_h = crop_size - pad_y if pad_x + crop_w > crop_size: crop_w = crop_size - pad_x # collect with context padding and place in input # with mean padding context_crop = im[box[0]:box[2], box[1]:box[3]] context_crop = caffe.io.resize_image(context_crop, (crop_h, crop_w)) crop = np.ones(self.crop_dims, dtype=np.float32) * self.crop_mean crop[pad_y:(pad_y + crop_h), pad_x:(pad_x + crop_w)] = context_crop return crop
[ "def", "crop", "(", "self", ",", "im", ",", "window", ")", ":", "# Crop window from the image.", "crop", "=", "im", "[", "window", "[", "0", "]", ":", "window", "[", "2", "]", ",", "window", "[", "1", "]", ":", "window", "[", "3", "]", "]", "if",...
https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/python/caffe/detector.py#L125-L179
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/calendar.py
python
HTMLCalendar.formatyearpage
(self, theyear, width=3, css='calendar.css', encoding=None)
return ''.join(v).encode(encoding, "xmlcharrefreplace")
Return a formatted year as a complete HTML page.
Return a formatted year as a complete HTML page.
[ "Return", "a", "formatted", "year", "as", "a", "complete", "HTML", "page", "." ]
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): """ Return a formatted year as a complete HTML page. """ if encoding is None: encoding = sys.getdefaultencoding() v = [] a = v.append a('<?xml version="1.0" encoding="%s"?>\n' % encoding) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) if css is not None: a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) a('<title>Calendar for %d</title>\n' % theyear) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding, "xmlcharrefreplace")
[ "def", "formatyearpage", "(", "self", ",", "theyear", ",", "width", "=", "3", ",", "css", "=", "'calendar.css'", ",", "encoding", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "sys", ".", "getdefaultencoding", "(", ")", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/calendar.py#L464-L485
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.quit
(self)
Quit the Tcl interpreter. All widgets will be destroyed.
Quit the Tcl interpreter. All widgets will be destroyed.
[ "Quit", "the", "Tcl", "interpreter", ".", "All", "widgets", "will", "be", "destroyed", "." ]
def quit(self): """Quit the Tcl interpreter. All widgets will be destroyed.""" self.tk.quit()
[ "def", "quit", "(", "self", ")", ":", "self", ".", "tk", ".", "quit", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1069-L1071
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/graph_actions.py
python
_write_summary_results
(output_dir, eval_results, current_global_step)
Writes eval results into summary file in given dir.
Writes eval results into summary file in given dir.
[ "Writes", "eval", "results", "into", "summary", "file", "in", "given", "dir", "." ]
def _write_summary_results(output_dir, eval_results, current_global_step): """Writes eval results into summary file in given dir.""" logging.info('Saving evaluation summary for step %d: %s', current_global_step, _eval_results_to_str(eval_results)) summary_writer = get_summary_writer(output_dir) summary = summary_pb2.Summary() for key in eval_results: if eval_results[key] is None: continue value = summary.value.add() value.tag = key if (isinstance(eval_results[key], np.float32) or isinstance(eval_results[key], float)): value.simple_value = float(eval_results[key]) else: logging.warn('Skipping summary for %s, must be a float or np.float32.', key) summary_writer.add_summary(summary, current_global_step) summary_writer.flush()
[ "def", "_write_summary_results", "(", "output_dir", ",", "eval_results", ",", "current_global_step", ")", ":", "logging", ".", "info", "(", "'Saving evaluation summary for step %d: %s'", ",", "current_global_step", ",", "_eval_results_to_str", "(", "eval_results", ")", ")...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/graph_actions.py#L456-L474
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py
python
AutoScaleConnection.create_or_update_tags
(self, tags)
return self.get_status('CreateOrUpdateTags', params, verb='POST')
Creates new tags or updates existing tags for an Auto Scaling group. :type tags: List of :class:`boto.ec2.autoscale.tag.Tag` :param tags: The new or updated tags.
Creates new tags or updates existing tags for an Auto Scaling group.
[ "Creates", "new", "tags", "or", "updates", "existing", "tags", "for", "an", "Auto", "Scaling", "group", "." ]
def create_or_update_tags(self, tags): """ Creates new tags or updates existing tags for an Auto Scaling group. :type tags: List of :class:`boto.ec2.autoscale.tag.Tag` :param tags: The new or updated tags. """ params = {} for i, tag in enumerate(tags): tag.build_params(params, i + 1) return self.get_status('CreateOrUpdateTags', params, verb='POST')
[ "def", "create_or_update_tags", "(", "self", ",", "tags", ")", ":", "params", "=", "{", "}", "for", "i", ",", "tag", "in", "enumerate", "(", "tags", ")", ":", "tag", ".", "build_params", "(", "params", ",", "i", "+", "1", ")", "return", "self", "."...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py#L873-L883
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
tools/onnx-graphsurgeon/onnx_graphsurgeon/logger/logger.py
python
Logger.register_callback
(self, callback)
Registers a callback with the logger, which will be invoked when the logging severity is modified. The callback is guaranteed to be called at least once in the register_callback function. Args: callback (Callable(Logger.Severity)): A callback that accepts the current logger severity.
Registers a callback with the logger, which will be invoked when the logging severity is modified. The callback is guaranteed to be called at least once in the register_callback function.
[ "Registers", "a", "callback", "with", "the", "logger", "which", "will", "be", "invoked", "when", "the", "logging", "severity", "is", "modified", ".", "The", "callback", "is", "guaranteed", "to", "be", "called", "at", "least", "once", "in", "the", "register_c...
def register_callback(self, callback): """ Registers a callback with the logger, which will be invoked when the logging severity is modified. The callback is guaranteed to be called at least once in the register_callback function. Args: callback (Callable(Logger.Severity)): A callback that accepts the current logger severity. """ callback(self._severity) self.logger_callbacks.append(callback)
[ "def", "register_callback", "(", "self", ",", "callback", ")", ":", "callback", "(", "self", ".", "_severity", ")", "self", ".", "logger_callbacks", ".", "append", "(", "callback", ")" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/onnx-graphsurgeon/onnx_graphsurgeon/logger/logger.py#L120-L129
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/simnet/train/tf/utils/datafeeds.py
python
TFPointwisePaddingData.ops
(self)
return dict([(k, features[k]) for k in self.left_slots.keys()]),\ dict([(k, features[k]) for k in self.right_slots.keys()]),\ features["label"]
gen data
gen data
[ "gen", "data" ]
def ops(self): """ gen data """ self.file_queue = tf.train.string_input_producer(self.filelist, num_epochs=self.epochs) self.reader = tf.TFRecordReader() _, example = self.reader.read(self.file_queue) batch_examples = load_batch_ops(example, self.batch_size, self.shuffle) features_types = {"label": tf.FixedLenFeature([2], tf.int64)} [features_types.update({u: tf.FixedLenFeature([v], tf.int64)}) for (u, v) in self.left_slots.iteritems()] [features_types.update({u: tf.FixedLenFeature([v], tf.int64)}) for (u, v) in self.right_slots.iteritems()] features = tf.parse_example(batch_examples, features = features_types) return dict([(k, features[k]) for k in self.left_slots.keys()]),\ dict([(k, features[k]) for k in self.right_slots.keys()]),\ features["label"]
[ "def", "ops", "(", "self", ")", ":", "self", ".", "file_queue", "=", "tf", ".", "train", ".", "string_input_producer", "(", "self", ".", "filelist", ",", "num_epochs", "=", "self", ".", "epochs", ")", "self", ".", "reader", "=", "tf", ".", "TFRecordRea...
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/tf/utils/datafeeds.py#L103-L120
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Geometry.AddPointZM
(self, *args, **kwargs)
return _ogr.Geometry_AddPointZM(self, *args, **kwargs)
r"""AddPointZM(Geometry self, double x, double y, double z, double m)
r"""AddPointZM(Geometry self, double x, double y, double z, double m)
[ "r", "AddPointZM", "(", "Geometry", "self", "double", "x", "double", "y", "double", "z", "double", "m", ")" ]
def AddPointZM(self, *args, **kwargs): r"""AddPointZM(Geometry self, double x, double y, double z, double m)""" return _ogr.Geometry_AddPointZM(self, *args, **kwargs)
[ "def", "AddPointZM", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_ogr", ".", "Geometry_AddPointZM", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L5866-L5868