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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sfzhang15/FaceBoxes | b52cc92f9362d3adc08d54666aeb9ebb62fdb7da | python/caffe/io.py | python | blobproto_to_array | (blob, return_diff=False) | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | [
"Convert",
"a",
"blob",
"proto",
"to",
"an",
"array",
".",
"In",
"default",
"we",
"will",
"just",
"return",
"the",
"data",
"unless",
"return_diff",
"is",
"True",
"in",
"which",
"case",
"we",
"will",
"return",
"the",
"diff",
"."
] | def blobproto_to_array(blob, return_diff=False):
"""
Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff.
"""
# Read the data into an array
if return_diff:
data = np.array(blob.diff)
else:
data = np.array(blob.data)
# Reshape the array
if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'):
# Use legacy 4D shape
return data.reshape(blob.num, blob.channels, blob.height, blob.width)
else:
return data.reshape(blob.shape.dim) | [
"def",
"blobproto_to_array",
"(",
"blob",
",",
"return_diff",
"=",
"False",
")",
":",
"# Read the data into an array",
"if",
"return_diff",
":",
"data",
"=",
"np",
".",
"array",
"(",
"blob",
".",
"diff",
")",
"else",
":",
"data",
"=",
"np",
".",
"array",
"(",
"blob",
".",
"data",
")",
"# Reshape the array",
"if",
"blob",
".",
"HasField",
"(",
"'num'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'channels'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'height'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'width'",
")",
":",
"# Use legacy 4D shape",
"return",
"data",
".",
"reshape",
"(",
"blob",
".",
"num",
",",
"blob",
".",
"channels",
",",
"blob",
".",
"height",
",",
"blob",
".",
"width",
")",
"else",
":",
"return",
"data",
".",
"reshape",
"(",
"blob",
".",
"shape",
".",
"dim",
")"
] | https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/python/caffe/io.py#L18-L34 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/ISISDirecInelasticConfig.py | python | UserProperties.rb_folder | (self) | Returns short name of user's RB folder
consisting of string RB and string representation of
RB number e.g. RB1510324 | Returns short name of user's RB folder
consisting of string RB and string representation of
RB number e.g. RB1510324 | [
"Returns",
"short",
"name",
"of",
"user",
"s",
"RB",
"folder",
"consisting",
"of",
"string",
"RB",
"and",
"string",
"representation",
"of",
"RB",
"number",
"e",
".",
"g",
".",
"RB1510324"
] | def rb_folder(self):
"""Returns short name of user's RB folder
consisting of string RB and string representation of
RB number e.g. RB1510324
"""
if self._user_id:
RBfolder = os.path.basename(self.rb_dir)
return RBfolder
else:
return None | [
"def",
"rb_folder",
"(",
"self",
")",
":",
"if",
"self",
".",
"_user_id",
":",
"RBfolder",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"rb_dir",
")",
"return",
"RBfolder",
"else",
":",
"return",
"None"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py#L132-L141 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py | python | TurtleScreenBase._blankimage | () | return img | return a blank image object | return a blank image object | [
"return",
"a",
"blank",
"image",
"object"
] | def _blankimage():
"""return a blank image object
"""
img = TK.PhotoImage(width=1, height=1)
img.blank()
return img | [
"def",
"_blankimage",
"(",
")",
":",
"img",
"=",
"TK",
".",
"PhotoImage",
"(",
"width",
"=",
"1",
",",
"height",
"=",
"1",
")",
"img",
".",
"blank",
"(",
")",
"return",
"img"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py#L467-L472 | |
mysql/mysql-workbench | 2f35f9034f015cbcd22139a60e1baa2e3e8e795c | modules/db.sqlite/db_sqlite_re_grt.py | python | SQLiteReverseEngineering.getSchemaNames | (cls, connection, catalog_name) | return [os.path.splitext(os.path.basename(connection.parameterValues['dbfile']))[0]] | Returns a list of schemata for the given connection object. | Returns a list of schemata for the given connection object. | [
"Returns",
"a",
"list",
"of",
"schemata",
"for",
"the",
"given",
"connection",
"object",
"."
] | def getSchemaNames(cls, connection, catalog_name):
"""Returns a list of schemata for the given connection object."""
return [os.path.splitext(os.path.basename(connection.parameterValues['dbfile']))[0]] | [
"def",
"getSchemaNames",
"(",
"cls",
",",
"connection",
",",
"catalog_name",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"connection",
".",
"parameterValues",
"[",
"'dbfile'",
"]",
")",
")",
"[",
"0",
"]",
"]"
] | https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/modules/db.sqlite/db_sqlite_re_grt.py#L95-L98 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/plugins/filebrowser/filebrowser/browser.py | python | FileBrowser2.DoBeginEdit | (self, item) | return True | Handle when an item is requested to be edited | Handle when an item is requested to be edited | [
"Handle",
"when",
"an",
"item",
"is",
"requested",
"to",
"be",
"edited"
] | def DoBeginEdit(self, item):
"""Handle when an item is requested to be edited"""
d = None
try:
d = self.GetPyData(item)
except wx.PyAssertionError:
util.Log("[FileBrowser][err] FileBrowser2.DoItemExpanding")
return False
if d and not os.access(d, os.W_OK) or os.path.ismount(d):
return False
return True | [
"def",
"DoBeginEdit",
"(",
"self",
",",
"item",
")",
":",
"d",
"=",
"None",
"try",
":",
"d",
"=",
"self",
".",
"GetPyData",
"(",
"item",
")",
"except",
"wx",
".",
"PyAssertionError",
":",
"util",
".",
"Log",
"(",
"\"[FileBrowser][err] FileBrowser2.DoItemExpanding\"",
")",
"return",
"False",
"if",
"d",
"and",
"not",
"os",
".",
"access",
"(",
"d",
",",
"os",
".",
"W_OK",
")",
"or",
"os",
".",
"path",
".",
"ismount",
"(",
"d",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/filebrowser/filebrowser/browser.py#L627-L637 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/TorsionFingerprints.py | python | _getBondsForTorsions | (mol, ignoreColinearBonds) | return bonds | Determine the bonds (or pair of atoms treated like a bond) for which
torsions should be calculated.
Arguments:
- refmol: the molecule of interest
- ignoreColinearBonds: if True (default), single bonds adjacent to
triple bonds are ignored
if False, alternative not-covalently bound
atoms are used to define the torsion | Determine the bonds (or pair of atoms treated like a bond) for which
torsions should be calculated. | [
"Determine",
"the",
"bonds",
"(",
"or",
"pair",
"of",
"atoms",
"treated",
"like",
"a",
"bond",
")",
"for",
"which",
"torsions",
"should",
"be",
"calculated",
"."
] | def _getBondsForTorsions(mol, ignoreColinearBonds):
""" Determine the bonds (or pair of atoms treated like a bond) for which
torsions should be calculated.
Arguments:
- refmol: the molecule of interest
- ignoreColinearBonds: if True (default), single bonds adjacent to
triple bonds are ignored
if False, alternative not-covalently bound
atoms are used to define the torsion
"""
# flag the atoms that cannot be part of the centre atoms of a torsion
# patterns: triple bonds and allenes
patts = [Chem.MolFromSmarts(x) for x in ['*#*', '[$([C](=*)=*)]']]
atomFlags = [0] * mol.GetNumAtoms()
for p in patts:
if mol.HasSubstructMatch(p):
matches = mol.GetSubstructMatches(p)
for match in matches:
for a in match:
atomFlags[a] = 1
bonds = []
doneBonds = [0] * mol.GetNumBonds()
for b in mol.GetBonds():
if b.IsInRing():
continue
a1 = b.GetBeginAtomIdx()
a2 = b.GetEndAtomIdx()
nb1 = _getHeavyAtomNeighbors(b.GetBeginAtom(), a2)
nb2 = _getHeavyAtomNeighbors(b.GetEndAtom(), a1)
if not doneBonds[b.GetIdx()] and (nb1 and nb2): # no terminal bonds
doneBonds[b.GetIdx()] = 1
# check if atoms cannot be middle atoms
if atomFlags[a1] or atomFlags[a2]:
if not ignoreColinearBonds: # search for alternative not-covalently bound atoms
while len(nb1) == 1 and atomFlags[a1]:
a1old = a1
a1 = nb1[0].GetIdx()
b = mol.GetBondBetweenAtoms(a1old, a1)
if b.GetEndAtom().GetIdx() == a1old:
nb1 = _getHeavyAtomNeighbors(b.GetBeginAtom(), a1old)
else:
nb1 = _getHeavyAtomNeighbors(b.GetEndAtom(), a1old)
doneBonds[b.GetIdx()] = 1
while len(nb2) == 1 and atomFlags[a2]:
doneBonds[b.GetIdx()] = 1
a2old = a2
a2 = nb2[0].GetIdx()
b = mol.GetBondBetweenAtoms(a2old, a2)
if b.GetBeginAtom().GetIdx() == a2old:
nb2 = _getHeavyAtomNeighbors(b.GetEndAtom(), a2old)
else:
nb2 = _getHeavyAtomNeighbors(b.GetBeginAtom(), a2old)
doneBonds[b.GetIdx()] = 1
if nb1 and nb2:
bonds.append((a1, a2, nb1, nb2))
else:
bonds.append((a1, a2, nb1, nb2))
return bonds | [
"def",
"_getBondsForTorsions",
"(",
"mol",
",",
"ignoreColinearBonds",
")",
":",
"# flag the atoms that cannot be part of the centre atoms of a torsion",
"# patterns: triple bonds and allenes",
"patts",
"=",
"[",
"Chem",
".",
"MolFromSmarts",
"(",
"x",
")",
"for",
"x",
"in",
"[",
"'*#*'",
",",
"'[$([C](=*)=*)]'",
"]",
"]",
"atomFlags",
"=",
"[",
"0",
"]",
"*",
"mol",
".",
"GetNumAtoms",
"(",
")",
"for",
"p",
"in",
"patts",
":",
"if",
"mol",
".",
"HasSubstructMatch",
"(",
"p",
")",
":",
"matches",
"=",
"mol",
".",
"GetSubstructMatches",
"(",
"p",
")",
"for",
"match",
"in",
"matches",
":",
"for",
"a",
"in",
"match",
":",
"atomFlags",
"[",
"a",
"]",
"=",
"1",
"bonds",
"=",
"[",
"]",
"doneBonds",
"=",
"[",
"0",
"]",
"*",
"mol",
".",
"GetNumBonds",
"(",
")",
"for",
"b",
"in",
"mol",
".",
"GetBonds",
"(",
")",
":",
"if",
"b",
".",
"IsInRing",
"(",
")",
":",
"continue",
"a1",
"=",
"b",
".",
"GetBeginAtomIdx",
"(",
")",
"a2",
"=",
"b",
".",
"GetEndAtomIdx",
"(",
")",
"nb1",
"=",
"_getHeavyAtomNeighbors",
"(",
"b",
".",
"GetBeginAtom",
"(",
")",
",",
"a2",
")",
"nb2",
"=",
"_getHeavyAtomNeighbors",
"(",
"b",
".",
"GetEndAtom",
"(",
")",
",",
"a1",
")",
"if",
"not",
"doneBonds",
"[",
"b",
".",
"GetIdx",
"(",
")",
"]",
"and",
"(",
"nb1",
"and",
"nb2",
")",
":",
"# no terminal bonds",
"doneBonds",
"[",
"b",
".",
"GetIdx",
"(",
")",
"]",
"=",
"1",
"# check if atoms cannot be middle atoms",
"if",
"atomFlags",
"[",
"a1",
"]",
"or",
"atomFlags",
"[",
"a2",
"]",
":",
"if",
"not",
"ignoreColinearBonds",
":",
"# search for alternative not-covalently bound atoms",
"while",
"len",
"(",
"nb1",
")",
"==",
"1",
"and",
"atomFlags",
"[",
"a1",
"]",
":",
"a1old",
"=",
"a1",
"a1",
"=",
"nb1",
"[",
"0",
"]",
".",
"GetIdx",
"(",
")",
"b",
"=",
"mol",
".",
"GetBondBetweenAtoms",
"(",
"a1old",
",",
"a1",
")",
"if",
"b",
".",
"GetEndAtom",
"(",
")",
".",
"GetIdx",
"(",
")",
"==",
"a1old",
":",
"nb1",
"=",
"_getHeavyAtomNeighbors",
"(",
"b",
".",
"GetBeginAtom",
"(",
")",
",",
"a1old",
")",
"else",
":",
"nb1",
"=",
"_getHeavyAtomNeighbors",
"(",
"b",
".",
"GetEndAtom",
"(",
")",
",",
"a1old",
")",
"doneBonds",
"[",
"b",
".",
"GetIdx",
"(",
")",
"]",
"=",
"1",
"while",
"len",
"(",
"nb2",
")",
"==",
"1",
"and",
"atomFlags",
"[",
"a2",
"]",
":",
"doneBonds",
"[",
"b",
".",
"GetIdx",
"(",
")",
"]",
"=",
"1",
"a2old",
"=",
"a2",
"a2",
"=",
"nb2",
"[",
"0",
"]",
".",
"GetIdx",
"(",
")",
"b",
"=",
"mol",
".",
"GetBondBetweenAtoms",
"(",
"a2old",
",",
"a2",
")",
"if",
"b",
".",
"GetBeginAtom",
"(",
")",
".",
"GetIdx",
"(",
")",
"==",
"a2old",
":",
"nb2",
"=",
"_getHeavyAtomNeighbors",
"(",
"b",
".",
"GetEndAtom",
"(",
")",
",",
"a2old",
")",
"else",
":",
"nb2",
"=",
"_getHeavyAtomNeighbors",
"(",
"b",
".",
"GetBeginAtom",
"(",
")",
",",
"a2old",
")",
"doneBonds",
"[",
"b",
".",
"GetIdx",
"(",
")",
"]",
"=",
"1",
"if",
"nb1",
"and",
"nb2",
":",
"bonds",
".",
"append",
"(",
"(",
"a1",
",",
"a2",
",",
"nb1",
",",
"nb2",
")",
")",
"else",
":",
"bonds",
".",
"append",
"(",
"(",
"a1",
",",
"a2",
",",
"nb1",
",",
"nb2",
")",
")",
"return",
"bonds"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/TorsionFingerprints.py#L146-L206 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/sparse/extract.py | python | tril | (A, k=0, format=None) | return _masked_coo(A, mask).asformat(format) | Return the lower triangular portion of a matrix in sparse format
Returns the elements on or below the k-th diagonal of the matrix A.
- k = 0 corresponds to the main diagonal
- k > 0 is above the main diagonal
- k < 0 is below the main diagonal
Parameters
----------
A : dense or sparse matrix
Matrix whose lower trianglar portion is desired.
k : integer : optional
The top-most diagonal of the lower triangle.
format : string
Sparse format of the result, e.g. format="csr", etc.
Returns
-------
L : sparse matrix
Lower triangular portion of A in sparse format.
See Also
--------
triu : upper triangle in sparse format
Examples
--------
>>> from scipy.sparse import csr_matrix, tril
>>> A = csr_matrix([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
... dtype='int32')
>>> A.toarray()
array([[1, 2, 0, 0, 3],
[4, 5, 0, 6, 7],
[0, 0, 8, 9, 0]])
>>> tril(A).toarray()
array([[1, 0, 0, 0, 0],
[4, 5, 0, 0, 0],
[0, 0, 8, 0, 0]])
>>> tril(A).nnz
4
>>> tril(A, k=1).toarray()
array([[1, 2, 0, 0, 0],
[4, 5, 0, 0, 0],
[0, 0, 8, 9, 0]])
>>> tril(A, k=-1).toarray()
array([[0, 0, 0, 0, 0],
[4, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
>>> tril(A, format='csc')
<3x5 sparse matrix of type '<type 'numpy.int32'>'
with 4 stored elements in Compressed Sparse Column format> | Return the lower triangular portion of a matrix in sparse format | [
"Return",
"the",
"lower",
"triangular",
"portion",
"of",
"a",
"matrix",
"in",
"sparse",
"format"
] | def tril(A, k=0, format=None):
"""Return the lower triangular portion of a matrix in sparse format
Returns the elements on or below the k-th diagonal of the matrix A.
- k = 0 corresponds to the main diagonal
- k > 0 is above the main diagonal
- k < 0 is below the main diagonal
Parameters
----------
A : dense or sparse matrix
Matrix whose lower trianglar portion is desired.
k : integer : optional
The top-most diagonal of the lower triangle.
format : string
Sparse format of the result, e.g. format="csr", etc.
Returns
-------
L : sparse matrix
Lower triangular portion of A in sparse format.
See Also
--------
triu : upper triangle in sparse format
Examples
--------
>>> from scipy.sparse import csr_matrix, tril
>>> A = csr_matrix([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
... dtype='int32')
>>> A.toarray()
array([[1, 2, 0, 0, 3],
[4, 5, 0, 6, 7],
[0, 0, 8, 9, 0]])
>>> tril(A).toarray()
array([[1, 0, 0, 0, 0],
[4, 5, 0, 0, 0],
[0, 0, 8, 0, 0]])
>>> tril(A).nnz
4
>>> tril(A, k=1).toarray()
array([[1, 2, 0, 0, 0],
[4, 5, 0, 0, 0],
[0, 0, 8, 9, 0]])
>>> tril(A, k=-1).toarray()
array([[0, 0, 0, 0, 0],
[4, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
>>> tril(A, format='csc')
<3x5 sparse matrix of type '<type 'numpy.int32'>'
with 4 stored elements in Compressed Sparse Column format>
"""
# convert to COOrdinate format where things are easy
A = coo_matrix(A, copy=False)
mask = A.row + k >= A.col
return _masked_coo(A, mask).asformat(format) | [
"def",
"tril",
"(",
"A",
",",
"k",
"=",
"0",
",",
"format",
"=",
"None",
")",
":",
"# convert to COOrdinate format where things are easy",
"A",
"=",
"coo_matrix",
"(",
"A",
",",
"copy",
"=",
"False",
")",
"mask",
"=",
"A",
".",
"row",
"+",
"k",
">=",
"A",
".",
"col",
"return",
"_masked_coo",
"(",
"A",
",",
"mask",
")",
".",
"asformat",
"(",
"format",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/extract.py#L45-L103 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/base_preprocessing_layer.py | python | convert_to_list | (values, sparse_default_value=None) | return values | Convert a TensorLike, CompositeTensor, or ndarray into a Python list. | Convert a TensorLike, CompositeTensor, or ndarray into a Python list. | [
"Convert",
"a",
"TensorLike",
"CompositeTensor",
"or",
"ndarray",
"into",
"a",
"Python",
"list",
"."
] | def convert_to_list(values, sparse_default_value=None):
"""Convert a TensorLike, CompositeTensor, or ndarray into a Python list."""
if tf_utils.is_ragged(values):
# There is a corner case when dealing with ragged tensors: if you get an
# actual RaggedTensor (not a RaggedTensorValue) passed in non-eager mode,
# you can't call to_list() on it without evaluating it first. However,
# because we don't yet fully support composite tensors across Keras,
# backend.get_value() won't evaluate the tensor.
# TODO(momernick): Get Keras to recognize composite tensors as Tensors
# and then replace this with a call to backend.get_value.
if (isinstance(values, ragged_tensor.RaggedTensor) and
not context.executing_eagerly()):
values = backend.get_session(values).run(values)
values = values.to_list()
if isinstance(values,
(sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):
if sparse_default_value is None:
if dtypes.as_dtype(values.values.dtype) == dtypes.string:
sparse_default_value = ''
else:
sparse_default_value = -1
dense_tensor = sparse_ops.sparse_tensor_to_dense(
values, default_value=sparse_default_value)
values = backend.get_value(dense_tensor)
if isinstance(values, ops.Tensor):
values = backend.get_value(values)
# We may get passed a ndarray or the code above may give us a ndarray.
# In either case, we want to force it into a standard python list.
if isinstance(values, np.ndarray):
values = values.tolist()
return values | [
"def",
"convert_to_list",
"(",
"values",
",",
"sparse_default_value",
"=",
"None",
")",
":",
"if",
"tf_utils",
".",
"is_ragged",
"(",
"values",
")",
":",
"# There is a corner case when dealing with ragged tensors: if you get an",
"# actual RaggedTensor (not a RaggedTensorValue) passed in non-eager mode,",
"# you can't call to_list() on it without evaluating it first. However,",
"# because we don't yet fully support composite tensors across Keras,",
"# backend.get_value() won't evaluate the tensor.",
"# TODO(momernick): Get Keras to recognize composite tensors as Tensors",
"# and then replace this with a call to backend.get_value.",
"if",
"(",
"isinstance",
"(",
"values",
",",
"ragged_tensor",
".",
"RaggedTensor",
")",
"and",
"not",
"context",
".",
"executing_eagerly",
"(",
")",
")",
":",
"values",
"=",
"backend",
".",
"get_session",
"(",
"values",
")",
".",
"run",
"(",
"values",
")",
"values",
"=",
"values",
".",
"to_list",
"(",
")",
"if",
"isinstance",
"(",
"values",
",",
"(",
"sparse_tensor",
".",
"SparseTensor",
",",
"sparse_tensor",
".",
"SparseTensorValue",
")",
")",
":",
"if",
"sparse_default_value",
"is",
"None",
":",
"if",
"dtypes",
".",
"as_dtype",
"(",
"values",
".",
"values",
".",
"dtype",
")",
"==",
"dtypes",
".",
"string",
":",
"sparse_default_value",
"=",
"''",
"else",
":",
"sparse_default_value",
"=",
"-",
"1",
"dense_tensor",
"=",
"sparse_ops",
".",
"sparse_tensor_to_dense",
"(",
"values",
",",
"default_value",
"=",
"sparse_default_value",
")",
"values",
"=",
"backend",
".",
"get_value",
"(",
"dense_tensor",
")",
"if",
"isinstance",
"(",
"values",
",",
"ops",
".",
"Tensor",
")",
":",
"values",
"=",
"backend",
".",
"get_value",
"(",
"values",
")",
"# We may get passed a ndarray or the code above may give us a ndarray.",
"# In either case, we want to force it into a standard python list.",
"if",
"isinstance",
"(",
"values",
",",
"np",
".",
"ndarray",
")",
":",
"values",
"=",
"values",
".",
"tolist",
"(",
")",
"return",
"values"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/base_preprocessing_layer.py#L445-L479 | |
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/xcodeproj_file.py | python | PBXGroup.AddOrGetFileByPath | (self, path, hierarchical) | Returns an existing or new file reference corresponding to path.
If hierarchical is True, this method will create or use the necessary
hierarchical group structure corresponding to path. Otherwise, it will
look in and create an item in the current group only.
If an existing matching reference is found, it is returned, otherwise, a
new one will be created, added to the correct group, and returned.
If path identifies a directory by virtue of carrying a trailing slash,
this method returns a PBXFileReference of "folder" type. If path
identifies a variant, by virtue of it identifying a file inside a directory
with an ".lproj" extension, this method returns a PBXVariantGroup
containing the variant named by path, and possibly other variants. For
all other paths, a "normal" PBXFileReference will be returned. | Returns an existing or new file reference corresponding to path. | [
"Returns",
"an",
"existing",
"or",
"new",
"file",
"reference",
"corresponding",
"to",
"path",
"."
] | def AddOrGetFileByPath(self, path, hierarchical):
"""Returns an existing or new file reference corresponding to path.
If hierarchical is True, this method will create or use the necessary
hierarchical group structure corresponding to path. Otherwise, it will
look in and create an item in the current group only.
If an existing matching reference is found, it is returned, otherwise, a
new one will be created, added to the correct group, and returned.
If path identifies a directory by virtue of carrying a trailing slash,
this method returns a PBXFileReference of "folder" type. If path
identifies a variant, by virtue of it identifying a file inside a directory
with an ".lproj" extension, this method returns a PBXVariantGroup
containing the variant named by path, and possibly other variants. For
all other paths, a "normal" PBXFileReference will be returned.
"""
# Adding or getting a directory? Directories end with a trailing slash.
is_dir = False
if path.endswith('/'):
is_dir = True
path = posixpath.normpath(path)
if is_dir:
path = path + '/'
# Adding or getting a variant? Variants are files inside directories
# with an ".lproj" extension. Xcode uses variants for localization. For
# a variant path/to/Language.lproj/MainMenu.nib, put a variant group named
# MainMenu.nib inside path/to, and give it a variant named Language. In
# this example, grandparent would be set to path/to and parent_root would
# be set to Language.
variant_name = None
parent = posixpath.dirname(path)
grandparent = posixpath.dirname(parent)
parent_basename = posixpath.basename(parent)
(parent_root, parent_ext) = posixpath.splitext(parent_basename)
if parent_ext == '.lproj':
variant_name = parent_root
if grandparent == '':
grandparent = None
# Putting a directory inside a variant group is not currently supported.
assert not is_dir or variant_name is None
path_split = path.split(posixpath.sep)
if len(path_split) == 1 or \
((is_dir or variant_name != None) and len(path_split) == 2) or \
not hierarchical:
# The PBXFileReference or PBXVariantGroup will be added to or gotten from
# this PBXGroup, no recursion necessary.
if variant_name is None:
# Add or get a PBXFileReference.
file_ref = self.GetChildByPath(path)
if file_ref != None:
assert file_ref.__class__ == PBXFileReference
else:
file_ref = PBXFileReference({'path': path})
self.AppendChild(file_ref)
else:
# Add or get a PBXVariantGroup. The variant group name is the same
# as the basename (MainMenu.nib in the example above). grandparent
# specifies the path to the variant group itself, and path_split[-2:]
# is the path of the specific variant relative to its group.
variant_group_name = posixpath.basename(path)
variant_group_ref = self.AddOrGetVariantGroupByNameAndPath(
variant_group_name, grandparent)
variant_path = posixpath.sep.join(path_split[-2:])
variant_ref = variant_group_ref.GetChildByPath(variant_path)
if variant_ref != None:
assert variant_ref.__class__ == PBXFileReference
else:
variant_ref = PBXFileReference({'name': variant_name,
'path': variant_path})
variant_group_ref.AppendChild(variant_ref)
# The caller is interested in the variant group, not the specific
# variant file.
file_ref = variant_group_ref
return file_ref
else:
# Hierarchical recursion. Add or get a PBXGroup corresponding to the
# outermost path component, and then recurse into it, chopping off that
# path component.
next_dir = path_split[0]
group_ref = self.GetChildByPath(next_dir)
if group_ref != None:
assert group_ref.__class__ == PBXGroup
else:
group_ref = PBXGroup({'path': next_dir})
self.AppendChild(group_ref)
return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]),
hierarchical) | [
"def",
"AddOrGetFileByPath",
"(",
"self",
",",
"path",
",",
"hierarchical",
")",
":",
"# Adding or getting a directory? Directories end with a trailing slash.",
"is_dir",
"=",
"False",
"if",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"is_dir",
"=",
"True",
"path",
"=",
"posixpath",
".",
"normpath",
"(",
"path",
")",
"if",
"is_dir",
":",
"path",
"=",
"path",
"+",
"'/'",
"# Adding or getting a variant? Variants are files inside directories",
"# with an \".lproj\" extension. Xcode uses variants for localization. For",
"# a variant path/to/Language.lproj/MainMenu.nib, put a variant group named",
"# MainMenu.nib inside path/to, and give it a variant named Language. In",
"# this example, grandparent would be set to path/to and parent_root would",
"# be set to Language.",
"variant_name",
"=",
"None",
"parent",
"=",
"posixpath",
".",
"dirname",
"(",
"path",
")",
"grandparent",
"=",
"posixpath",
".",
"dirname",
"(",
"parent",
")",
"parent_basename",
"=",
"posixpath",
".",
"basename",
"(",
"parent",
")",
"(",
"parent_root",
",",
"parent_ext",
")",
"=",
"posixpath",
".",
"splitext",
"(",
"parent_basename",
")",
"if",
"parent_ext",
"==",
"'.lproj'",
":",
"variant_name",
"=",
"parent_root",
"if",
"grandparent",
"==",
"''",
":",
"grandparent",
"=",
"None",
"# Putting a directory inside a variant group is not currently supported.",
"assert",
"not",
"is_dir",
"or",
"variant_name",
"is",
"None",
"path_split",
"=",
"path",
".",
"split",
"(",
"posixpath",
".",
"sep",
")",
"if",
"len",
"(",
"path_split",
")",
"==",
"1",
"or",
"(",
"(",
"is_dir",
"or",
"variant_name",
"!=",
"None",
")",
"and",
"len",
"(",
"path_split",
")",
"==",
"2",
")",
"or",
"not",
"hierarchical",
":",
"# The PBXFileReference or PBXVariantGroup will be added to or gotten from",
"# this PBXGroup, no recursion necessary.",
"if",
"variant_name",
"is",
"None",
":",
"# Add or get a PBXFileReference.",
"file_ref",
"=",
"self",
".",
"GetChildByPath",
"(",
"path",
")",
"if",
"file_ref",
"!=",
"None",
":",
"assert",
"file_ref",
".",
"__class__",
"==",
"PBXFileReference",
"else",
":",
"file_ref",
"=",
"PBXFileReference",
"(",
"{",
"'path'",
":",
"path",
"}",
")",
"self",
".",
"AppendChild",
"(",
"file_ref",
")",
"else",
":",
"# Add or get a PBXVariantGroup. The variant group name is the same",
"# as the basename (MainMenu.nib in the example above). grandparent",
"# specifies the path to the variant group itself, and path_split[-2:]",
"# is the path of the specific variant relative to its group.",
"variant_group_name",
"=",
"posixpath",
".",
"basename",
"(",
"path",
")",
"variant_group_ref",
"=",
"self",
".",
"AddOrGetVariantGroupByNameAndPath",
"(",
"variant_group_name",
",",
"grandparent",
")",
"variant_path",
"=",
"posixpath",
".",
"sep",
".",
"join",
"(",
"path_split",
"[",
"-",
"2",
":",
"]",
")",
"variant_ref",
"=",
"variant_group_ref",
".",
"GetChildByPath",
"(",
"variant_path",
")",
"if",
"variant_ref",
"!=",
"None",
":",
"assert",
"variant_ref",
".",
"__class__",
"==",
"PBXFileReference",
"else",
":",
"variant_ref",
"=",
"PBXFileReference",
"(",
"{",
"'name'",
":",
"variant_name",
",",
"'path'",
":",
"variant_path",
"}",
")",
"variant_group_ref",
".",
"AppendChild",
"(",
"variant_ref",
")",
"# The caller is interested in the variant group, not the specific",
"# variant file.",
"file_ref",
"=",
"variant_group_ref",
"return",
"file_ref",
"else",
":",
"# Hierarchical recursion. Add or get a PBXGroup corresponding to the",
"# outermost path component, and then recurse into it, chopping off that",
"# path component.",
"next_dir",
"=",
"path_split",
"[",
"0",
"]",
"group_ref",
"=",
"self",
".",
"GetChildByPath",
"(",
"next_dir",
")",
"if",
"group_ref",
"!=",
"None",
":",
"assert",
"group_ref",
".",
"__class__",
"==",
"PBXGroup",
"else",
":",
"group_ref",
"=",
"PBXGroup",
"(",
"{",
"'path'",
":",
"next_dir",
"}",
")",
"self",
".",
"AppendChild",
"(",
"group_ref",
")",
"return",
"group_ref",
".",
"AddOrGetFileByPath",
"(",
"posixpath",
".",
"sep",
".",
"join",
"(",
"path_split",
"[",
"1",
":",
"]",
")",
",",
"hierarchical",
")"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcodeproj_file.py#L1180-L1271 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/Codegen.py | python | CGNativeMember.getArg | (self, arg) | return Argument(decl.define(), arg.identifier.name) | Get the full argument declaration for an argument | Get the full argument declaration for an argument | [
"Get",
"the",
"full",
"argument",
"declaration",
"for",
"an",
"argument"
] | def getArg(self, arg):
"""
Get the full argument declaration for an argument
"""
decl, ref = self.getArgType(arg.type, arg.canHaveMissingValue(),
"Variadic" if arg.variadic else False)
if ref:
decl = CGWrapper(decl, pre="const ", post="&")
return Argument(decl.define(), arg.identifier.name) | [
"def",
"getArg",
"(",
"self",
",",
"arg",
")",
":",
"decl",
",",
"ref",
"=",
"self",
".",
"getArgType",
"(",
"arg",
".",
"type",
",",
"arg",
".",
"canHaveMissingValue",
"(",
")",
",",
"\"Variadic\"",
"if",
"arg",
".",
"variadic",
"else",
"False",
")",
"if",
"ref",
":",
"decl",
"=",
"CGWrapper",
"(",
"decl",
",",
"pre",
"=",
"\"const \"",
",",
"post",
"=",
"\"&\"",
")",
"return",
"Argument",
"(",
"decl",
".",
"define",
"(",
")",
",",
"arg",
".",
"identifier",
".",
"name",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/Codegen.py#L12545-L12554 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/converter.py | python | _get_default_annual_spacing | (nyears) | return (min_spacing, maj_spacing) | Returns a default spacing between consecutive ticks for annual data. | Returns a default spacing between consecutive ticks for annual data. | [
"Returns",
"a",
"default",
"spacing",
"between",
"consecutive",
"ticks",
"for",
"annual",
"data",
"."
] | def _get_default_annual_spacing(nyears):
"""
Returns a default spacing between consecutive ticks for annual data.
"""
if nyears < 11:
(min_spacing, maj_spacing) = (1, 1)
elif nyears < 20:
(min_spacing, maj_spacing) = (1, 2)
elif nyears < 50:
(min_spacing, maj_spacing) = (1, 5)
elif nyears < 100:
(min_spacing, maj_spacing) = (5, 10)
elif nyears < 200:
(min_spacing, maj_spacing) = (5, 25)
elif nyears < 600:
(min_spacing, maj_spacing) = (10, 50)
else:
factor = nyears // 1000 + 1
(min_spacing, maj_spacing) = (factor * 20, factor * 100)
return (min_spacing, maj_spacing) | [
"def",
"_get_default_annual_spacing",
"(",
"nyears",
")",
":",
"if",
"nyears",
"<",
"11",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"1",
",",
"1",
")",
"elif",
"nyears",
"<",
"20",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"1",
",",
"2",
")",
"elif",
"nyears",
"<",
"50",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"1",
",",
"5",
")",
"elif",
"nyears",
"<",
"100",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"5",
",",
"10",
")",
"elif",
"nyears",
"<",
"200",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"5",
",",
"25",
")",
"elif",
"nyears",
"<",
"600",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"10",
",",
"50",
")",
"else",
":",
"factor",
"=",
"nyears",
"//",
"1000",
"+",
"1",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"factor",
"*",
"20",
",",
"factor",
"*",
"100",
")",
"return",
"(",
"min_spacing",
",",
"maj_spacing",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/converter.py#L511-L530 | |
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | python/ola/OlaClient.py | python | OlaClient.SetUniverseName | (self, universe, name, callback=None) | return True | Set the name of a universe.
Args:
universe: the universe to set the name of
name: the new name for the universe
callback: The function to call once complete, takes one argument, a
RequestStatus object.
Returns:
True if the request was sent, False otherwise. | Set the name of a universe. | [
"Set",
"the",
"name",
"of",
"a",
"universe",
"."
] | def SetUniverseName(self, universe, name, callback=None):
"""Set the name of a universe.
Args:
universe: the universe to set the name of
name: the new name for the universe
callback: The function to call once complete, takes one argument, a
RequestStatus object.
Returns:
True if the request was sent, False otherwise.
"""
if self._socket is None:
return False
controller = SimpleRpcController()
request = Ola_pb2.UniverseNameRequest()
request.universe = universe
request.name = name
try:
self._stub.SetUniverseName(
controller, request,
lambda x, y: self._AckMessageComplete(callback, x, y))
except socket.error:
raise OLADNotRunningException()
return True | [
"def",
"SetUniverseName",
"(",
"self",
",",
"universe",
",",
"name",
",",
"callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_socket",
"is",
"None",
":",
"return",
"False",
"controller",
"=",
"SimpleRpcController",
"(",
")",
"request",
"=",
"Ola_pb2",
".",
"UniverseNameRequest",
"(",
")",
"request",
".",
"universe",
"=",
"universe",
"request",
".",
"name",
"=",
"name",
"try",
":",
"self",
".",
"_stub",
".",
"SetUniverseName",
"(",
"controller",
",",
"request",
",",
"lambda",
"x",
",",
"y",
":",
"self",
".",
"_AckMessageComplete",
"(",
"callback",
",",
"x",
",",
"y",
")",
")",
"except",
"socket",
".",
"error",
":",
"raise",
"OLADNotRunningException",
"(",
")",
"return",
"True"
] | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/OlaClient.py#L967-L992 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/service.py | python | Service.get_service_client | (self, session: boto3.Session = None, verbose: bool = False) | return cgf_service_client.for_url(self.url, session=session, verbose=verbose, repack=True) | Gets a service client for a stack's service api.
Will use repack to pack any non dict responses into generic {'Results': response}
Arguments:
session: A pre-made boto3 session, otherwise a new session is created
verbose: If true, sets the client to be verbose, otherwise only error statements will be logged
Returns a cgf_service_client.Path object that can be used to make requests. | Gets a service client for a stack's service api.
Will use repack to pack any non dict responses into generic {'Results': response} | [
"Gets",
"a",
"service",
"client",
"for",
"a",
"stack",
"s",
"service",
"api",
".",
"Will",
"use",
"repack",
"to",
"pack",
"any",
"non",
"dict",
"responses",
"into",
"generic",
"{",
"Results",
":",
"response",
"}"
] | def get_service_client(self, session: boto3.Session = None, verbose: bool = False) -> cgf_service_client.Path:
"""
Gets a service client for a stack's service api.
Will use repack to pack any non dict responses into generic {'Results': response}
Arguments:
session: A pre-made boto3 session, otherwise a new session is created
verbose: If true, sets the client to be verbose, otherwise only error statements will be logged
Returns a cgf_service_client.Path object that can be used to make requests.
"""
if self._context.config.project_stack_id is None:
raise HandledError("Project stack does not exist.")
return cgf_service_client.for_url(self.url, session=session, verbose=verbose, repack=True) | [
"def",
"get_service_client",
"(",
"self",
",",
"session",
":",
"boto3",
".",
"Session",
"=",
"None",
",",
"verbose",
":",
"bool",
"=",
"False",
")",
"->",
"cgf_service_client",
".",
"Path",
":",
"if",
"self",
".",
"_context",
".",
"config",
".",
"project_stack_id",
"is",
"None",
":",
"raise",
"HandledError",
"(",
"\"Project stack does not exist.\"",
")",
"return",
"cgf_service_client",
".",
"for_url",
"(",
"self",
".",
"url",
",",
"session",
"=",
"session",
",",
"verbose",
"=",
"verbose",
",",
"repack",
"=",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/service.py#L72-L85 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/docview.py | python | CommandProcessor.SetMenuStrings | (self) | Sets the menu labels according to the currently set menu and the
current command state. | Sets the menu labels according to the currently set menu and the
current command state. | [
"Sets",
"the",
"menu",
"labels",
"according",
"to",
"the",
"currently",
"set",
"menu",
"and",
"the",
"current",
"command",
"state",
"."
] | def SetMenuStrings(self):
"""
Sets the menu labels according to the currently set menu and the
current command state.
"""
if self.GetEditMenu() != None:
undoCommand = self._GetCurrentCommand()
redoCommand = self._GetCurrentRedoCommand()
undoItem = self.GetEditMenu().FindItemById(wx.ID_UNDO)
redoItem = self.GetEditMenu().FindItemById(wx.ID_REDO)
if self.GetUndoAccelerator():
undoAccel = '\t' + self.GetUndoAccelerator()
else:
undoAccel = ''
if self.GetRedoAccelerator():
redoAccel = '\t' + self.GetRedoAccelerator()
else:
redoAccel = ''
if undoCommand and undoItem and undoCommand.CanUndo():
undoItem.SetText(_("&Undo ") + undoCommand.GetName() + undoAccel)
#elif undoCommand and not undoCommand.CanUndo():
# undoItem.SetText(_("Can't Undo") + undoAccel)
else:
undoItem.SetText(_("&Undo" + undoAccel))
if redoCommand and redoItem:
redoItem.SetText(_("&Redo ") + redoCommand.GetName() + redoAccel)
else:
redoItem.SetText(_("&Redo") + redoAccel) | [
"def",
"SetMenuStrings",
"(",
"self",
")",
":",
"if",
"self",
".",
"GetEditMenu",
"(",
")",
"!=",
"None",
":",
"undoCommand",
"=",
"self",
".",
"_GetCurrentCommand",
"(",
")",
"redoCommand",
"=",
"self",
".",
"_GetCurrentRedoCommand",
"(",
")",
"undoItem",
"=",
"self",
".",
"GetEditMenu",
"(",
")",
".",
"FindItemById",
"(",
"wx",
".",
"ID_UNDO",
")",
"redoItem",
"=",
"self",
".",
"GetEditMenu",
"(",
")",
".",
"FindItemById",
"(",
"wx",
".",
"ID_REDO",
")",
"if",
"self",
".",
"GetUndoAccelerator",
"(",
")",
":",
"undoAccel",
"=",
"'\\t'",
"+",
"self",
".",
"GetUndoAccelerator",
"(",
")",
"else",
":",
"undoAccel",
"=",
"''",
"if",
"self",
".",
"GetRedoAccelerator",
"(",
")",
":",
"redoAccel",
"=",
"'\\t'",
"+",
"self",
".",
"GetRedoAccelerator",
"(",
")",
"else",
":",
"redoAccel",
"=",
"''",
"if",
"undoCommand",
"and",
"undoItem",
"and",
"undoCommand",
".",
"CanUndo",
"(",
")",
":",
"undoItem",
".",
"SetText",
"(",
"_",
"(",
"\"&Undo \"",
")",
"+",
"undoCommand",
".",
"GetName",
"(",
")",
"+",
"undoAccel",
")",
"#elif undoCommand and not undoCommand.CanUndo():",
"# undoItem.SetText(_(\"Can't Undo\") + undoAccel)",
"else",
":",
"undoItem",
".",
"SetText",
"(",
"_",
"(",
"\"&Undo\"",
"+",
"undoAccel",
")",
")",
"if",
"redoCommand",
"and",
"redoItem",
":",
"redoItem",
".",
"SetText",
"(",
"_",
"(",
"\"&Redo \"",
")",
"+",
"redoCommand",
".",
"GetName",
"(",
")",
"+",
"redoAccel",
")",
"else",
":",
"redoItem",
".",
"SetText",
"(",
"_",
"(",
"\"&Redo\"",
")",
"+",
"redoAccel",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L3134-L3161 | ||
libLAS/libLAS | e6a1aaed412d638687b8aec44f7b12df7ca2bbbb | python/liblas/header.py | python | Header.set_pointrecordsbyreturncount | (self, value) | Sets the histogram of point records by return number from a list of
returns 0..8
>>> l = [1341235L, 3412341222L, 0L, 0L, 4321L, 0L, 0L, 0L]
>>> h.point_return_count = l
>>> h.point_return_count
[1341235L, 3412341222L, 0L, 0L, 4321L, 0L, 0L, 0L] | Sets the histogram of point records by return number from a list of
returns 0..8 | [
"Sets",
"the",
"histogram",
"of",
"point",
"records",
"by",
"return",
"number",
"from",
"a",
"list",
"of",
"returns",
"0",
"..",
"8"
] | def set_pointrecordsbyreturncount(self, value):
"""Sets the histogram of point records by return number from a list of
returns 0..8
>>> l = [1341235L, 3412341222L, 0L, 0L, 4321L, 0L, 0L, 0L]
>>> h.point_return_count = l
>>> h.point_return_count
[1341235L, 3412341222L, 0L, 0L, 4321L, 0L, 0L, 0L]
"""
for i in value[0:7]:
core.las.LASHeader_SetPointRecordsByReturnCount(self.handle,
value.index(i), i) | [
"def",
"set_pointrecordsbyreturncount",
"(",
"self",
",",
"value",
")",
":",
"for",
"i",
"in",
"value",
"[",
"0",
":",
"7",
"]",
":",
"core",
".",
"las",
".",
"LASHeader_SetPointRecordsByReturnCount",
"(",
"self",
".",
"handle",
",",
"value",
".",
"index",
"(",
"i",
")",
",",
"i",
")"
] | https://github.com/libLAS/libLAS/blob/e6a1aaed412d638687b8aec44f7b12df7ca2bbbb/python/liblas/header.py#L559-L571 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/_multivariate.py | python | wishart_gen.pdf | (self, x, df, scale) | return np.exp(self.logpdf(x, df, scale)) | Wishart probability density function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
Each quantile must be a symmetric positive definite matrix.
%(_doc_default_callparams)s
Returns
-------
pdf : ndarray
Probability density function evaluated at `x`
Notes
-----
%(_doc_callparams_note)s | Wishart probability density function. | [
"Wishart",
"probability",
"density",
"function",
"."
] | def pdf(self, x, df, scale):
"""
Wishart probability density function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
Each quantile must be a symmetric positive definite matrix.
%(_doc_default_callparams)s
Returns
-------
pdf : ndarray
Probability density function evaluated at `x`
Notes
-----
%(_doc_callparams_note)s
"""
return np.exp(self.logpdf(x, df, scale)) | [
"def",
"pdf",
"(",
"self",
",",
"x",
",",
"df",
",",
"scale",
")",
":",
"return",
"np",
".",
"exp",
"(",
"self",
".",
"logpdf",
"(",
"x",
",",
"df",
",",
"scale",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L1692-L1713 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | GLGenerator.WriteGLES2InterfaceHeader | (self, filename) | Writes the GLES2 interface header. | Writes the GLES2 interface header. | [
"Writes",
"the",
"GLES2",
"interface",
"header",
"."
] | def WriteGLES2InterfaceHeader(self, filename):
"""Writes the GLES2 interface header."""
comment = ("// This file is included by gles2_interface.h to declare the\n"
"// GL api functions.\n")
with CHeaderWriter(filename, comment) as f:
for func in self.original_functions:
func.WriteGLES2InterfaceHeader(f)
self.generated_cpp_filenames.append(filename) | [
"def",
"WriteGLES2InterfaceHeader",
"(",
"self",
",",
"filename",
")",
":",
"comment",
"=",
"(",
"\"// This file is included by gles2_interface.h to declare the\\n\"",
"\"// GL api functions.\\n\"",
")",
"with",
"CHeaderWriter",
"(",
"filename",
",",
"comment",
")",
"as",
"f",
":",
"for",
"func",
"in",
"self",
".",
"original_functions",
":",
"func",
".",
"WriteGLES2InterfaceHeader",
"(",
"f",
")",
"self",
".",
"generated_cpp_filenames",
".",
"append",
"(",
"filename",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L10653-L10660 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/onnxruntime_inference_collection.py | python | IOBinding.bind_ortvalue_output | (self, name, ortvalue) | :param name: output name
:param ortvalue: OrtValue instance to bind | :param name: output name
:param ortvalue: OrtValue instance to bind | [
":",
"param",
"name",
":",
"output",
"name",
":",
"param",
"ortvalue",
":",
"OrtValue",
"instance",
"to",
"bind"
] | def bind_ortvalue_output(self, name, ortvalue):
'''
:param name: output name
:param ortvalue: OrtValue instance to bind
'''
self._iobinding.bind_ortvalue_output(name, ortvalue._ortvalue) | [
"def",
"bind_ortvalue_output",
"(",
"self",
",",
"name",
",",
"ortvalue",
")",
":",
"self",
".",
"_iobinding",
".",
"bind_ortvalue_output",
"(",
"name",
",",
"ortvalue",
".",
"_ortvalue",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L484-L489 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/datetimes.py | python | DatetimeArray.tz_localize | (self, tz, ambiguous="raise", nonexistent="raise") | return self._simple_new(new_dates, dtype=dtype, freq=freq) | Localize tz-naive Datetime Array/Index to tz-aware
Datetime Array/Index.
This method takes a time zone (tz) naive Datetime Array/Index object
and makes this time zone aware. It does not move the time to another
time zone.
This method can also be used to do the inverse -- to create a time
zone unaware object from an aware object. To that end, pass `tz=None`.
Parameters
----------
tz : str, pytz.timezone, dateutil.tz.tzfile or None
Time zone to convert timestamps to. Passing ``None`` will
remove the time zone information preserving local time.
ambiguous : 'infer', 'NaT', bool array, default 'raise'
When clocks moved backward due to DST, ambiguous times may arise.
For example in Central European Time (UTC+01), when going from
03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at
00:30:00 UTC and at 01:30:00 UTC. In such a situation, the
`ambiguous` parameter dictates how ambiguous times should be
handled.
- 'infer' will attempt to infer fall dst-transition hours based on
order
- bool-ndarray where True signifies a DST time, False signifies a
non-DST time (note that this flag is only applicable for
ambiguous times)
- 'NaT' will return NaT where there are ambiguous times
- 'raise' will raise an AmbiguousTimeError if there are ambiguous
times.
nonexistent : 'shift_forward', 'shift_backward, 'NaT', timedelta, \
default 'raise'
A nonexistent time does not exist in a particular timezone
where clocks moved forward due to DST.
- 'shift_forward' will shift the nonexistent time forward to the
closest existing time
- 'shift_backward' will shift the nonexistent time backward to the
closest existing time
- 'NaT' will return NaT where there are nonexistent times
- timedelta objects will shift nonexistent times by the timedelta
- 'raise' will raise an NonExistentTimeError if there are
nonexistent times.
Returns
-------
Same type as self
Array/Index converted to the specified time zone.
Raises
------
TypeError
If the Datetime Array/Index is tz-aware and tz is not None.
See Also
--------
DatetimeIndex.tz_convert : Convert tz-aware DatetimeIndex from
one time zone to another.
Examples
--------
>>> tz_naive = pd.date_range('2018-03-01 09:00', periods=3)
>>> tz_naive
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq='D')
Localize DatetimeIndex in US/Eastern time zone:
>>> tz_aware = tz_naive.tz_localize(tz='US/Eastern')
>>> tz_aware
DatetimeIndex(['2018-03-01 09:00:00-05:00',
'2018-03-02 09:00:00-05:00',
'2018-03-03 09:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq=None)
With the ``tz=None``, we can remove the time zone information
while keeping the local time (not converted to UTC):
>>> tz_aware.tz_localize(None)
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq=None)
Be careful with DST changes. When there is sequential data, pandas can
infer the DST time:
>>> s = pd.to_datetime(pd.Series(['2018-10-28 01:30:00',
... '2018-10-28 02:00:00',
... '2018-10-28 02:30:00',
... '2018-10-28 02:00:00',
... '2018-10-28 02:30:00',
... '2018-10-28 03:00:00',
... '2018-10-28 03:30:00']))
>>> s.dt.tz_localize('CET', ambiguous='infer')
0 2018-10-28 01:30:00+02:00
1 2018-10-28 02:00:00+02:00
2 2018-10-28 02:30:00+02:00
3 2018-10-28 02:00:00+01:00
4 2018-10-28 02:30:00+01:00
5 2018-10-28 03:00:00+01:00
6 2018-10-28 03:30:00+01:00
dtype: datetime64[ns, CET]
In some cases, inferring the DST is impossible. In such cases, you can
pass an ndarray to the ambiguous parameter to set the DST explicitly
>>> s = pd.to_datetime(pd.Series(['2018-10-28 01:20:00',
... '2018-10-28 02:36:00',
... '2018-10-28 03:46:00']))
>>> s.dt.tz_localize('CET', ambiguous=np.array([True, True, False]))
0 2018-10-28 01:20:00+02:00
1 2018-10-28 02:36:00+02:00
2 2018-10-28 03:46:00+01:00
dtype: datetime64[ns, CET]
If the DST transition causes nonexistent times, you can shift these
dates forward or backwards with a timedelta object or `'shift_forward'`
or `'shift_backwards'`.
>>> s = pd.to_datetime(pd.Series(['2015-03-29 02:30:00',
... '2015-03-29 03:30:00']))
>>> s.dt.tz_localize('Europe/Warsaw', nonexistent='shift_forward')
0 2015-03-29 03:00:00+02:00
1 2015-03-29 03:30:00+02:00
dtype: datetime64[ns, Europe/Warsaw]
>>> s.dt.tz_localize('Europe/Warsaw', nonexistent='shift_backward')
0 2015-03-29 01:59:59.999999999+01:00
1 2015-03-29 03:30:00+02:00
dtype: datetime64[ns, Europe/Warsaw]
>>> s.dt.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H'))
0 2015-03-29 03:30:00+02:00
1 2015-03-29 03:30:00+02:00
dtype: datetime64[ns, Europe/Warsaw] | Localize tz-naive Datetime Array/Index to tz-aware
Datetime Array/Index. | [
"Localize",
"tz",
"-",
"naive",
"Datetime",
"Array",
"/",
"Index",
"to",
"tz",
"-",
"aware",
"Datetime",
"Array",
"/",
"Index",
"."
] | def tz_localize(self, tz, ambiguous="raise", nonexistent="raise") -> DatetimeArray:
"""
Localize tz-naive Datetime Array/Index to tz-aware
Datetime Array/Index.
This method takes a time zone (tz) naive Datetime Array/Index object
and makes this time zone aware. It does not move the time to another
time zone.
This method can also be used to do the inverse -- to create a time
zone unaware object from an aware object. To that end, pass `tz=None`.
Parameters
----------
tz : str, pytz.timezone, dateutil.tz.tzfile or None
Time zone to convert timestamps to. Passing ``None`` will
remove the time zone information preserving local time.
ambiguous : 'infer', 'NaT', bool array, default 'raise'
When clocks moved backward due to DST, ambiguous times may arise.
For example in Central European Time (UTC+01), when going from
03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at
00:30:00 UTC and at 01:30:00 UTC. In such a situation, the
`ambiguous` parameter dictates how ambiguous times should be
handled.
- 'infer' will attempt to infer fall dst-transition hours based on
order
- bool-ndarray where True signifies a DST time, False signifies a
non-DST time (note that this flag is only applicable for
ambiguous times)
- 'NaT' will return NaT where there are ambiguous times
- 'raise' will raise an AmbiguousTimeError if there are ambiguous
times.
nonexistent : 'shift_forward', 'shift_backward, 'NaT', timedelta, \
default 'raise'
A nonexistent time does not exist in a particular timezone
where clocks moved forward due to DST.
- 'shift_forward' will shift the nonexistent time forward to the
closest existing time
- 'shift_backward' will shift the nonexistent time backward to the
closest existing time
- 'NaT' will return NaT where there are nonexistent times
- timedelta objects will shift nonexistent times by the timedelta
- 'raise' will raise an NonExistentTimeError if there are
nonexistent times.
Returns
-------
Same type as self
Array/Index converted to the specified time zone.
Raises
------
TypeError
If the Datetime Array/Index is tz-aware and tz is not None.
See Also
--------
DatetimeIndex.tz_convert : Convert tz-aware DatetimeIndex from
one time zone to another.
Examples
--------
>>> tz_naive = pd.date_range('2018-03-01 09:00', periods=3)
>>> tz_naive
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq='D')
Localize DatetimeIndex in US/Eastern time zone:
>>> tz_aware = tz_naive.tz_localize(tz='US/Eastern')
>>> tz_aware
DatetimeIndex(['2018-03-01 09:00:00-05:00',
'2018-03-02 09:00:00-05:00',
'2018-03-03 09:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq=None)
With the ``tz=None``, we can remove the time zone information
while keeping the local time (not converted to UTC):
>>> tz_aware.tz_localize(None)
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq=None)
Be careful with DST changes. When there is sequential data, pandas can
infer the DST time:
>>> s = pd.to_datetime(pd.Series(['2018-10-28 01:30:00',
... '2018-10-28 02:00:00',
... '2018-10-28 02:30:00',
... '2018-10-28 02:00:00',
... '2018-10-28 02:30:00',
... '2018-10-28 03:00:00',
... '2018-10-28 03:30:00']))
>>> s.dt.tz_localize('CET', ambiguous='infer')
0 2018-10-28 01:30:00+02:00
1 2018-10-28 02:00:00+02:00
2 2018-10-28 02:30:00+02:00
3 2018-10-28 02:00:00+01:00
4 2018-10-28 02:30:00+01:00
5 2018-10-28 03:00:00+01:00
6 2018-10-28 03:30:00+01:00
dtype: datetime64[ns, CET]
In some cases, inferring the DST is impossible. In such cases, you can
pass an ndarray to the ambiguous parameter to set the DST explicitly
>>> s = pd.to_datetime(pd.Series(['2018-10-28 01:20:00',
... '2018-10-28 02:36:00',
... '2018-10-28 03:46:00']))
>>> s.dt.tz_localize('CET', ambiguous=np.array([True, True, False]))
0 2018-10-28 01:20:00+02:00
1 2018-10-28 02:36:00+02:00
2 2018-10-28 03:46:00+01:00
dtype: datetime64[ns, CET]
If the DST transition causes nonexistent times, you can shift these
dates forward or backwards with a timedelta object or `'shift_forward'`
or `'shift_backwards'`.
>>> s = pd.to_datetime(pd.Series(['2015-03-29 02:30:00',
... '2015-03-29 03:30:00']))
>>> s.dt.tz_localize('Europe/Warsaw', nonexistent='shift_forward')
0 2015-03-29 03:00:00+02:00
1 2015-03-29 03:30:00+02:00
dtype: datetime64[ns, Europe/Warsaw]
>>> s.dt.tz_localize('Europe/Warsaw', nonexistent='shift_backward')
0 2015-03-29 01:59:59.999999999+01:00
1 2015-03-29 03:30:00+02:00
dtype: datetime64[ns, Europe/Warsaw]
>>> s.dt.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H'))
0 2015-03-29 03:30:00+02:00
1 2015-03-29 03:30:00+02:00
dtype: datetime64[ns, Europe/Warsaw]
"""
nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward")
if nonexistent not in nonexistent_options and not isinstance(
nonexistent, timedelta
):
raise ValueError(
"The nonexistent argument must be one of 'raise', "
"'NaT', 'shift_forward', 'shift_backward' or "
"a timedelta object"
)
if self.tz is not None:
if tz is None:
new_dates = tzconversion.tz_convert_from_utc(self.asi8, self.tz)
else:
raise TypeError("Already tz-aware, use tz_convert to convert.")
else:
tz = timezones.maybe_get_tz(tz)
# Convert to UTC
new_dates = tzconversion.tz_localize_to_utc(
self.asi8, tz, ambiguous=ambiguous, nonexistent=nonexistent
)
new_dates = new_dates.view(DT64NS_DTYPE)
dtype = tz_to_dtype(tz)
freq = None
if timezones.is_utc(tz) or (len(self) == 1 and not isna(new_dates[0])):
# we can preserve freq
# TODO: Also for fixed-offsets
freq = self.freq
elif tz is None and self.tz is None:
# no-op
freq = self.freq
return self._simple_new(new_dates, dtype=dtype, freq=freq) | [
"def",
"tz_localize",
"(",
"self",
",",
"tz",
",",
"ambiguous",
"=",
"\"raise\"",
",",
"nonexistent",
"=",
"\"raise\"",
")",
"->",
"DatetimeArray",
":",
"nonexistent_options",
"=",
"(",
"\"raise\"",
",",
"\"NaT\"",
",",
"\"shift_forward\"",
",",
"\"shift_backward\"",
")",
"if",
"nonexistent",
"not",
"in",
"nonexistent_options",
"and",
"not",
"isinstance",
"(",
"nonexistent",
",",
"timedelta",
")",
":",
"raise",
"ValueError",
"(",
"\"The nonexistent argument must be one of 'raise', \"",
"\"'NaT', 'shift_forward', 'shift_backward' or \"",
"\"a timedelta object\"",
")",
"if",
"self",
".",
"tz",
"is",
"not",
"None",
":",
"if",
"tz",
"is",
"None",
":",
"new_dates",
"=",
"tzconversion",
".",
"tz_convert_from_utc",
"(",
"self",
".",
"asi8",
",",
"self",
".",
"tz",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Already tz-aware, use tz_convert to convert.\"",
")",
"else",
":",
"tz",
"=",
"timezones",
".",
"maybe_get_tz",
"(",
"tz",
")",
"# Convert to UTC",
"new_dates",
"=",
"tzconversion",
".",
"tz_localize_to_utc",
"(",
"self",
".",
"asi8",
",",
"tz",
",",
"ambiguous",
"=",
"ambiguous",
",",
"nonexistent",
"=",
"nonexistent",
")",
"new_dates",
"=",
"new_dates",
".",
"view",
"(",
"DT64NS_DTYPE",
")",
"dtype",
"=",
"tz_to_dtype",
"(",
"tz",
")",
"freq",
"=",
"None",
"if",
"timezones",
".",
"is_utc",
"(",
"tz",
")",
"or",
"(",
"len",
"(",
"self",
")",
"==",
"1",
"and",
"not",
"isna",
"(",
"new_dates",
"[",
"0",
"]",
")",
")",
":",
"# we can preserve freq",
"# TODO: Also for fixed-offsets",
"freq",
"=",
"self",
".",
"freq",
"elif",
"tz",
"is",
"None",
"and",
"self",
".",
"tz",
"is",
"None",
":",
"# no-op",
"freq",
"=",
"self",
".",
"freq",
"return",
"self",
".",
"_simple_new",
"(",
"new_dates",
",",
"dtype",
"=",
"dtype",
",",
"freq",
"=",
"freq",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/datetimes.py#L864-L1038 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewItemArray.__iter__ | (*args, **kwargs) | return _dataview.DataViewItemArray___iter__(*args, **kwargs) | __iter__(self) -> DataViewItemArray_iterator | __iter__(self) -> DataViewItemArray_iterator | [
"__iter__",
"(",
"self",
")",
"-",
">",
"DataViewItemArray_iterator"
] | def __iter__(*args, **kwargs):
"""__iter__(self) -> DataViewItemArray_iterator"""
return _dataview.DataViewItemArray___iter__(*args, **kwargs) | [
"def",
"__iter__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewItemArray___iter__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L157-L159 | |
BestSonny/SSTD | 174d452189f6bf9cf4b6957719392008bd974069 | tools/extra/resize_and_crop_images.py | python | OpenCVResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256) | Takes an image name, resize it and crop the center square | Takes an image name, resize it and crop the center square | [
"Takes",
"an",
"image",
"name",
"resize",
"it",
"and",
"crop",
"the",
"center",
"square"
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256):
'''Takes an image name, resize it and crop the center square
'''
img = cv2.imread(input_file)
height, width, depth = img.shape
new_height = output_side_length
new_width = output_side_length
if height > width:
new_height = output_side_length * height / width
else:
new_width = output_side_length * width / height
resized_img = cv2.resize(img, (new_width, new_height))
height_offset = (new_height - output_side_length) / 2
width_offset = (new_width - output_side_length) / 2
cropped_img = resized_img[height_offset:height_offset + output_side_length,
width_offset:width_offset + output_side_length]
cv2.imwrite(output_file, cropped_img) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"input_file",
")",
"height",
",",
"width",
",",
"depth",
"=",
"img",
".",
"shape",
"new_height",
"=",
"output_side_length",
"new_width",
"=",
"output_side_length",
"if",
"height",
">",
"width",
":",
"new_height",
"=",
"output_side_length",
"*",
"height",
"/",
"width",
"else",
":",
"new_width",
"=",
"output_side_length",
"*",
"width",
"/",
"height",
"resized_img",
"=",
"cv2",
".",
"resize",
"(",
"img",
",",
"(",
"new_width",
",",
"new_height",
")",
")",
"height_offset",
"=",
"(",
"new_height",
"-",
"output_side_length",
")",
"/",
"2",
"width_offset",
"=",
"(",
"new_width",
"-",
"output_side_length",
")",
"/",
"2",
"cropped_img",
"=",
"resized_img",
"[",
"height_offset",
":",
"height_offset",
"+",
"output_side_length",
",",
"width_offset",
":",
"width_offset",
"+",
"output_side_length",
"]",
"cv2",
".",
"imwrite",
"(",
"output_file",
",",
"cropped_img",
")"
] | https://github.com/BestSonny/SSTD/blob/174d452189f6bf9cf4b6957719392008bd974069/tools/extra/resize_and_crop_images.py#L20-L36 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/wallet.py | python | Wallet.withdrawal_lock | (self, withdrawal_lock) | Sets the withdrawal_lock of this Wallet.
:param withdrawal_lock: The withdrawal_lock of this Wallet. # noqa: E501
:type: list[str] | Sets the withdrawal_lock of this Wallet. | [
"Sets",
"the",
"withdrawal_lock",
"of",
"this",
"Wallet",
"."
] | def withdrawal_lock(self, withdrawal_lock):
"""Sets the withdrawal_lock of this Wallet.
:param withdrawal_lock: The withdrawal_lock of this Wallet. # noqa: E501
:type: list[str]
"""
self._withdrawal_lock = withdrawal_lock | [
"def",
"withdrawal_lock",
"(",
"self",
",",
"withdrawal_lock",
")",
":",
"self",
".",
"_withdrawal_lock",
"=",
"withdrawal_lock"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/wallet.py#L687-L695 | ||
google/nucleus | 68d3947fafba1337f294c0668a6e1c7f3f1273e3 | nucleus/io/bed.py | python | NativeBedWriter.__init__ | (self, output_path, header=None) | Initializer for NativeBedWriter.
Args:
output_path: str. The path to which to write the BED file.
header: nucleus.genomics.v1.BedHeader. The header that defines all
information germane to the constituent BED records. | Initializer for NativeBedWriter. | [
"Initializer",
"for",
"NativeBedWriter",
"."
] | def __init__(self, output_path, header=None):
"""Initializer for NativeBedWriter.
Args:
output_path: str. The path to which to write the BED file.
header: nucleus.genomics.v1.BedHeader. The header that defines all
information germane to the constituent BED records.
"""
super(NativeBedWriter, self).__init__()
if header is None:
header = bed_pb2.BedHeader(num_fields=3)
writer_options = bed_pb2.BedWriterOptions()
self._writer = bed_writer.BedWriter.to_file(output_path, header,
writer_options) | [
"def",
"__init__",
"(",
"self",
",",
"output_path",
",",
"header",
"=",
"None",
")",
":",
"super",
"(",
"NativeBedWriter",
",",
"self",
")",
".",
"__init__",
"(",
")",
"if",
"header",
"is",
"None",
":",
"header",
"=",
"bed_pb2",
".",
"BedHeader",
"(",
"num_fields",
"=",
"3",
")",
"writer_options",
"=",
"bed_pb2",
".",
"BedWriterOptions",
"(",
")",
"self",
".",
"_writer",
"=",
"bed_writer",
".",
"BedWriter",
".",
"to_file",
"(",
"output_path",
",",
"header",
",",
"writer_options",
")"
] | https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/io/bed.py#L125-L138 | ||
rdiankov/openrave | d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7 | python/examples/tutorial_grasptransform.py | python | main | (env,options) | Main example code. | Main example code. | [
"Main",
"example",
"code",
"."
] | def main(env,options):
"Main example code."
robot = env.ReadRobotXMLFile('robots/pr2-beta-static.zae')
env.Add(robot)
target = env.ReadKinBodyXMLFile('data/mug2.kinbody.xml')
env.Add(target)
# init target pose
O_T_Target = array([[1,0,0,1],
[0,1,0,1],
[0,0,1,1],
[0,0,0,1]])
target.SetTransform(O_T_Target)
robot.SetActiveManipulator('leftarm')
# init robot pose: l_shoulder_pan, r_shoulder_pan, torso, l_gripper_l_finger_joint
names = ['l_shoulder_pan_joint', 'r_shoulder_pan_joint', 'torso_lift_joint', 'l_gripper_l_finger_joint']
dofs = [robot.GetJoint(name).GetDOFIndex() for name in names]
robot.SetDOFValues([pi/2,-pi/2,0.31,0.54],dofs)
gt = GraspTransform(env,target)
handles = []
raw_input('This demo shows how to find the transform that moves the hand to the target.\npress ENTER to continue...')
print('showing robot transform in global frame O_T_R')
handles = gt.drawTransform(gt.robot.GetTransform())
raw_input('press ENTER to continue...')
print('showing target transform in global frame O_T_Target')
handles = gt.drawTransform(gt.target.GetTransform())
raw_input('press ENTER to continue...')
print('showing grasping frame in global frame O_T_G')
handles = gt.drawTransform(gt.robot.GetActiveManipulator().GetTransform())
raw_input('press ENTER to continue...')
raw_input('Guess what the robot will look like when the hand is on the target?\npress ENTER to continue...')
gt.showGrasp(target.GetTransform())
raw_input('press ENTER to exit') | [
"def",
"main",
"(",
"env",
",",
"options",
")",
":",
"robot",
"=",
"env",
".",
"ReadRobotXMLFile",
"(",
"'robots/pr2-beta-static.zae'",
")",
"env",
".",
"Add",
"(",
"robot",
")",
"target",
"=",
"env",
".",
"ReadKinBodyXMLFile",
"(",
"'data/mug2.kinbody.xml'",
")",
"env",
".",
"Add",
"(",
"target",
")",
"# init target pose",
"O_T_Target",
"=",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
",",
"1",
"]",
",",
"[",
"0",
",",
"1",
",",
"0",
",",
"1",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
",",
"1",
"]",
",",
"[",
"0",
",",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"target",
".",
"SetTransform",
"(",
"O_T_Target",
")",
"robot",
".",
"SetActiveManipulator",
"(",
"'leftarm'",
")",
"# init robot pose: l_shoulder_pan, r_shoulder_pan, torso, l_gripper_l_finger_joint",
"names",
"=",
"[",
"'l_shoulder_pan_joint'",
",",
"'r_shoulder_pan_joint'",
",",
"'torso_lift_joint'",
",",
"'l_gripper_l_finger_joint'",
"]",
"dofs",
"=",
"[",
"robot",
".",
"GetJoint",
"(",
"name",
")",
".",
"GetDOFIndex",
"(",
")",
"for",
"name",
"in",
"names",
"]",
"robot",
".",
"SetDOFValues",
"(",
"[",
"pi",
"/",
"2",
",",
"-",
"pi",
"/",
"2",
",",
"0.31",
",",
"0.54",
"]",
",",
"dofs",
")",
"gt",
"=",
"GraspTransform",
"(",
"env",
",",
"target",
")",
"handles",
"=",
"[",
"]",
"raw_input",
"(",
"'This demo shows how to find the transform that moves the hand to the target.\\npress ENTER to continue...'",
")",
"print",
"(",
"'showing robot transform in global frame O_T_R'",
")",
"handles",
"=",
"gt",
".",
"drawTransform",
"(",
"gt",
".",
"robot",
".",
"GetTransform",
"(",
")",
")",
"raw_input",
"(",
"'press ENTER to continue...'",
")",
"print",
"(",
"'showing target transform in global frame O_T_Target'",
")",
"handles",
"=",
"gt",
".",
"drawTransform",
"(",
"gt",
".",
"target",
".",
"GetTransform",
"(",
")",
")",
"raw_input",
"(",
"'press ENTER to continue...'",
")",
"print",
"(",
"'showing grasping frame in global frame O_T_G'",
")",
"handles",
"=",
"gt",
".",
"drawTransform",
"(",
"gt",
".",
"robot",
".",
"GetActiveManipulator",
"(",
")",
".",
"GetTransform",
"(",
")",
")",
"raw_input",
"(",
"'press ENTER to continue...'",
")",
"raw_input",
"(",
"'Guess what the robot will look like when the hand is on the target?\\npress ENTER to continue...'",
")",
"gt",
".",
"showGrasp",
"(",
"target",
".",
"GetTransform",
"(",
")",
")",
"raw_input",
"(",
"'press ENTER to exit'",
")"
] | https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/examples/tutorial_grasptransform.py#L158-L191 | ||
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/core/additions/qgssettingsentry.py | python | PyQgsSettingsEntryEnumFlag.setValue | (self, value, dynamicKeyPart=None) | return super().setVariantValue(enumFlagKey, dynamicKeyPart) | Set settings value.
:param dynamicKeyPart: argument specifies the dynamic part of the settings key. | Set settings value.
:param dynamicKeyPart: argument specifies the dynamic part of the settings key. | [
"Set",
"settings",
"value",
".",
":",
"param",
"dynamicKeyPart",
":",
"argument",
"specifies",
"the",
"dynamic",
"part",
"of",
"the",
"settings",
"key",
"."
] | def setValue(self, value, dynamicKeyPart=None):
"""
Set settings value.
:param dynamicKeyPart: argument specifies the dynamic part of the settings key.
"""
if self.__metaEnum is None or not self.__metaEnum.isValid():
QgsLogger.debug("Invalid metaenum. Enum/Flag probably misses Q_ENUM/Q_FLAG declaration. Settings key: '{0}'".format(self.key()))
return False
enumFlagKey = str()
if self.__metaEnum.isFlag():
enumFlagKey = self.__metaEnum.valueToKeys(value)
else:
enumFlagKey = self.__metaEnum.valueToKey(value)
if not enumFlagKey:
QgsLogger.debug("Invalid enum/flag value '{0}'.".format(value))
return False
return super().setVariantValue(enumFlagKey, dynamicKeyPart) | [
"def",
"setValue",
"(",
"self",
",",
"value",
",",
"dynamicKeyPart",
"=",
"None",
")",
":",
"if",
"self",
".",
"__metaEnum",
"is",
"None",
"or",
"not",
"self",
".",
"__metaEnum",
".",
"isValid",
"(",
")",
":",
"QgsLogger",
".",
"debug",
"(",
"\"Invalid metaenum. Enum/Flag probably misses Q_ENUM/Q_FLAG declaration. Settings key: '{0}'\"",
".",
"format",
"(",
"self",
".",
"key",
"(",
")",
")",
")",
"return",
"False",
"enumFlagKey",
"=",
"str",
"(",
")",
"if",
"self",
".",
"__metaEnum",
".",
"isFlag",
"(",
")",
":",
"enumFlagKey",
"=",
"self",
".",
"__metaEnum",
".",
"valueToKeys",
"(",
"value",
")",
"else",
":",
"enumFlagKey",
"=",
"self",
".",
"__metaEnum",
".",
"valueToKey",
"(",
"value",
")",
"if",
"not",
"enumFlagKey",
":",
"QgsLogger",
".",
"debug",
"(",
"\"Invalid enum/flag value '{0}'.\"",
".",
"format",
"(",
"value",
")",
")",
"return",
"False",
"return",
"super",
"(",
")",
".",
"setVariantValue",
"(",
"enumFlagKey",
",",
"dynamicKeyPart",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/core/additions/qgssettingsentry.py#L97-L116 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/config/expandlibs_exec.py | python | ExpandArgsMore.__exit__ | (self, type, value, tb) | Automatically remove temporary files | Automatically remove temporary files | [
"Automatically",
"remove",
"temporary",
"files"
] | def __exit__(self, type, value, tb):
'''Automatically remove temporary files'''
for tmp in self.tmp:
if os.path.isdir(tmp):
shutil.rmtree(tmp, True)
else:
os.remove(tmp) | [
"def",
"__exit__",
"(",
"self",
",",
"type",
",",
"value",
",",
"tb",
")",
":",
"for",
"tmp",
"in",
"self",
".",
"tmp",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"tmp",
")",
":",
"shutil",
".",
"rmtree",
"(",
"tmp",
",",
"True",
")",
"else",
":",
"os",
".",
"remove",
"(",
"tmp",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/config/expandlibs_exec.py#L57-L63 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/ops.py | python | Operation.traceback | (self) | return _convert_stack(self._traceback) | Returns the call stack from when this operation was constructed. | Returns the call stack from when this operation was constructed. | [
"Returns",
"the",
"call",
"stack",
"from",
"when",
"this",
"operation",
"was",
"constructed",
"."
] | def traceback(self):
"""Returns the call stack from when this operation was constructed."""
return _convert_stack(self._traceback) | [
"def",
"traceback",
"(",
"self",
")",
":",
"return",
"_convert_stack",
"(",
"self",
".",
"_traceback",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/ops.py#L1508-L1510 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | build/android/emulator.py | python | Emulator.Shutdown | (self) | Shuts down the process started by launch. | Shuts down the process started by launch. | [
"Shuts",
"down",
"the",
"process",
"started",
"by",
"launch",
"."
] | def Shutdown(self):
"""Shuts down the process started by launch."""
if self.popen:
self.popen.poll()
if self.popen.returncode == None:
self.popen.kill()
self.popen = None | [
"def",
"Shutdown",
"(",
"self",
")",
":",
"if",
"self",
".",
"popen",
":",
"self",
".",
"popen",
".",
"poll",
"(",
")",
"if",
"self",
".",
"popen",
".",
"returncode",
"==",
"None",
":",
"self",
".",
"popen",
".",
"kill",
"(",
")",
"self",
".",
"popen",
"=",
"None"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/emulator.py#L229-L235 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/onnxruntime_inference_collection.py | python | SparseTensor.sparse_coo_from_numpy | (dense_shape, values, coo_indices, ort_device) | return SparseTensor(C.SparseTensor.sparse_coo_from_numpy(dense_shape, values, coo_indices,
ort_device._get_c_device())) | Factory method to construct a SparseTensor in COO format from given arguments
:param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor
must be on cpu memory
:param values: a homogeneous, contiguous 1-D numpy array that contains non-zero elements of the tensor
of a type.
:param coo_indices: contiguous numpy array(int64) that contains COO indices for the tensor. coo_indices may
have a 1-D shape when it contains a linear index of non-zero values and its length must be equal to
that of the values. It can also be of 2-D shape, in which has it contains pairs of coordinates for
each of the nnz values and its length must be exactly twice of the values length.
:param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
suppored for non-numeric data types.
For primitive types, the method will map values and coo_indices arrays into native memory and will use
them as backing storage. It will increment the reference count for numpy arrays and it will decrement it
on GC. The buffers may reside in any storage either CPU or GPU.
For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
on other devices and their memory can not be mapped. | Factory method to construct a SparseTensor in COO format from given arguments | [
"Factory",
"method",
"to",
"construct",
"a",
"SparseTensor",
"in",
"COO",
"format",
"from",
"given",
"arguments"
] | def sparse_coo_from_numpy(dense_shape, values, coo_indices, ort_device):
'''
Factory method to construct a SparseTensor in COO format from given arguments
:param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor
must be on cpu memory
:param values: a homogeneous, contiguous 1-D numpy array that contains non-zero elements of the tensor
of a type.
:param coo_indices: contiguous numpy array(int64) that contains COO indices for the tensor. coo_indices may
have a 1-D shape when it contains a linear index of non-zero values and its length must be equal to
that of the values. It can also be of 2-D shape, in which has it contains pairs of coordinates for
each of the nnz values and its length must be exactly twice of the values length.
:param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
suppored for non-numeric data types.
For primitive types, the method will map values and coo_indices arrays into native memory and will use
them as backing storage. It will increment the reference count for numpy arrays and it will decrement it
on GC. The buffers may reside in any storage either CPU or GPU.
For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
on other devices and their memory can not be mapped.
'''
return SparseTensor(C.SparseTensor.sparse_coo_from_numpy(dense_shape, values, coo_indices,
ort_device._get_c_device())) | [
"def",
"sparse_coo_from_numpy",
"(",
"dense_shape",
",",
"values",
",",
"coo_indices",
",",
"ort_device",
")",
":",
"return",
"SparseTensor",
"(",
"C",
".",
"SparseTensor",
".",
"sparse_coo_from_numpy",
"(",
"dense_shape",
",",
"values",
",",
"coo_indices",
",",
"ort_device",
".",
"_get_c_device",
"(",
")",
")",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L695-L717 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | third_party/gpus/check_cuda_libs.py | python | check_cuda_lib | (path, check_soname=True) | Tests if a library exists on disk and whether its soname matches the filename.
Args:
path: the path to the library.
check_soname: whether to check the soname as well.
Raises:
ConfigError: If the library does not exist or if its soname does not match
the filename. | Tests if a library exists on disk and whether its soname matches the filename. | [
"Tests",
"if",
"a",
"library",
"exists",
"on",
"disk",
"and",
"whether",
"its",
"soname",
"matches",
"the",
"filename",
"."
] | def check_cuda_lib(path, check_soname=True):
"""Tests if a library exists on disk and whether its soname matches the filename.
Args:
path: the path to the library.
check_soname: whether to check the soname as well.
Raises:
ConfigError: If the library does not exist or if its soname does not match
the filename.
"""
if not os.path.isfile(path):
raise ConfigError("No library found under: " + path)
objdump = which("objdump")
if check_soname and objdump is not None:
# Decode is necessary as in py3 the return type changed from str to bytes
output = subprocess.check_output([objdump, "-p", path]).decode("utf-8")
output = [line for line in output.splitlines() if "SONAME" in line]
sonames = [line.strip().split(" ")[-1] for line in output]
if not any(soname == os.path.basename(path) for soname in sonames):
raise ConfigError("None of the libraries match their SONAME: " + path) | [
"def",
"check_cuda_lib",
"(",
"path",
",",
"check_soname",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"raise",
"ConfigError",
"(",
"\"No library found under: \"",
"+",
"path",
")",
"objdump",
"=",
"which",
"(",
"\"objdump\"",
")",
"if",
"check_soname",
"and",
"objdump",
"is",
"not",
"None",
":",
"# Decode is necessary as in py3 the return type changed from str to bytes",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"objdump",
",",
"\"-p\"",
",",
"path",
"]",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"output",
"=",
"[",
"line",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
"if",
"\"SONAME\"",
"in",
"line",
"]",
"sonames",
"=",
"[",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
"[",
"-",
"1",
"]",
"for",
"line",
"in",
"output",
"]",
"if",
"not",
"any",
"(",
"soname",
"==",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"for",
"soname",
"in",
"sonames",
")",
":",
"raise",
"ConfigError",
"(",
"\"None of the libraries match their SONAME: \"",
"+",
"path",
")"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/third_party/gpus/check_cuda_libs.py#L42-L62 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | lineno | (loc, strg) | return strg.count("\n", 0, loc) + 1 | Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note - the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`ParserElement.parseString`
for more information on parsing strings containing ``<TAB>`` s, and
suggested methods to maintain a consistent view of the parsed string, the
parse location, and line and column positions within the parsed string. | Returns current line number within a string, counting newlines as line separators. | [
"Returns",
"current",
"line",
"number",
"within",
"a",
"string",
"counting",
"newlines",
"as",
"line",
"separators",
"."
] | def lineno(loc, strg):
"""Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note - the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`ParserElement.parseString`
for more information on parsing strings containing ``<TAB>`` s, and
suggested methods to maintain a consistent view of the parsed string, the
parse location, and line and column positions within the parsed string.
"""
return strg.count("\n", 0, loc) + 1 | [
"def",
"lineno",
"(",
"loc",
",",
"strg",
")",
":",
"return",
"strg",
".",
"count",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")",
"+",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L2449-L2469 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | 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",
")",
")",
"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",
"(",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/graph_actions.py#L450-L468 | ||
Caffe-MPI/Caffe-MPI.github.io | df5992af571a2a19981b69635115c393f18d1c76 | scripts/cpp_lint.py | python | FileInfo.IsSource | (self) | return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') | File has a source file extension. | File has a source file extension. | [
"File",
"has",
"a",
"source",
"file",
"extension",
"."
] | def IsSource(self):
"""File has a source file extension."""
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') | [
"def",
"IsSource",
"(",
"self",
")",
":",
"return",
"self",
".",
"Extension",
"(",
")",
"[",
"1",
":",
"]",
"in",
"(",
"'c'",
",",
"'cc'",
",",
"'cpp'",
",",
"'cxx'",
")"
] | https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/scripts/cpp_lint.py#L956-L958 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | MemoryFSHandler.CanOpen | (*args, **kwargs) | return _core_.MemoryFSHandler_CanOpen(*args, **kwargs) | CanOpen(self, String location) -> bool | CanOpen(self, String location) -> bool | [
"CanOpen",
"(",
"self",
"String",
"location",
")",
"-",
">",
"bool"
] | def CanOpen(*args, **kwargs):
"""CanOpen(self, String location) -> bool"""
return _core_.MemoryFSHandler_CanOpen(*args, **kwargs) | [
"def",
"CanOpen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MemoryFSHandler_CanOpen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L2574-L2576 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mailbox.py | python | MaildirMessage.add_flag | (self, flag) | Set the given flag(s) without changing others. | Set the given flag(s) without changing others. | [
"Set",
"the",
"given",
"flag",
"(",
"s",
")",
"without",
"changing",
"others",
"."
] | def add_flag(self, flag):
"""Set the given flag(s) without changing others."""
self.set_flags(''.join(set(self.get_flags()) | set(flag))) | [
"def",
"add_flag",
"(",
"self",
",",
"flag",
")",
":",
"self",
".",
"set_flags",
"(",
"''",
".",
"join",
"(",
"set",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"|",
"set",
"(",
"flag",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L1513-L1515 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/six.py | python | _import_module | (name) | return sys.modules[name] | Import module, returning the module after the last dot. | Import module, returning the module after the last dot. | [
"Import",
"module",
"returning",
"the",
"module",
"after",
"the",
"last",
"dot",
"."
] | def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name] | [
"def",
"_import_module",
"(",
"name",
")",
":",
"__import__",
"(",
"name",
")",
"return",
"sys",
".",
"modules",
"[",
"name",
"]"
] | 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/six.py#L80-L83 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/parso/py2/parso/python/diff.py | python | DiffParser._parse | (self, until_line) | Parses at least until the given line, but might just parse more until a
valid state is reached. | Parses at least until the given line, but might just parse more until a
valid state is reached. | [
"Parses",
"at",
"least",
"until",
"the",
"given",
"line",
"but",
"might",
"just",
"parse",
"more",
"until",
"a",
"valid",
"state",
"is",
"reached",
"."
] | def _parse(self, until_line):
"""
Parses at least until the given line, but might just parse more until a
valid state is reached.
"""
last_until_line = 0
while until_line > self._nodes_tree.parsed_until_line:
node = self._try_parse_part(until_line)
nodes = node.children
self._nodes_tree.add_parsed_nodes(nodes, self._keyword_token_indents)
if self._replace_tos_indent is not None:
self._nodes_tree.indents[-1] = self._replace_tos_indent
LOG.debug(
'parse_part from %s to %s (to %s in part parser)',
nodes[0].get_start_pos_of_prefix()[0],
self._nodes_tree.parsed_until_line,
node.end_pos[0] - 1
)
# Since the tokenizer sometimes has bugs, we cannot be sure that
# this loop terminates. Therefore assert that there's always a
# change.
assert last_until_line != self._nodes_tree.parsed_until_line, last_until_line
last_until_line = self._nodes_tree.parsed_until_line | [
"def",
"_parse",
"(",
"self",
",",
"until_line",
")",
":",
"last_until_line",
"=",
"0",
"while",
"until_line",
">",
"self",
".",
"_nodes_tree",
".",
"parsed_until_line",
":",
"node",
"=",
"self",
".",
"_try_parse_part",
"(",
"until_line",
")",
"nodes",
"=",
"node",
".",
"children",
"self",
".",
"_nodes_tree",
".",
"add_parsed_nodes",
"(",
"nodes",
",",
"self",
".",
"_keyword_token_indents",
")",
"if",
"self",
".",
"_replace_tos_indent",
"is",
"not",
"None",
":",
"self",
".",
"_nodes_tree",
".",
"indents",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"_replace_tos_indent",
"LOG",
".",
"debug",
"(",
"'parse_part from %s to %s (to %s in part parser)'",
",",
"nodes",
"[",
"0",
"]",
".",
"get_start_pos_of_prefix",
"(",
")",
"[",
"0",
"]",
",",
"self",
".",
"_nodes_tree",
".",
"parsed_until_line",
",",
"node",
".",
"end_pos",
"[",
"0",
"]",
"-",
"1",
")",
"# Since the tokenizer sometimes has bugs, we cannot be sure that",
"# this loop terminates. Therefore assert that there's always a",
"# change.",
"assert",
"last_until_line",
"!=",
"self",
".",
"_nodes_tree",
".",
"parsed_until_line",
",",
"last_until_line",
"last_until_line",
"=",
"self",
".",
"_nodes_tree",
".",
"parsed_until_line"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/parso/py2/parso/python/diff.py#L407-L431 | ||
weichengkuo/DeepBox | c4f8c065b6a51cf296540cc453a44f0519aaacc9 | caffe-fast-rcnn/scripts/cpp_lint.py | python | CleanseRawStrings | (raw_lines) | return lines_without_raw_strings | Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings. | Removes C++11 raw strings from lines. | [
"Removes",
"C",
"++",
"11",
"raw",
"strings",
"from",
"lines",
"."
] | def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings.
"""
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and resume copying the original lines, and also insert
# a "" on the last line.
leading_space = Match(r'^(\s*)\S', line)
line = leading_space.group(1) + '""' + line[end + len(delimiter):]
delimiter = None
else:
# Haven't found the end yet, append a blank line.
line = ''
else:
# Look for beginning of a raw string.
# See 2.14.15 [lex.string] for syntax.
matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if matched:
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + '""' +
matched.group(3)[end + len(delimiter):])
delimiter = None
else:
# Start of a multi-line raw string
line = matched.group(1) + '""'
lines_without_raw_strings.append(line)
# TODO(unknown): if delimiter is not None here, we might want to
# emit a warning for unterminated string.
return lines_without_raw_strings | [
"def",
"CleanseRawStrings",
"(",
"raw_lines",
")",
":",
"delimiter",
"=",
"None",
"lines_without_raw_strings",
"=",
"[",
"]",
"for",
"line",
"in",
"raw_lines",
":",
"if",
"delimiter",
":",
"# Inside a raw string, look for the end",
"end",
"=",
"line",
".",
"find",
"(",
"delimiter",
")",
"if",
"end",
">=",
"0",
":",
"# Found the end of the string, match leading space for this",
"# line and resume copying the original lines, and also insert",
"# a \"\" on the last line.",
"leading_space",
"=",
"Match",
"(",
"r'^(\\s*)\\S'",
",",
"line",
")",
"line",
"=",
"leading_space",
".",
"group",
"(",
"1",
")",
"+",
"'\"\"'",
"+",
"line",
"[",
"end",
"+",
"len",
"(",
"delimiter",
")",
":",
"]",
"delimiter",
"=",
"None",
"else",
":",
"# Haven't found the end yet, append a blank line.",
"line",
"=",
"''",
"else",
":",
"# Look for beginning of a raw string.",
"# See 2.14.15 [lex.string] for syntax.",
"matched",
"=",
"Match",
"(",
"r'^(.*)\\b(?:R|u8R|uR|UR|LR)\"([^\\s\\\\()]*)\\((.*)$'",
",",
"line",
")",
"if",
"matched",
":",
"delimiter",
"=",
"')'",
"+",
"matched",
".",
"group",
"(",
"2",
")",
"+",
"'\"'",
"end",
"=",
"matched",
".",
"group",
"(",
"3",
")",
".",
"find",
"(",
"delimiter",
")",
"if",
"end",
">=",
"0",
":",
"# Raw string ended on same line",
"line",
"=",
"(",
"matched",
".",
"group",
"(",
"1",
")",
"+",
"'\"\"'",
"+",
"matched",
".",
"group",
"(",
"3",
")",
"[",
"end",
"+",
"len",
"(",
"delimiter",
")",
":",
"]",
")",
"delimiter",
"=",
"None",
"else",
":",
"# Start of a multi-line raw string",
"line",
"=",
"matched",
".",
"group",
"(",
"1",
")",
"+",
"'\"\"'",
"lines_without_raw_strings",
".",
"append",
"(",
"line",
")",
"# TODO(unknown): if delimiter is not None here, we might want to",
"# emit a warning for unterminated string.",
"return",
"lines_without_raw_strings"
] | https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L1062-L1120 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/protocols/housekeepingprotocol.py | python | Jtagice3HousekeepingProtocol.end_session | (self, reset_tool=False) | Ends a session with the debugger (sign-off)
:param reset_tool: resets the hardware
:return: | Ends a session with the debugger (sign-off) | [
"Ends",
"a",
"session",
"with",
"the",
"debugger",
"(",
"sign",
"-",
"off",
")"
] | def end_session(self, reset_tool=False):
"""
Ends a session with the debugger (sign-off)
:param reset_tool: resets the hardware
:return:
"""
self.logger.debug("Housekeeping::end_session")
response = self.jtagice3_command_response(
bytearray([self.CMD_HOUSEKEEPING_END_SESSION, self.CMD_VERSION0, 1 if reset_tool else 0]))
self.check_response(response) | [
"def",
"end_session",
"(",
"self",
",",
"reset_tool",
"=",
"False",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Housekeeping::end_session\"",
")",
"response",
"=",
"self",
".",
"jtagice3_command_response",
"(",
"bytearray",
"(",
"[",
"self",
".",
"CMD_HOUSEKEEPING_END_SESSION",
",",
"self",
".",
"CMD_VERSION0",
",",
"1",
"if",
"reset_tool",
"else",
"0",
"]",
")",
")",
"self",
".",
"check_response",
"(",
"response",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/housekeepingprotocol.py#L85-L95 | ||
may0324/DeepCompression-caffe | 0aff6c1287bda4cfc7f378ed8a16524e1afabd8c | python/caffe/net_spec.py | python | to_proto | (*tops) | return net | Generate a NetParameter that contains all layers needed to compute
all arguments. | Generate a NetParameter that contains all layers needed to compute
all arguments. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"all",
"arguments",
"."
] | def to_proto(*tops):
"""Generate a NetParameter that contains all layers needed to compute
all arguments."""
layers = OrderedDict()
autonames = Counter()
for top in tops:
top.fn._to_proto(layers, {}, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net | [
"def",
"to_proto",
"(",
"*",
"tops",
")",
":",
"layers",
"=",
"OrderedDict",
"(",
")",
"autonames",
"=",
"Counter",
"(",
")",
"for",
"top",
"in",
"tops",
":",
"top",
".",
"fn",
".",
"_to_proto",
"(",
"layers",
",",
"{",
"}",
",",
"autonames",
")",
"net",
"=",
"caffe_pb2",
".",
"NetParameter",
"(",
")",
"net",
".",
"layer",
".",
"extend",
"(",
"layers",
".",
"values",
"(",
")",
")",
"return",
"net"
] | https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/python/caffe/net_spec.py#L43-L53 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/command.py | python | FbCmd.get_shortcut_help | (self) | return [(key, "Shortcut for %s" % val) for key,val in self.shortcutKeys.items()] | Shortcut help | Shortcut help | [
"Shortcut",
"help"
] | def get_shortcut_help(self):
"""Shortcut help"""
return [(key, "Shortcut for %s" % val) for key,val in self.shortcutKeys.items()] | [
"def",
"get_shortcut_help",
"(",
"self",
")",
":",
"return",
"[",
"(",
"key",
",",
"\"Shortcut for %s\"",
"%",
"val",
")",
"for",
"key",
",",
"val",
"in",
"self",
".",
"shortcutKeys",
".",
"items",
"(",
")",
"]"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/command.py#L367-L369 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/deps/protobuf/python/mox.py | python | Verify | (*args) | Verify mocks.
Args:
# args is any number of mocks to be verified. | Verify mocks. | [
"Verify",
"mocks",
"."
] | def Verify(*args):
"""Verify mocks.
Args:
# args is any number of mocks to be verified.
"""
for mock in args:
mock._Verify() | [
"def",
"Verify",
"(",
"*",
"args",
")",
":",
"for",
"mock",
"in",
"args",
":",
"mock",
".",
"_Verify",
"(",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/mox.py#L246-L254 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | CalculateLayoutEvent.SetFlags | (*args, **kwargs) | return _windows_.CalculateLayoutEvent_SetFlags(*args, **kwargs) | SetFlags(self, int flags) | SetFlags(self, int flags) | [
"SetFlags",
"(",
"self",
"int",
"flags",
")"
] | def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _windows_.CalculateLayoutEvent_SetFlags(*args, **kwargs) | [
"def",
"SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"CalculateLayoutEvent_SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L2011-L2013 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/sized_controls.py | python | GetSizerProps | (self) | return props | Returns a dictionary of prop name + value | Returns a dictionary of prop name + value | [
"Returns",
"a",
"dictionary",
"of",
"prop",
"name",
"+",
"value"
] | def GetSizerProps(self):
"""
Returns a dictionary of prop name + value
"""
props = {}
item = self.GetParent().GetSizer().GetItem(self)
if item is None:
return None
props['proportion'] = item.GetProportion()
flags = item.GetFlag()
if flags & border['all'] == border['all']:
props['border'] = (['all'], item.GetBorder())
else:
borders = []
for key in border:
if flags & border[key]:
borders.append(key)
props['border'] = (borders, item.GetBorder())
if flags & align['center'] == align['center']:
props['align'] = 'center'
else:
for key in halign:
if flags & halign[key]:
props['halign'] = key
for key in valign:
if flags & valign[key]:
props['valign'] = key
for key in minsize:
if flags & minsize[key]:
props['minsize'] = key
for key in misc_flags:
if flags & misc_flags[key]:
props[key] = "true"
return props | [
"def",
"GetSizerProps",
"(",
"self",
")",
":",
"props",
"=",
"{",
"}",
"item",
"=",
"self",
".",
"GetParent",
"(",
")",
".",
"GetSizer",
"(",
")",
".",
"GetItem",
"(",
"self",
")",
"if",
"item",
"is",
"None",
":",
"return",
"None",
"props",
"[",
"'proportion'",
"]",
"=",
"item",
".",
"GetProportion",
"(",
")",
"flags",
"=",
"item",
".",
"GetFlag",
"(",
")",
"if",
"flags",
"&",
"border",
"[",
"'all'",
"]",
"==",
"border",
"[",
"'all'",
"]",
":",
"props",
"[",
"'border'",
"]",
"=",
"(",
"[",
"'all'",
"]",
",",
"item",
".",
"GetBorder",
"(",
")",
")",
"else",
":",
"borders",
"=",
"[",
"]",
"for",
"key",
"in",
"border",
":",
"if",
"flags",
"&",
"border",
"[",
"key",
"]",
":",
"borders",
".",
"append",
"(",
"key",
")",
"props",
"[",
"'border'",
"]",
"=",
"(",
"borders",
",",
"item",
".",
"GetBorder",
"(",
")",
")",
"if",
"flags",
"&",
"align",
"[",
"'center'",
"]",
"==",
"align",
"[",
"'center'",
"]",
":",
"props",
"[",
"'align'",
"]",
"=",
"'center'",
"else",
":",
"for",
"key",
"in",
"halign",
":",
"if",
"flags",
"&",
"halign",
"[",
"key",
"]",
":",
"props",
"[",
"'halign'",
"]",
"=",
"key",
"for",
"key",
"in",
"valign",
":",
"if",
"flags",
"&",
"valign",
"[",
"key",
"]",
":",
"props",
"[",
"'valign'",
"]",
"=",
"key",
"for",
"key",
"in",
"minsize",
":",
"if",
"flags",
"&",
"minsize",
"[",
"key",
"]",
":",
"props",
"[",
"'minsize'",
"]",
"=",
"key",
"for",
"key",
"in",
"misc_flags",
":",
"if",
"flags",
"&",
"misc_flags",
"[",
"key",
"]",
":",
"props",
"[",
"key",
"]",
"=",
"\"true\"",
"return",
"props"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/sized_controls.py#L289-L331 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBExpressionOptions.GetTrapExceptions | (self) | return _lldb.SBExpressionOptions_GetTrapExceptions(self) | GetTrapExceptions(SBExpressionOptions self) -> bool | GetTrapExceptions(SBExpressionOptions self) -> bool | [
"GetTrapExceptions",
"(",
"SBExpressionOptions",
"self",
")",
"-",
">",
"bool"
] | def GetTrapExceptions(self):
"""GetTrapExceptions(SBExpressionOptions self) -> bool"""
return _lldb.SBExpressionOptions_GetTrapExceptions(self) | [
"def",
"GetTrapExceptions",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBExpressionOptions_GetTrapExceptions",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L5034-L5036 | |
DLR-SC/tigl | d1c5901e948e33d10b1f9659ff3e22c4717b455f | thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py | python | CppLexerNavigator.GetNextTokenSkipWhiteSpaceAndComment | (self) | return self.GetNextToken(True, True) | Get Next Token skip whitespace and comment.
This method changes the current lex position. | Get Next Token skip whitespace and comment.
This method changes the current lex position. | [
"Get",
"Next",
"Token",
"skip",
"whitespace",
"and",
"comment",
".",
"This",
"method",
"changes",
"the",
"current",
"lex",
"position",
"."
] | def GetNextTokenSkipWhiteSpaceAndComment(self):
"""
Get Next Token skip whitespace and comment.
This method changes the current lex position.
"""
return self.GetNextToken(True, True) | [
"def",
"GetNextTokenSkipWhiteSpaceAndComment",
"(",
"self",
")",
":",
"return",
"self",
".",
"GetNextToken",
"(",
"True",
",",
"True",
")"
] | https://github.com/DLR-SC/tigl/blob/d1c5901e948e33d10b1f9659ff3e22c4717b455f/thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py#L508-L514 | |
nileshkulkarni/csm | 0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc | csm/nnutils/geom_utils.py | python | hamilton_product | (qa, qb) | return torch.stack([q_mult_0, q_mult_1, q_mult_2, q_mult_3], dim=-1) | Multiply qa by qb.
Args:
qa: B X N X 4 quaternions
qb: B X N X 4 quaternions
Returns:
q_mult: B X N X 4 | Multiply qa by qb. | [
"Multiply",
"qa",
"by",
"qb",
"."
] | def hamilton_product(qa, qb):
"""Multiply qa by qb.
Args:
qa: B X N X 4 quaternions
qb: B X N X 4 quaternions
Returns:
q_mult: B X N X 4
"""
qa_0 = qa[:, :, 0]
qa_1 = qa[:, :, 1]
qa_2 = qa[:, :, 2]
qa_3 = qa[:, :, 3]
qb_0 = qb[:, :, 0]
qb_1 = qb[:, :, 1]
qb_2 = qb[:, :, 2]
qb_3 = qb[:, :, 3]
# See https://en.wikipedia.org/wiki/Quaternion#Hamilton_product
q_mult_0 = qa_0 * qb_0 - qa_1 * qb_1 - qa_2 * qb_2 - qa_3 * qb_3
q_mult_1 = qa_0 * qb_1 + qa_1 * qb_0 + qa_2 * qb_3 - qa_3 * qb_2
q_mult_2 = qa_0 * qb_2 - qa_1 * qb_3 + qa_2 * qb_0 + qa_3 * qb_1
q_mult_3 = qa_0 * qb_3 + qa_1 * qb_2 - qa_2 * qb_1 + qa_3 * qb_0
return torch.stack([q_mult_0, q_mult_1, q_mult_2, q_mult_3], dim=-1) | [
"def",
"hamilton_product",
"(",
"qa",
",",
"qb",
")",
":",
"qa_0",
"=",
"qa",
"[",
":",
",",
":",
",",
"0",
"]",
"qa_1",
"=",
"qa",
"[",
":",
",",
":",
",",
"1",
"]",
"qa_2",
"=",
"qa",
"[",
":",
",",
":",
",",
"2",
"]",
"qa_3",
"=",
"qa",
"[",
":",
",",
":",
",",
"3",
"]",
"qb_0",
"=",
"qb",
"[",
":",
",",
":",
",",
"0",
"]",
"qb_1",
"=",
"qb",
"[",
":",
",",
":",
",",
"1",
"]",
"qb_2",
"=",
"qb",
"[",
":",
",",
":",
",",
"2",
"]",
"qb_3",
"=",
"qb",
"[",
":",
",",
":",
",",
"3",
"]",
"# See https://en.wikipedia.org/wiki/Quaternion#Hamilton_product",
"q_mult_0",
"=",
"qa_0",
"*",
"qb_0",
"-",
"qa_1",
"*",
"qb_1",
"-",
"qa_2",
"*",
"qb_2",
"-",
"qa_3",
"*",
"qb_3",
"q_mult_1",
"=",
"qa_0",
"*",
"qb_1",
"+",
"qa_1",
"*",
"qb_0",
"+",
"qa_2",
"*",
"qb_3",
"-",
"qa_3",
"*",
"qb_2",
"q_mult_2",
"=",
"qa_0",
"*",
"qb_2",
"-",
"qa_1",
"*",
"qb_3",
"+",
"qa_2",
"*",
"qb_0",
"+",
"qa_3",
"*",
"qb_1",
"q_mult_3",
"=",
"qa_0",
"*",
"qb_3",
"+",
"qa_1",
"*",
"qb_2",
"-",
"qa_2",
"*",
"qb_1",
"+",
"qa_3",
"*",
"qb_0",
"return",
"torch",
".",
"stack",
"(",
"[",
"q_mult_0",
",",
"q_mult_1",
",",
"q_mult_2",
",",
"q_mult_3",
"]",
",",
"dim",
"=",
"-",
"1",
")"
] | https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/nnutils/geom_utils.py#L168-L193 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/linalg/linalg_impl.py | python | _matrix_exp_pade3 | (matrix) | return matrix_u, matrix_v | 3rd-order Pade approximant for matrix exponential. | 3rd-order Pade approximant for matrix exponential. | [
"3rd",
"-",
"order",
"Pade",
"approximant",
"for",
"matrix",
"exponential",
"."
] | def _matrix_exp_pade3(matrix):
"""3rd-order Pade approximant for matrix exponential."""
b = [120.0, 60.0, 12.0]
b = [constant_op.constant(x, matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
tmp = matrix_2 + b[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[2] * matrix_2 + b[0] * ident
return matrix_u, matrix_v | [
"def",
"_matrix_exp_pade3",
"(",
"matrix",
")",
":",
"b",
"=",
"[",
"120.0",
",",
"60.0",
",",
"12.0",
"]",
"b",
"=",
"[",
"constant_op",
".",
"constant",
"(",
"x",
",",
"matrix",
".",
"dtype",
")",
"for",
"x",
"in",
"b",
"]",
"ident",
"=",
"linalg_ops",
".",
"eye",
"(",
"array_ops",
".",
"shape",
"(",
"matrix",
")",
"[",
"-",
"2",
"]",
",",
"batch_shape",
"=",
"array_ops",
".",
"shape",
"(",
"matrix",
")",
"[",
":",
"-",
"2",
"]",
",",
"dtype",
"=",
"matrix",
".",
"dtype",
")",
"matrix_2",
"=",
"math_ops",
".",
"matmul",
"(",
"matrix",
",",
"matrix",
")",
"tmp",
"=",
"matrix_2",
"+",
"b",
"[",
"1",
"]",
"*",
"ident",
"matrix_u",
"=",
"math_ops",
".",
"matmul",
"(",
"matrix",
",",
"tmp",
")",
"matrix_v",
"=",
"b",
"[",
"2",
"]",
"*",
"matrix_2",
"+",
"b",
"[",
"0",
"]",
"*",
"ident",
"return",
"matrix_u",
",",
"matrix_v"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/linalg/linalg_impl.py#L132-L144 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/utils/llvm-build/llvmbuild/main.py | python | LLVMProjectInfo.validate_components | (self) | validate_components() -> None
Validate that the project components are well-defined. Among other
things, this checks that:
- Components have valid references.
- Components references do not form cycles.
We also construct the map from component names to info, and the
topological ordering of components. | validate_components() -> None | [
"validate_components",
"()",
"-",
">",
"None"
] | def validate_components(self):
"""validate_components() -> None
Validate that the project components are well-defined. Among other
things, this checks that:
- Components have valid references.
- Components references do not form cycles.
We also construct the map from component names to info, and the
topological ordering of components.
"""
# Create the component info map and validate that component names are
# unique.
self.component_info_map = {}
for ci in self.component_infos:
existing = self.component_info_map.get(ci.name)
if existing is not None:
# We found a duplicate component name, report it and error out.
fatal("found duplicate component %r (at %r and %r)" % (
ci.name, ci.subpath, existing.subpath))
self.component_info_map[ci.name] = ci
# Disallow 'all' as a component name, which is a special case.
if 'all' in self.component_info_map:
fatal("project is not allowed to define 'all' component")
# Add the root component.
if '$ROOT' in self.component_info_map:
fatal("project is not allowed to define $ROOT component")
self.component_info_map['$ROOT'] = componentinfo.GroupComponentInfo(
'/', '$ROOT', None)
self.component_infos.append(self.component_info_map['$ROOT'])
# Topologically order the component information according to their
# component references.
def visit_component_info(ci, current_stack, current_set):
# Check for a cycles.
if ci in current_set:
# We found a cycle, report it and error out.
cycle_description = ' -> '.join(
'%r (%s)' % (ci.name, relation)
for relation,ci in current_stack)
fatal("found cycle to %r after following: %s -> %s" % (
ci.name, cycle_description, ci.name))
# If we have already visited this item, we are done.
if ci not in components_to_visit:
return
# Otherwise, mark the component info as visited and traverse.
components_to_visit.remove(ci)
# Validate the parent reference, which we treat specially.
if ci.parent is not None:
parent = self.component_info_map.get(ci.parent)
if parent is None:
fatal("component %r has invalid reference %r (via %r)" % (
ci.name, ci.parent, 'parent'))
ci.set_parent_instance(parent)
for relation,referent_name in ci.get_component_references():
# Validate that the reference is ok.
referent = self.component_info_map.get(referent_name)
if referent is None:
fatal("component %r has invalid reference %r (via %r)" % (
ci.name, referent_name, relation))
# Visit the reference.
current_stack.append((relation,ci))
current_set.add(ci)
visit_component_info(referent, current_stack, current_set)
current_set.remove(ci)
current_stack.pop()
# Finally, add the component info to the ordered list.
self.ordered_component_infos.append(ci)
# FIXME: We aren't actually correctly checking for cycles along the
# parent edges. Haven't decided how I want to handle this -- I thought
# about only checking cycles by relation type. If we do that, it falls
# out easily. If we don't, we should special case the check.
self.ordered_component_infos = []
components_to_visit = sorted(
set(self.component_infos),
key = lambda c: c.name)
while components_to_visit:
visit_component_info(components_to_visit[0], [], set())
# Canonicalize children lists.
for c in self.ordered_component_infos:
c.children.sort(key = lambda c: c.name) | [
"def",
"validate_components",
"(",
"self",
")",
":",
"# Create the component info map and validate that component names are",
"# unique.",
"self",
".",
"component_info_map",
"=",
"{",
"}",
"for",
"ci",
"in",
"self",
".",
"component_infos",
":",
"existing",
"=",
"self",
".",
"component_info_map",
".",
"get",
"(",
"ci",
".",
"name",
")",
"if",
"existing",
"is",
"not",
"None",
":",
"# We found a duplicate component name, report it and error out.",
"fatal",
"(",
"\"found duplicate component %r (at %r and %r)\"",
"%",
"(",
"ci",
".",
"name",
",",
"ci",
".",
"subpath",
",",
"existing",
".",
"subpath",
")",
")",
"self",
".",
"component_info_map",
"[",
"ci",
".",
"name",
"]",
"=",
"ci",
"# Disallow 'all' as a component name, which is a special case.",
"if",
"'all'",
"in",
"self",
".",
"component_info_map",
":",
"fatal",
"(",
"\"project is not allowed to define 'all' component\"",
")",
"# Add the root component.",
"if",
"'$ROOT'",
"in",
"self",
".",
"component_info_map",
":",
"fatal",
"(",
"\"project is not allowed to define $ROOT component\"",
")",
"self",
".",
"component_info_map",
"[",
"'$ROOT'",
"]",
"=",
"componentinfo",
".",
"GroupComponentInfo",
"(",
"'/'",
",",
"'$ROOT'",
",",
"None",
")",
"self",
".",
"component_infos",
".",
"append",
"(",
"self",
".",
"component_info_map",
"[",
"'$ROOT'",
"]",
")",
"# Topologically order the component information according to their",
"# component references.",
"def",
"visit_component_info",
"(",
"ci",
",",
"current_stack",
",",
"current_set",
")",
":",
"# Check for a cycles.",
"if",
"ci",
"in",
"current_set",
":",
"# We found a cycle, report it and error out.",
"cycle_description",
"=",
"' -> '",
".",
"join",
"(",
"'%r (%s)'",
"%",
"(",
"ci",
".",
"name",
",",
"relation",
")",
"for",
"relation",
",",
"ci",
"in",
"current_stack",
")",
"fatal",
"(",
"\"found cycle to %r after following: %s -> %s\"",
"%",
"(",
"ci",
".",
"name",
",",
"cycle_description",
",",
"ci",
".",
"name",
")",
")",
"# If we have already visited this item, we are done.",
"if",
"ci",
"not",
"in",
"components_to_visit",
":",
"return",
"# Otherwise, mark the component info as visited and traverse.",
"components_to_visit",
".",
"remove",
"(",
"ci",
")",
"# Validate the parent reference, which we treat specially.",
"if",
"ci",
".",
"parent",
"is",
"not",
"None",
":",
"parent",
"=",
"self",
".",
"component_info_map",
".",
"get",
"(",
"ci",
".",
"parent",
")",
"if",
"parent",
"is",
"None",
":",
"fatal",
"(",
"\"component %r has invalid reference %r (via %r)\"",
"%",
"(",
"ci",
".",
"name",
",",
"ci",
".",
"parent",
",",
"'parent'",
")",
")",
"ci",
".",
"set_parent_instance",
"(",
"parent",
")",
"for",
"relation",
",",
"referent_name",
"in",
"ci",
".",
"get_component_references",
"(",
")",
":",
"# Validate that the reference is ok.",
"referent",
"=",
"self",
".",
"component_info_map",
".",
"get",
"(",
"referent_name",
")",
"if",
"referent",
"is",
"None",
":",
"fatal",
"(",
"\"component %r has invalid reference %r (via %r)\"",
"%",
"(",
"ci",
".",
"name",
",",
"referent_name",
",",
"relation",
")",
")",
"# Visit the reference.",
"current_stack",
".",
"append",
"(",
"(",
"relation",
",",
"ci",
")",
")",
"current_set",
".",
"add",
"(",
"ci",
")",
"visit_component_info",
"(",
"referent",
",",
"current_stack",
",",
"current_set",
")",
"current_set",
".",
"remove",
"(",
"ci",
")",
"current_stack",
".",
"pop",
"(",
")",
"# Finally, add the component info to the ordered list.",
"self",
".",
"ordered_component_infos",
".",
"append",
"(",
"ci",
")",
"# FIXME: We aren't actually correctly checking for cycles along the",
"# parent edges. Haven't decided how I want to handle this -- I thought",
"# about only checking cycles by relation type. If we do that, it falls",
"# out easily. If we don't, we should special case the check.",
"self",
".",
"ordered_component_infos",
"=",
"[",
"]",
"components_to_visit",
"=",
"sorted",
"(",
"set",
"(",
"self",
".",
"component_infos",
")",
",",
"key",
"=",
"lambda",
"c",
":",
"c",
".",
"name",
")",
"while",
"components_to_visit",
":",
"visit_component_info",
"(",
"components_to_visit",
"[",
"0",
"]",
",",
"[",
"]",
",",
"set",
"(",
")",
")",
"# Canonicalize children lists.",
"for",
"c",
"in",
"self",
".",
"ordered_component_infos",
":",
"c",
".",
"children",
".",
"sort",
"(",
"key",
"=",
"lambda",
"c",
":",
"c",
".",
"name",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/llvm-build/llvmbuild/main.py#L90-L182 | ||
dmlc/rabit | f307acebdc8b165e6d50dce2e287a1bc3eec8870 | python/rabit.py | python | finalize | () | Finalize the rabit engine.
Call this function after you finished all jobs. | Finalize the rabit engine. | [
"Finalize",
"the",
"rabit",
"engine",
"."
] | def finalize():
"""Finalize the rabit engine.
Call this function after you finished all jobs.
"""
_LIB.RabitFinalize()
_unloadlib() | [
"def",
"finalize",
"(",
")",
":",
"_LIB",
".",
"RabitFinalize",
"(",
")",
"_unloadlib",
"(",
")"
] | https://github.com/dmlc/rabit/blob/f307acebdc8b165e6d50dce2e287a1bc3eec8870/python/rabit.py#L112-L118 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/transform.py | python | Transform.parameters | (self) | return {name: getattr(self, name) for name in property_param_names} | A dict of names to values of properties marked with `@parameter`. | A dict of names to values of properties marked with ` | [
"A",
"dict",
"of",
"names",
"to",
"values",
"of",
"properties",
"marked",
"with"
] | def parameters(self):
"""A dict of names to values of properties marked with `@parameter`."""
property_param_names = [name
for name, func in inspect.getmembers(type(self))
if (hasattr(func, "fget") and hasattr(
getattr(func, "fget"), "is_parameter"))]
return {name: getattr(self, name) for name in property_param_names} | [
"def",
"parameters",
"(",
"self",
")",
":",
"property_param_names",
"=",
"[",
"name",
"for",
"name",
",",
"func",
"in",
"inspect",
".",
"getmembers",
"(",
"type",
"(",
"self",
")",
")",
"if",
"(",
"hasattr",
"(",
"func",
",",
"\"fget\"",
")",
"and",
"hasattr",
"(",
"getattr",
"(",
"func",
",",
"\"fget\"",
")",
",",
"\"is_parameter\"",
")",
")",
"]",
"return",
"{",
"name",
":",
"getattr",
"(",
"self",
",",
"name",
")",
"for",
"name",
"in",
"property_param_names",
"}"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/transform.py#L120-L126 | |
UDST/pandana | 3e3d35ca2d57428714b89ed8fc7020bc55067e1d | pandana/network.py | python | Network.shortest_paths | (self, nodes_a, nodes_b, imp_name=None) | return [self.node_ids.values[p] for p in paths] | Vectorized calculation of shortest paths. Accepts a list of origins
and list of destinations and returns a corresponding list of
shortest path routes. Must provide an impedance name if more than
one is available.
Added in Pandana v0.6.
Parameters
----------
nodes_a : list-like of ints
Source node IDs
nodes_b : list-like of ints
Corresponding destination node IDs
imp_name : string
The impedance name to use for the shortest path
Returns
-------
paths : list of np.ndarray
Nodes traversed in each shortest path | Vectorized calculation of shortest paths. Accepts a list of origins
and list of destinations and returns a corresponding list of
shortest path routes. Must provide an impedance name if more than
one is available. | [
"Vectorized",
"calculation",
"of",
"shortest",
"paths",
".",
"Accepts",
"a",
"list",
"of",
"origins",
"and",
"list",
"of",
"destinations",
"and",
"returns",
"a",
"corresponding",
"list",
"of",
"shortest",
"path",
"routes",
".",
"Must",
"provide",
"an",
"impedance",
"name",
"if",
"more",
"than",
"one",
"is",
"available",
"."
] | def shortest_paths(self, nodes_a, nodes_b, imp_name=None):
"""
Vectorized calculation of shortest paths. Accepts a list of origins
and list of destinations and returns a corresponding list of
shortest path routes. Must provide an impedance name if more than
one is available.
Added in Pandana v0.6.
Parameters
----------
nodes_a : list-like of ints
Source node IDs
nodes_b : list-like of ints
Corresponding destination node IDs
imp_name : string
The impedance name to use for the shortest path
Returns
-------
paths : list of np.ndarray
Nodes traversed in each shortest path
"""
if len(nodes_a) != len(nodes_b):
raise ValueError("Origin and destination counts don't match: {}, {}"
.format(len(nodes_a), len(nodes_b)))
# map to internal node indexes
nodes_a_idx = self._node_indexes(pd.Series(nodes_a)).values
nodes_b_idx = self._node_indexes(pd.Series(nodes_b)).values
imp_num = self._imp_name_to_num(imp_name)
paths = self.net.shortest_paths(nodes_a_idx, nodes_b_idx, imp_num)
# map back to external node ids
return [self.node_ids.values[p] for p in paths] | [
"def",
"shortest_paths",
"(",
"self",
",",
"nodes_a",
",",
"nodes_b",
",",
"imp_name",
"=",
"None",
")",
":",
"if",
"len",
"(",
"nodes_a",
")",
"!=",
"len",
"(",
"nodes_b",
")",
":",
"raise",
"ValueError",
"(",
"\"Origin and destination counts don't match: {}, {}\"",
".",
"format",
"(",
"len",
"(",
"nodes_a",
")",
",",
"len",
"(",
"nodes_b",
")",
")",
")",
"# map to internal node indexes",
"nodes_a_idx",
"=",
"self",
".",
"_node_indexes",
"(",
"pd",
".",
"Series",
"(",
"nodes_a",
")",
")",
".",
"values",
"nodes_b_idx",
"=",
"self",
".",
"_node_indexes",
"(",
"pd",
".",
"Series",
"(",
"nodes_b",
")",
")",
".",
"values",
"imp_num",
"=",
"self",
".",
"_imp_name_to_num",
"(",
"imp_name",
")",
"paths",
"=",
"self",
".",
"net",
".",
"shortest_paths",
"(",
"nodes_a_idx",
",",
"nodes_b_idx",
",",
"imp_num",
")",
"# map back to external node ids",
"return",
"[",
"self",
".",
"node_ids",
".",
"values",
"[",
"p",
"]",
"for",
"p",
"in",
"paths",
"]"
] | https://github.com/UDST/pandana/blob/3e3d35ca2d57428714b89ed8fc7020bc55067e1d/pandana/network.py#L202-L239 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/sparse/series.py | python | SparseSeries.set_value | (self, label, value, takeable=False) | return self._set_value(label, value, takeable=takeable) | Quickly set single value at passed label. If label is not contained, a
new object is created with the label placed at the end of the result
index
.. deprecated:: 0.21.0
Please use .at[] or .iat[] accessors.
Parameters
----------
label : object
Partial indexing with MultiIndex not allowed
value : object
Scalar value
takeable : interpret the index as indexers, default False
Notes
-----
This method *always* returns a new object. It is not particularly
efficient but is provided for API compatibility with Series
Returns
-------
series : SparseSeries | Quickly set single value at passed label. If label is not contained, a
new object is created with the label placed at the end of the result
index | [
"Quickly",
"set",
"single",
"value",
"at",
"passed",
"label",
".",
"If",
"label",
"is",
"not",
"contained",
"a",
"new",
"object",
"is",
"created",
"with",
"the",
"label",
"placed",
"at",
"the",
"end",
"of",
"the",
"result",
"index"
] | def set_value(self, label, value, takeable=False):
"""
Quickly set single value at passed label. If label is not contained, a
new object is created with the label placed at the end of the result
index
.. deprecated:: 0.21.0
Please use .at[] or .iat[] accessors.
Parameters
----------
label : object
Partial indexing with MultiIndex not allowed
value : object
Scalar value
takeable : interpret the index as indexers, default False
Notes
-----
This method *always* returns a new object. It is not particularly
efficient but is provided for API compatibility with Series
Returns
-------
series : SparseSeries
"""
warnings.warn("set_value is deprecated and will be removed "
"in a future release. Please use "
".at[] or .iat[] accessors instead", FutureWarning,
stacklevel=2)
return self._set_value(label, value, takeable=takeable) | [
"def",
"set_value",
"(",
"self",
",",
"label",
",",
"value",
",",
"takeable",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"set_value is deprecated and will be removed \"",
"\"in a future release. Please use \"",
"\".at[] or .iat[] accessors instead\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"self",
".",
"_set_value",
"(",
"label",
",",
"value",
",",
"takeable",
"=",
"takeable",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/sparse/series.py#L374-L405 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/libs/onnx/onnx/utils.py | python | polish_model | (model) | return model | This function combines several useful utility functions together. | This function combines several useful utility functions together. | [
"This",
"function",
"combines",
"several",
"useful",
"utility",
"functions",
"together",
"."
] | def polish_model(model): # type: (ModelProto) -> ModelProto
'''
This function combines several useful utility functions together.
'''
onnx.checker.check_model(model)
onnx.helper.strip_doc_string(model)
model = onnx.shape_inference.infer_shapes(model)
model = onnx.optimizer.optimize(model)
onnx.checker.check_model(model)
return model | [
"def",
"polish_model",
"(",
"model",
")",
":",
"# type: (ModelProto) -> ModelProto",
"onnx",
".",
"checker",
".",
"check_model",
"(",
"model",
")",
"onnx",
".",
"helper",
".",
"strip_doc_string",
"(",
"model",
")",
"model",
"=",
"onnx",
".",
"shape_inference",
".",
"infer_shapes",
"(",
"model",
")",
"model",
"=",
"onnx",
".",
"optimizer",
".",
"optimize",
"(",
"model",
")",
"onnx",
".",
"checker",
".",
"check_model",
"(",
"model",
")",
"return",
"model"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/libs/onnx/onnx/utils.py#L14-L23 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PGProperty.Last | (*args, **kwargs) | return _propgrid.PGProperty_Last(*args, **kwargs) | Last(self) -> PGProperty | Last(self) -> PGProperty | [
"Last",
"(",
"self",
")",
"-",
">",
"PGProperty"
] | def Last(*args, **kwargs):
"""Last(self) -> PGProperty"""
return _propgrid.PGProperty_Last(*args, **kwargs) | [
"def",
"Last",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_Last",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L819-L821 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pydoc.py | python | classify_class_attrs | (object) | return results | Wrap inspect.classify_class_attrs, with fixup for data descriptors. | Wrap inspect.classify_class_attrs, with fixup for data descriptors. | [
"Wrap",
"inspect",
".",
"classify_class_attrs",
"with",
"fixup",
"for",
"data",
"descriptors",
"."
] | def classify_class_attrs(object):
"""Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
results = []
for (name, kind, cls, value) in inspect.classify_class_attrs(object):
if inspect.isdatadescriptor(value):
kind = 'data descriptor'
results.append((name, kind, cls, value))
return results | [
"def",
"classify_class_attrs",
"(",
"object",
")",
":",
"results",
"=",
"[",
"]",
"for",
"(",
"name",
",",
"kind",
",",
"cls",
",",
"value",
")",
"in",
"inspect",
".",
"classify_class_attrs",
"(",
"object",
")",
":",
"if",
"inspect",
".",
"isdatadescriptor",
"(",
"value",
")",
":",
"kind",
"=",
"'data descriptor'",
"results",
".",
"append",
"(",
"(",
"name",
",",
"kind",
",",
"cls",
",",
"value",
")",
")",
"return",
"results"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pydoc.py#L207-L214 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/command/alias.py | python | shquote | (arg) | return arg | Quote an argument for later parsing by shlex.split() | Quote an argument for later parsing by shlex.split() | [
"Quote",
"an",
"argument",
"for",
"later",
"parsing",
"by",
"shlex",
".",
"split",
"()"
] | def shquote(arg):
"""Quote an argument for later parsing by shlex.split()"""
for c in '"', "'", "\\", "#":
if c in arg:
return repr(arg)
if arg.split() != [arg]:
return repr(arg)
return arg | [
"def",
"shquote",
"(",
"arg",
")",
":",
"for",
"c",
"in",
"'\"'",
",",
"\"'\"",
",",
"\"\\\\\"",
",",
"\"#\"",
":",
"if",
"c",
"in",
"arg",
":",
"return",
"repr",
"(",
"arg",
")",
"if",
"arg",
".",
"split",
"(",
")",
"!=",
"[",
"arg",
"]",
":",
"return",
"repr",
"(",
"arg",
")",
"return",
"arg"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/alias.py#L8-L15 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py2/pygments/scanner.py | python | Scanner.test | (self, pattern) | return self.check(pattern) is not None | Apply a pattern on the current position and check
if it patches. Doesn't touch pos. | Apply a pattern on the current position and check
if it patches. Doesn't touch pos. | [
"Apply",
"a",
"pattern",
"on",
"the",
"current",
"position",
"and",
"check",
"if",
"it",
"patches",
".",
"Doesn",
"t",
"touch",
"pos",
"."
] | def test(self, pattern):
"""Apply a pattern on the current position and check
if it patches. Doesn't touch pos.
"""
return self.check(pattern) is not None | [
"def",
"test",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"self",
".",
"check",
"(",
"pattern",
")",
"is",
"not",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py2/pygments/scanner.py#L67-L71 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/IcoImagePlugin.py | python | IcoFile.frame | (self, idx) | return im | Get an image from frame idx | Get an image from frame idx | [
"Get",
"an",
"image",
"from",
"frame",
"idx"
] | def frame(self, idx):
"""
Get an image from frame idx
"""
header = self.entry[idx]
self.buf.seek(header["offset"])
data = self.buf.read(8)
self.buf.seek(header["offset"])
if data[:8] == PngImagePlugin._MAGIC:
# png frame
im = PngImagePlugin.PngImageFile(self.buf)
else:
# XOR + AND mask bmp frame
im = BmpImagePlugin.DibImageFile(self.buf)
Image._decompression_bomb_check(im.size)
# change tile dimension to only encompass XOR image
im._size = (im.size[0], int(im.size[1] / 2))
d, e, o, a = im.tile[0]
im.tile[0] = d, (0, 0) + im.size, o, a
# figure out where AND mask image starts
mode = a[0]
bpp = 8
for k, v in BmpImagePlugin.BIT2MODE.items():
if mode == v[1]:
bpp = k
break
if 32 == bpp:
# 32-bit color depth icon image allows semitransparent areas
# PIL's DIB format ignores transparency bits, recover them.
# The DIB is packed in BGRX byte order where X is the alpha
# channel.
# Back up to start of bmp data
self.buf.seek(o)
# extract every 4th byte (eg. 3,7,11,15,...)
alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
# convert to an 8bpp grayscale image
mask = Image.frombuffer(
"L", # 8bpp
im.size, # (w, h)
alpha_bytes, # source chars
"raw", # raw decoder
("L", 0, -1), # 8bpp inverted, unpadded, reversed
)
else:
# get AND image from end of bitmap
w = im.size[0]
if (w % 32) > 0:
# bitmap row data is aligned to word boundaries
w += 32 - (im.size[0] % 32)
# the total mask data is
# padded row size * height / bits per char
and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))
total_bytes = int((w * im.size[1]) / 8)
self.buf.seek(and_mask_offset)
mask_data = self.buf.read(total_bytes)
# convert raw data to image
mask = Image.frombuffer(
"1", # 1 bpp
im.size, # (w, h)
mask_data, # source chars
"raw", # raw decoder
("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
)
# now we have two images, im is XOR image and mask is AND image
# apply mask image as alpha channel
im = im.convert("RGBA")
im.putalpha(mask)
return im | [
"def",
"frame",
"(",
"self",
",",
"idx",
")",
":",
"header",
"=",
"self",
".",
"entry",
"[",
"idx",
"]",
"self",
".",
"buf",
".",
"seek",
"(",
"header",
"[",
"\"offset\"",
"]",
")",
"data",
"=",
"self",
".",
"buf",
".",
"read",
"(",
"8",
")",
"self",
".",
"buf",
".",
"seek",
"(",
"header",
"[",
"\"offset\"",
"]",
")",
"if",
"data",
"[",
":",
"8",
"]",
"==",
"PngImagePlugin",
".",
"_MAGIC",
":",
"# png frame",
"im",
"=",
"PngImagePlugin",
".",
"PngImageFile",
"(",
"self",
".",
"buf",
")",
"else",
":",
"# XOR + AND mask bmp frame",
"im",
"=",
"BmpImagePlugin",
".",
"DibImageFile",
"(",
"self",
".",
"buf",
")",
"Image",
".",
"_decompression_bomb_check",
"(",
"im",
".",
"size",
")",
"# change tile dimension to only encompass XOR image",
"im",
".",
"_size",
"=",
"(",
"im",
".",
"size",
"[",
"0",
"]",
",",
"int",
"(",
"im",
".",
"size",
"[",
"1",
"]",
"/",
"2",
")",
")",
"d",
",",
"e",
",",
"o",
",",
"a",
"=",
"im",
".",
"tile",
"[",
"0",
"]",
"im",
".",
"tile",
"[",
"0",
"]",
"=",
"d",
",",
"(",
"0",
",",
"0",
")",
"+",
"im",
".",
"size",
",",
"o",
",",
"a",
"# figure out where AND mask image starts",
"mode",
"=",
"a",
"[",
"0",
"]",
"bpp",
"=",
"8",
"for",
"k",
",",
"v",
"in",
"BmpImagePlugin",
".",
"BIT2MODE",
".",
"items",
"(",
")",
":",
"if",
"mode",
"==",
"v",
"[",
"1",
"]",
":",
"bpp",
"=",
"k",
"break",
"if",
"32",
"==",
"bpp",
":",
"# 32-bit color depth icon image allows semitransparent areas",
"# PIL's DIB format ignores transparency bits, recover them.",
"# The DIB is packed in BGRX byte order where X is the alpha",
"# channel.",
"# Back up to start of bmp data",
"self",
".",
"buf",
".",
"seek",
"(",
"o",
")",
"# extract every 4th byte (eg. 3,7,11,15,...)",
"alpha_bytes",
"=",
"self",
".",
"buf",
".",
"read",
"(",
"im",
".",
"size",
"[",
"0",
"]",
"*",
"im",
".",
"size",
"[",
"1",
"]",
"*",
"4",
")",
"[",
"3",
":",
":",
"4",
"]",
"# convert to an 8bpp grayscale image",
"mask",
"=",
"Image",
".",
"frombuffer",
"(",
"\"L\"",
",",
"# 8bpp",
"im",
".",
"size",
",",
"# (w, h)",
"alpha_bytes",
",",
"# source chars",
"\"raw\"",
",",
"# raw decoder",
"(",
"\"L\"",
",",
"0",
",",
"-",
"1",
")",
",",
"# 8bpp inverted, unpadded, reversed",
")",
"else",
":",
"# get AND image from end of bitmap",
"w",
"=",
"im",
".",
"size",
"[",
"0",
"]",
"if",
"(",
"w",
"%",
"32",
")",
">",
"0",
":",
"# bitmap row data is aligned to word boundaries",
"w",
"+=",
"32",
"-",
"(",
"im",
".",
"size",
"[",
"0",
"]",
"%",
"32",
")",
"# the total mask data is",
"# padded row size * height / bits per char",
"and_mask_offset",
"=",
"o",
"+",
"int",
"(",
"im",
".",
"size",
"[",
"0",
"]",
"*",
"im",
".",
"size",
"[",
"1",
"]",
"*",
"(",
"bpp",
"/",
"8.0",
")",
")",
"total_bytes",
"=",
"int",
"(",
"(",
"w",
"*",
"im",
".",
"size",
"[",
"1",
"]",
")",
"/",
"8",
")",
"self",
".",
"buf",
".",
"seek",
"(",
"and_mask_offset",
")",
"mask_data",
"=",
"self",
".",
"buf",
".",
"read",
"(",
"total_bytes",
")",
"# convert raw data to image",
"mask",
"=",
"Image",
".",
"frombuffer",
"(",
"\"1\"",
",",
"# 1 bpp",
"im",
".",
"size",
",",
"# (w, h)",
"mask_data",
",",
"# source chars",
"\"raw\"",
",",
"# raw decoder",
"(",
"\"1;I\"",
",",
"int",
"(",
"w",
"/",
"8",
")",
",",
"-",
"1",
")",
",",
"# 1bpp inverted, padded, reversed",
")",
"# now we have two images, im is XOR image and mask is AND image",
"# apply mask image as alpha channel",
"im",
"=",
"im",
".",
"convert",
"(",
"\"RGBA\"",
")",
"im",
".",
"putalpha",
"(",
"mask",
")",
"return",
"im"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/IcoImagePlugin.py#L163-L245 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/backend.py | python | Backend.write_memory | (self, data, memory_name=MemoryNames.FLASH, offset_byte=0, blocksize=0, pagewrite_delay=0) | Write target device memory
:param memory_name: Name of memory as defined in memorynames.py
:param offset_byte: Byte offset within memory to start writing to.
:param data: bytearray of raw data bytes to write
:param blocksize: max number of bytes to send at a time. Ignored if 0 or omitted, and not passed
to write_memory; only serialupdi supports this.
:raises: PymcuprogToolConnectionError if not connected to any tool (connect_to_tool not run)
:raises: PymcuprogSessionError if a session has not been started (session_start not run)
:raises: ValueError if trying to write outside the specified memory
:raises: ValueError if the specified memory is not defined for the target device | Write target device memory | [
"Write",
"target",
"device",
"memory"
] | def write_memory(self, data, memory_name=MemoryNames.FLASH, offset_byte=0, blocksize=0, pagewrite_delay=0):
"""
Write target device memory
:param memory_name: Name of memory as defined in memorynames.py
:param offset_byte: Byte offset within memory to start writing to.
:param data: bytearray of raw data bytes to write
:param blocksize: max number of bytes to send at a time. Ignored if 0 or omitted, and not passed
to write_memory; only serialupdi supports this.
:raises: PymcuprogToolConnectionError if not connected to any tool (connect_to_tool not run)
:raises: PymcuprogSessionError if a session has not been started (session_start not run)
:raises: ValueError if trying to write outside the specified memory
:raises: ValueError if the specified memory is not defined for the target device
"""
self._is_tool_not_connected_raise()
self._is_session_not_active_raise()
if blocksize == 0:
self.programmer.write_memory(data=data, memory_name=memory_name, offset=offset_byte, pagewrite_delay=pagewrite_delay)
else:
self.programmer.write_memory(data=data, memory_name=memory_name, offset=offset_byte, blocksize=blocksize, pagewrite_delay=pagewrite_delay) | [
"def",
"write_memory",
"(",
"self",
",",
"data",
",",
"memory_name",
"=",
"MemoryNames",
".",
"FLASH",
",",
"offset_byte",
"=",
"0",
",",
"blocksize",
"=",
"0",
",",
"pagewrite_delay",
"=",
"0",
")",
":",
"self",
".",
"_is_tool_not_connected_raise",
"(",
")",
"self",
".",
"_is_session_not_active_raise",
"(",
")",
"if",
"blocksize",
"==",
"0",
":",
"self",
".",
"programmer",
".",
"write_memory",
"(",
"data",
"=",
"data",
",",
"memory_name",
"=",
"memory_name",
",",
"offset",
"=",
"offset_byte",
",",
"pagewrite_delay",
"=",
"pagewrite_delay",
")",
"else",
":",
"self",
".",
"programmer",
".",
"write_memory",
"(",
"data",
"=",
"data",
",",
"memory_name",
"=",
"memory_name",
",",
"offset",
"=",
"offset_byte",
",",
"blocksize",
"=",
"blocksize",
",",
"pagewrite_delay",
"=",
"pagewrite_delay",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/backend.py#L506-L526 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/ctc_ops.py | python | _CTCLossGrad | (op, grad_loss, _) | return [_BroadcastMul(grad_loss, grad), None, None, None] | The derivative provided by CTC Loss.
Args:
op: the CTCLoss op.
grad_loss: The backprop for cost.
Returns:
The CTC Loss gradient. | The derivative provided by CTC Loss. | [
"The",
"derivative",
"provided",
"by",
"CTC",
"Loss",
"."
] | def _CTCLossGrad(op, grad_loss, _):
"""The derivative provided by CTC Loss.
Args:
op: the CTCLoss op.
grad_loss: The backprop for cost.
Returns:
The CTC Loss gradient.
"""
# Outputs are: loss, grad
grad = op.outputs[1]
# Return gradient for inputs and None for
# labels_indices, labels_values and sequence_length
return [_BroadcastMul(grad_loss, grad), None, None, None] | [
"def",
"_CTCLossGrad",
"(",
"op",
",",
"grad_loss",
",",
"_",
")",
":",
"# Outputs are: loss, grad",
"grad",
"=",
"op",
".",
"outputs",
"[",
"1",
"]",
"# Return gradient for inputs and None for",
"# labels_indices, labels_values and sequence_length",
"return",
"[",
"_BroadcastMul",
"(",
"grad_loss",
",",
"grad",
")",
",",
"None",
",",
"None",
",",
"None",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/ctc_ops.py#L121-L135 | |
makerbase-mks/MKS-SBASE | 76c9f4b2391f3d48c17f5fb066a2cbe0895b9f1b | Firmware/Marlin-bugfix-2.0.x/buildroot/share/atom/auto_build.py | python | output_window._clear_all | (self) | erases all text | erases all text | [
"erases",
"all",
"text"
] | def _clear_all(self):
'''erases all text'''
isok = askokcancel('Clear All', 'Erase all text?', frame=self,
default='ok')
if isok:
self.delete('1.0', 'end') | [
"def",
"_clear_all",
"(",
"self",
")",
":",
"isok",
"=",
"askokcancel",
"(",
"'Clear All'",
",",
"'Erase all text?'",
",",
"frame",
"=",
"self",
",",
"default",
"=",
"'ok'",
")",
"if",
"isok",
":",
"self",
".",
"delete",
"(",
"'1.0'",
",",
"'end'",
")"
] | https://github.com/makerbase-mks/MKS-SBASE/blob/76c9f4b2391f3d48c17f5fb066a2cbe0895b9f1b/Firmware/Marlin-bugfix-2.0.x/buildroot/share/atom/auto_build.py#L1201-L1207 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/serverui/sdhashsrv/sdhashsrv.py | python | Client.saveSet | (self, num1, filename) | return self.recv_saveSet() | Parameters:
- num1
- filename | Parameters:
- num1
- filename | [
"Parameters",
":",
"-",
"num1",
"-",
"filename"
] | def saveSet(self, num1, filename):
"""
Parameters:
- num1
- filename
"""
self.send_saveSet(num1, filename)
return self.recv_saveSet() | [
"def",
"saveSet",
"(",
"self",
",",
"num1",
",",
"filename",
")",
":",
"self",
".",
"send_saveSet",
"(",
"num1",
",",
"filename",
")",
"return",
"self",
".",
"recv_saveSet",
"(",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/serverui/sdhashsrv/sdhashsrv.py#L366-L373 | |
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Utilities/Scripts/SEMToMediaWiki.py | python | GetSEMDoc | (filename) | return executableNode[0] | r"""
Read the xml file from the first argument of command line
Return the primary heirarchial tree node. | r"""
Read the xml file from the first argument of command line
Return the primary heirarchial tree node. | [
"r",
"Read",
"the",
"xml",
"file",
"from",
"the",
"first",
"argument",
"of",
"command",
"line",
"Return",
"the",
"primary",
"heirarchial",
"tree",
"node",
"."
] | def GetSEMDoc(filename):
r"""
Read the xml file from the first argument of command line
Return the primary heirarchial tree node.
"""
doc = xml.dom.minidom.parse(filename)
executableNode = [node for node in doc.childNodes if
node.nodeName == "executable"]
#Only use the first
return executableNode[0] | [
"def",
"GetSEMDoc",
"(",
"filename",
")",
":",
"doc",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parse",
"(",
"filename",
")",
"executableNode",
"=",
"[",
"node",
"for",
"node",
"in",
"doc",
".",
"childNodes",
"if",
"node",
".",
"nodeName",
"==",
"\"executable\"",
"]",
"#Only use the first",
"return",
"executableNode",
"[",
"0",
"]"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Utilities/Scripts/SEMToMediaWiki.py#L89-L98 | |
sfzhang15/RefineDet | 52b6fe23dc1a160fe710b7734576dca509bf4fae | scripts/cpp_lint.py | python | _BlockInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
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. | Run checks that applies to text after the closing brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"after",
"the",
"closing",
"brace",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
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.
"""
pass | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/scripts/cpp_lint.py#L1782-L1793 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/skia/tools/copyright/fileparser.py | python | Parser.GetCopyrightBlockAttributes | (self, comment_block) | return (first_match[0], first_match[1]) | Given a comment block, return a tuple of attributes: (year, holder).
If comment_block is None, or none of the attributes are found,
this will return (None, None). | Given a comment block, return a tuple of attributes: (year, holder). | [
"Given",
"a",
"comment",
"block",
"return",
"a",
"tuple",
"of",
"attributes",
":",
"(",
"year",
"holder",
")",
"."
] | def GetCopyrightBlockAttributes(self, comment_block):
"""Given a comment block, return a tuple of attributes: (year, holder).
If comment_block is None, or none of the attributes are found,
this will return (None, None)."""
if not comment_block:
return (None, None)
matches = self._attribute_pattern.findall(comment_block)
if not matches:
return (None, None)
first_match = matches[0]
return (first_match[0], first_match[1]) | [
"def",
"GetCopyrightBlockAttributes",
"(",
"self",
",",
"comment_block",
")",
":",
"if",
"not",
"comment_block",
":",
"return",
"(",
"None",
",",
"None",
")",
"matches",
"=",
"self",
".",
"_attribute_pattern",
".",
"findall",
"(",
"comment_block",
")",
"if",
"not",
"matches",
":",
"return",
"(",
"None",
",",
"None",
")",
"first_match",
"=",
"matches",
"[",
"0",
"]",
"return",
"(",
"first_match",
"[",
"0",
"]",
",",
"first_match",
"[",
"1",
"]",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/tools/copyright/fileparser.py#L43-L54 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | EncodingConverter.__init__ | (self, *args, **kwargs) | __init__(self) -> EncodingConverter | __init__(self) -> EncodingConverter | [
"__init__",
"(",
"self",
")",
"-",
">",
"EncodingConverter"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> EncodingConverter"""
_gdi_.EncodingConverter_swiginit(self,_gdi_.new_EncodingConverter(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"EncodingConverter_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_EncodingConverter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3182-L3184 | ||
shogun-toolbox/shogun | 9b8d856971af5a295dd6ad70623ae45647a6334c | applications/easysvm/esvm/experiment.py | python | svm_cv | (argv) | A top level script to parse input parameters and run cross validation | A top level script to parse input parameters and run cross validation | [
"A",
"top",
"level",
"script",
"to",
"parse",
"input",
"parameters",
"and",
"run",
"cross",
"validation"
] | def svm_cv(argv):
"""A top level script to parse input parameters and run cross validation"""
assert(argv[1]=='cv')
if len(argv)<5:sys.stderr.write("usage: %s cv repeat C kernelname [kernelparameters] [arff|fasta] inputfiles outputfile [dna|protein] non(nucleotide|amino)converter \n" % argv[0]);sys.exit(-1)
# parse input parameters
cv = int(argv[2])
C = float(argv[3])
(kernelname,kparam,argv_rest) = parse.parse_kernel_param(argv[4:],False)
(examples,labels,argv_rest) = parse.parse_input_file_train(kernelname, argv_rest)
(seq_source, nuc_con) = ('', '')
if kernelname == 'spec' or kernelname == 'wd':
if len(argv_rest)<1:sys.stderr.write("outputfile [dna|protein] non(nucleotide|amino)converter are missing\n");sys.exit(-1)
if len(argv_rest)<2:sys.stderr.write("[dna|protein] non(nucleotide|amino)converter are missing\n");sys.exit(-1)
if len(argv_rest)<3:
if argv_rest[-1] == 'dna':
sys.stderr.write("non-nucleotide converter like [A|T|C|G|R|Y|N] is missing. Cannot continue.\n")
sys.exit(-1)
elif argv_rest[-1] == 'protein':
sys.stderr.write("non-amino acid converter like [G|P|A|V|L|I|M|C|F|Y|W|H|K|R|Q|N|E|D|S|T|random] is missing. Cannot continue.\n")
sys.exit(-1)
else:
sys.stderr.write("Here expect FASTA sequence type as [dna|protein] instead of -"+ argv_rest[-1] +"- Cannot continue.\n")
sys.exit(-1)
if len(argv_rest)>3:sys.stderr.write("Too many arguments\n");sys.exit(-1)
seq_source = argv_rest[1]
nuc_con = argv_rest[2]
if kernelname == 'linear' or kernelname == 'gauss' or kernelname == 'poly':
if len(argv_rest)<1:sys.stderr.write("outputfile misssing\n");sys.exit(-1)
if len(argv_rest)>1:sys.stderr.write("Too many arguments\n");sys.exit(-1)
outfilename = argv_rest[0]
utils.check_params(kparam, C, len(examples[0]))
# run cross-validation
(all_outputs, all_split) = crossvalidation(cv, kernelname, kparam, C, examples, labels, seq_source, nuc_con)
try:
f = open(outfilename, 'w+')
except:
sys.stderr.write('Fails to open the outputfile at ' + outfilename + ' Cannot continue.\n')
sys.exit(-1)
res_str = '#example\toutput\tsplit\n'
f.write(res_str)
for ix in xrange(len(all_outputs)):
res_str = '%d\t%2.7f\t%d\n' % (ix,all_outputs[ix],all_split[ix])
f.write(res_str)
f.close() | [
"def",
"svm_cv",
"(",
"argv",
")",
":",
"assert",
"(",
"argv",
"[",
"1",
"]",
"==",
"'cv'",
")",
"if",
"len",
"(",
"argv",
")",
"<",
"5",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"usage: %s cv repeat C kernelname [kernelparameters] [arff|fasta] inputfiles outputfile [dna|protein] non(nucleotide|amino)converter \\n\"",
"%",
"argv",
"[",
"0",
"]",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"# parse input parameters",
"cv",
"=",
"int",
"(",
"argv",
"[",
"2",
"]",
")",
"C",
"=",
"float",
"(",
"argv",
"[",
"3",
"]",
")",
"(",
"kernelname",
",",
"kparam",
",",
"argv_rest",
")",
"=",
"parse",
".",
"parse_kernel_param",
"(",
"argv",
"[",
"4",
":",
"]",
",",
"False",
")",
"(",
"examples",
",",
"labels",
",",
"argv_rest",
")",
"=",
"parse",
".",
"parse_input_file_train",
"(",
"kernelname",
",",
"argv_rest",
")",
"(",
"seq_source",
",",
"nuc_con",
")",
"=",
"(",
"''",
",",
"''",
")",
"if",
"kernelname",
"==",
"'spec'",
"or",
"kernelname",
"==",
"'wd'",
":",
"if",
"len",
"(",
"argv_rest",
")",
"<",
"1",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"outputfile [dna|protein] non(nucleotide|amino)converter are missing\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"if",
"len",
"(",
"argv_rest",
")",
"<",
"2",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"[dna|protein] non(nucleotide|amino)converter are missing\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"if",
"len",
"(",
"argv_rest",
")",
"<",
"3",
":",
"if",
"argv_rest",
"[",
"-",
"1",
"]",
"==",
"'dna'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"non-nucleotide converter like [A|T|C|G|R|Y|N] is missing. Cannot continue.\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"elif",
"argv_rest",
"[",
"-",
"1",
"]",
"==",
"'protein'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"non-amino acid converter like [G|P|A|V|L|I|M|C|F|Y|W|H|K|R|Q|N|E|D|S|T|random] is missing. Cannot continue.\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Here expect FASTA sequence type as [dna|protein] instead of -\"",
"+",
"argv_rest",
"[",
"-",
"1",
"]",
"+",
"\"- Cannot continue.\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"if",
"len",
"(",
"argv_rest",
")",
">",
"3",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Too many arguments\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"seq_source",
"=",
"argv_rest",
"[",
"1",
"]",
"nuc_con",
"=",
"argv_rest",
"[",
"2",
"]",
"if",
"kernelname",
"==",
"'linear'",
"or",
"kernelname",
"==",
"'gauss'",
"or",
"kernelname",
"==",
"'poly'",
":",
"if",
"len",
"(",
"argv_rest",
")",
"<",
"1",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"outputfile misssing\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"if",
"len",
"(",
"argv_rest",
")",
">",
"1",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Too many arguments\\n\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"outfilename",
"=",
"argv_rest",
"[",
"0",
"]",
"utils",
".",
"check_params",
"(",
"kparam",
",",
"C",
",",
"len",
"(",
"examples",
"[",
"0",
"]",
")",
")",
"# run cross-validation",
"(",
"all_outputs",
",",
"all_split",
")",
"=",
"crossvalidation",
"(",
"cv",
",",
"kernelname",
",",
"kparam",
",",
"C",
",",
"examples",
",",
"labels",
",",
"seq_source",
",",
"nuc_con",
")",
"try",
":",
"f",
"=",
"open",
"(",
"outfilename",
",",
"'w+'",
")",
"except",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Fails to open the outputfile at '",
"+",
"outfilename",
"+",
"' Cannot continue.\\n'",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"res_str",
"=",
"'#example\\toutput\\tsplit\\n'",
"f",
".",
"write",
"(",
"res_str",
")",
"for",
"ix",
"in",
"xrange",
"(",
"len",
"(",
"all_outputs",
")",
")",
":",
"res_str",
"=",
"'%d\\t%2.7f\\t%d\\n'",
"%",
"(",
"ix",
",",
"all_outputs",
"[",
"ix",
"]",
",",
"all_split",
"[",
"ix",
"]",
")",
"f",
".",
"write",
"(",
"res_str",
")",
"f",
".",
"close",
"(",
")"
] | https://github.com/shogun-toolbox/shogun/blob/9b8d856971af5a295dd6ad70623ae45647a6334c/applications/easysvm/esvm/experiment.py#L462-L511 | ||
Fyusion/LLFF | c6e27b1ee59cb18f054ccb0f87a90214dbe70482 | llff/poses/colmap_read_model.py | python | read_cameras_binary | (path_to_model_file) | return cameras | see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasBinary(const std::string& path)
void Reconstruction::ReadCamerasBinary(const std::string& path) | see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasBinary(const std::string& path)
void Reconstruction::ReadCamerasBinary(const std::string& path) | [
"see",
":",
"src",
"/",
"base",
"/",
"reconstruction",
".",
"cc",
"void",
"Reconstruction",
"::",
"WriteCamerasBinary",
"(",
"const",
"std",
"::",
"string&",
"path",
")",
"void",
"Reconstruction",
"::",
"ReadCamerasBinary",
"(",
"const",
"std",
"::",
"string&",
"path",
")"
] | def read_cameras_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasBinary(const std::string& path)
void Reconstruction::ReadCamerasBinary(const std::string& path)
"""
cameras = {}
with open(path_to_model_file, "rb") as fid:
num_cameras = read_next_bytes(fid, 8, "Q")[0]
for camera_line_index in range(num_cameras):
camera_properties = read_next_bytes(
fid, num_bytes=24, format_char_sequence="iiQQ")
camera_id = camera_properties[0]
model_id = camera_properties[1]
model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
width = camera_properties[2]
height = camera_properties[3]
num_params = CAMERA_MODEL_IDS[model_id].num_params
params = read_next_bytes(fid, num_bytes=8*num_params,
format_char_sequence="d"*num_params)
cameras[camera_id] = Camera(id=camera_id,
model=model_name,
width=width,
height=height,
params=np.array(params))
assert len(cameras) == num_cameras
return cameras | [
"def",
"read_cameras_binary",
"(",
"path_to_model_file",
")",
":",
"cameras",
"=",
"{",
"}",
"with",
"open",
"(",
"path_to_model_file",
",",
"\"rb\"",
")",
"as",
"fid",
":",
"num_cameras",
"=",
"read_next_bytes",
"(",
"fid",
",",
"8",
",",
"\"Q\"",
")",
"[",
"0",
"]",
"for",
"camera_line_index",
"in",
"range",
"(",
"num_cameras",
")",
":",
"camera_properties",
"=",
"read_next_bytes",
"(",
"fid",
",",
"num_bytes",
"=",
"24",
",",
"format_char_sequence",
"=",
"\"iiQQ\"",
")",
"camera_id",
"=",
"camera_properties",
"[",
"0",
"]",
"model_id",
"=",
"camera_properties",
"[",
"1",
"]",
"model_name",
"=",
"CAMERA_MODEL_IDS",
"[",
"camera_properties",
"[",
"1",
"]",
"]",
".",
"model_name",
"width",
"=",
"camera_properties",
"[",
"2",
"]",
"height",
"=",
"camera_properties",
"[",
"3",
"]",
"num_params",
"=",
"CAMERA_MODEL_IDS",
"[",
"model_id",
"]",
".",
"num_params",
"params",
"=",
"read_next_bytes",
"(",
"fid",
",",
"num_bytes",
"=",
"8",
"*",
"num_params",
",",
"format_char_sequence",
"=",
"\"d\"",
"*",
"num_params",
")",
"cameras",
"[",
"camera_id",
"]",
"=",
"Camera",
"(",
"id",
"=",
"camera_id",
",",
"model",
"=",
"model_name",
",",
"width",
"=",
"width",
",",
"height",
"=",
"height",
",",
"params",
"=",
"np",
".",
"array",
"(",
"params",
")",
")",
"assert",
"len",
"(",
"cameras",
")",
"==",
"num_cameras",
"return",
"cameras"
] | https://github.com/Fyusion/LLFF/blob/c6e27b1ee59cb18f054ccb0f87a90214dbe70482/llff/poses/colmap_read_model.py#L108-L134 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | GLcharHandler.WriteImmediateFormatTest | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteImmediateFormatTest(self, func, file):
"""Overrriden from TypeHandler."""
init_code = []
check_code = []
all_but_last_arg = func.GetCmdArgs()[:-1]
for value, arg in enumerate(all_but_last_arg):
init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
for value, arg in enumerate(all_but_last_arg):
check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
(arg.type, value + 11, arg.name))
code = """
TEST_F(GLES2FormatTest, %(func_name)s) {
cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
static const char* const test_str = \"test string\";
void* next_cmd = cmd.Set(
&cmd,
%(init_code)s
test_str,
strlen(test_str));
EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
cmd.header.command);
EXPECT_EQ(sizeof(cmd) +
RoundSizeToMultipleOfEntries(strlen(test_str)),
cmd.header.size * 4u);
EXPECT_EQ(static_cast<char*>(next_cmd),
reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
RoundSizeToMultipleOfEntries(strlen(test_str)));
%(check_code)s
EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
CheckBytesWritten(
next_cmd,
sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
sizeof(cmd) + strlen(test_str));
}
"""
file.Write(code % {
'func_name': func.name,
'init_code': "\n".join(init_code),
'check_code': "\n".join(check_code),
}) | [
"def",
"WriteImmediateFormatTest",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"init_code",
"=",
"[",
"]",
"check_code",
"=",
"[",
"]",
"all_but_last_arg",
"=",
"func",
".",
"GetCmdArgs",
"(",
")",
"[",
":",
"-",
"1",
"]",
"for",
"value",
",",
"arg",
"in",
"enumerate",
"(",
"all_but_last_arg",
")",
":",
"init_code",
".",
"append",
"(",
"\" static_cast<%s>(%d),\"",
"%",
"(",
"arg",
".",
"type",
",",
"value",
"+",
"11",
")",
")",
"for",
"value",
",",
"arg",
"in",
"enumerate",
"(",
"all_but_last_arg",
")",
":",
"check_code",
".",
"append",
"(",
"\" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\"",
"%",
"(",
"arg",
".",
"type",
",",
"value",
"+",
"11",
",",
"arg",
".",
"name",
")",
")",
"code",
"=",
"\"\"\"\nTEST_F(GLES2FormatTest, %(func_name)s) {\n cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();\n static const char* const test_str = \\\"test string\\\";\n void* next_cmd = cmd.Set(\n &cmd,\n%(init_code)s\n test_str,\n strlen(test_str));\n EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),\n cmd.header.command);\n EXPECT_EQ(sizeof(cmd) +\n RoundSizeToMultipleOfEntries(strlen(test_str)),\n cmd.header.size * 4u);\n EXPECT_EQ(static_cast<char*>(next_cmd),\n reinterpret_cast<char*>(&cmd) + sizeof(cmd) +\n RoundSizeToMultipleOfEntries(strlen(test_str)));\n%(check_code)s\n EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);\n EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));\n CheckBytesWritten(\n next_cmd,\n sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),\n sizeof(cmd) + strlen(test_str));\n}\n\n\"\"\"",
"file",
".",
"Write",
"(",
"code",
"%",
"{",
"'func_name'",
":",
"func",
".",
"name",
",",
"'init_code'",
":",
"\"\\n\"",
".",
"join",
"(",
"init_code",
")",
",",
"'check_code'",
":",
"\"\\n\"",
".",
"join",
"(",
"check_code",
")",
",",
"}",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5373-L5414 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/gluon/data/dataloader.py | python | _MultiWorkerIter._push_next | (self) | Assign next batch workload to workers. | Assign next batch workload to workers. | [
"Assign",
"next",
"batch",
"workload",
"to",
"workers",
"."
] | def _push_next(self):
"""Assign next batch workload to workers."""
r = next(self._iter, None)
if r is None:
return
async_ret = self._worker_pool.apply_async(
self._worker_fn, (r, self._batchify_fn, self._dataset))
self._data_buffer[self._sent_idx] = async_ret
self._sent_idx += 1 | [
"def",
"_push_next",
"(",
"self",
")",
":",
"r",
"=",
"next",
"(",
"self",
".",
"_iter",
",",
"None",
")",
"if",
"r",
"is",
"None",
":",
"return",
"async_ret",
"=",
"self",
".",
"_worker_pool",
".",
"apply_async",
"(",
"self",
".",
"_worker_fn",
",",
"(",
"r",
",",
"self",
".",
"_batchify_fn",
",",
"self",
".",
"_dataset",
")",
")",
"self",
".",
"_data_buffer",
"[",
"self",
".",
"_sent_idx",
"]",
"=",
"async_ret",
"self",
".",
"_sent_idx",
"+=",
"1"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/data/dataloader.py#L465-L473 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/mesa/MesaLib/src/gallium/auxiliary/util/u_format_pack.py | python | value_to_native | (type, value) | Get the value of unity for this type. | Get the value of unity for this type. | [
"Get",
"the",
"value",
"of",
"unity",
"for",
"this",
"type",
"."
] | def value_to_native(type, value):
'''Get the value of unity for this type.'''
if type.type == FLOAT:
return value
if type.type == FIXED:
return int(value * (1 << (type.size/2)))
if not type.norm:
return int(value)
if type.type == UNSIGNED:
return int(value * ((1 << type.size) - 1))
if type.type == SIGNED:
return int(value * ((1 << (type.size - 1)) - 1))
assert False | [
"def",
"value_to_native",
"(",
"type",
",",
"value",
")",
":",
"if",
"type",
".",
"type",
"==",
"FLOAT",
":",
"return",
"value",
"if",
"type",
".",
"type",
"==",
"FIXED",
":",
"return",
"int",
"(",
"value",
"*",
"(",
"1",
"<<",
"(",
"type",
".",
"size",
"/",
"2",
")",
")",
")",
"if",
"not",
"type",
".",
"norm",
":",
"return",
"int",
"(",
"value",
")",
"if",
"type",
".",
"type",
"==",
"UNSIGNED",
":",
"return",
"int",
"(",
"value",
"*",
"(",
"(",
"1",
"<<",
"type",
".",
"size",
")",
"-",
"1",
")",
")",
"if",
"type",
".",
"type",
"==",
"SIGNED",
":",
"return",
"int",
"(",
"value",
"*",
"(",
"(",
"1",
"<<",
"(",
"type",
".",
"size",
"-",
"1",
")",
")",
"-",
"1",
")",
")",
"assert",
"False"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/mesa/MesaLib/src/gallium/auxiliary/util/u_format_pack.py#L188-L200 | ||
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/win/Source/Includes/QtIncludes/src/3rdparty/freetype/src/tools/glnames.py | python | filter_glyph_names | ( alist, filter ) | return extras | filter `alist' by taking _out_ all glyph names that are in `filter | filter `alist' by taking _out_ all glyph names that are in `filter | [
"filter",
"alist",
"by",
"taking",
"_out_",
"all",
"glyph",
"names",
"that",
"are",
"in",
"filter"
] | def filter_glyph_names( alist, filter ):
"""filter `alist' by taking _out_ all glyph names that are in `filter'"""
count = 0
extras = []
for name in alist:
try:
filtered_index = filter.index( name )
except:
extras.append( name )
return extras | [
"def",
"filter_glyph_names",
"(",
"alist",
",",
"filter",
")",
":",
"count",
"=",
"0",
"extras",
"=",
"[",
"]",
"for",
"name",
"in",
"alist",
":",
"try",
":",
"filtered_index",
"=",
"filter",
".",
"index",
"(",
"name",
")",
"except",
":",
"extras",
".",
"append",
"(",
"name",
")",
"return",
"extras"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/Includes/QtIncludes/src/3rdparty/freetype/src/tools/glnames.py#L4971-L4983 | |
rampageX/firmware-mod-kit | c94cd6aeee50d92ec5280a6dba6d74828fd3606b | src/binwalk-2.1.1/src/binwalk/core/display.py | python | Display._format_line | (self, line) | return formatted_line | Formats a line of text to fit in the terminal window.
For Tim. | Formats a line of text to fit in the terminal window.
For Tim. | [
"Formats",
"a",
"line",
"of",
"text",
"to",
"fit",
"in",
"the",
"terminal",
"window",
".",
"For",
"Tim",
"."
] | def _format_line(self, line):
'''
Formats a line of text to fit in the terminal window.
For Tim.
'''
delim = '\n'
offset = 0
self.string_parts = []
# Split the line into an array of columns, e.g., ['0', '0x00000000', 'Some description here']
line_columns = line.split(None, self.num_columns-1)
if line_columns:
# Find where the start of the last column (description) starts in the line of text.
# All line wraps need to be aligned to this offset.
offset = line.rfind(line_columns[-1])
# The delimiter will be a newline followed by spaces padding out the line wrap to the alignment offset.
delim += ' ' * offset
if line_columns and self.fit_to_screen and len(line) > self.SCREEN_WIDTH:
# Calculate the maximum length that each wrapped line can be
max_line_wrap_length = self.SCREEN_WIDTH - offset
# Append all but the last column to formatted_line
formatted_line = line[:offset]
# Loop to split up line into multiple max_line_wrap_length pieces
while len(line[offset:]) > max_line_wrap_length:
# Find the nearest space to wrap the line at (so we don't split a word across two lines)
split_offset = line[offset:offset+max_line_wrap_length].rfind(' ')
# If there were no good places to split the line, just truncate it at max_line_wrap_length
if split_offset < 1:
split_offset = max_line_wrap_length
self._append_to_data_parts(line, offset, offset+split_offset)
offset += split_offset
# Add any remaining data (guarunteed to be max_line_wrap_length long or shorter) to self.string_parts
self._append_to_data_parts(line, offset, offset+len(line[offset:]))
# Append self.string_parts to formatted_line; each part seperated by delim
formatted_line += delim.join(self.string_parts)
else:
formatted_line = line
return formatted_line | [
"def",
"_format_line",
"(",
"self",
",",
"line",
")",
":",
"delim",
"=",
"'\\n'",
"offset",
"=",
"0",
"self",
".",
"string_parts",
"=",
"[",
"]",
"# Split the line into an array of columns, e.g., ['0', '0x00000000', 'Some description here']",
"line_columns",
"=",
"line",
".",
"split",
"(",
"None",
",",
"self",
".",
"num_columns",
"-",
"1",
")",
"if",
"line_columns",
":",
"# Find where the start of the last column (description) starts in the line of text.",
"# All line wraps need to be aligned to this offset.",
"offset",
"=",
"line",
".",
"rfind",
"(",
"line_columns",
"[",
"-",
"1",
"]",
")",
"# The delimiter will be a newline followed by spaces padding out the line wrap to the alignment offset.",
"delim",
"+=",
"' '",
"*",
"offset",
"if",
"line_columns",
"and",
"self",
".",
"fit_to_screen",
"and",
"len",
"(",
"line",
")",
">",
"self",
".",
"SCREEN_WIDTH",
":",
"# Calculate the maximum length that each wrapped line can be",
"max_line_wrap_length",
"=",
"self",
".",
"SCREEN_WIDTH",
"-",
"offset",
"# Append all but the last column to formatted_line",
"formatted_line",
"=",
"line",
"[",
":",
"offset",
"]",
"# Loop to split up line into multiple max_line_wrap_length pieces",
"while",
"len",
"(",
"line",
"[",
"offset",
":",
"]",
")",
">",
"max_line_wrap_length",
":",
"# Find the nearest space to wrap the line at (so we don't split a word across two lines)",
"split_offset",
"=",
"line",
"[",
"offset",
":",
"offset",
"+",
"max_line_wrap_length",
"]",
".",
"rfind",
"(",
"' '",
")",
"# If there were no good places to split the line, just truncate it at max_line_wrap_length",
"if",
"split_offset",
"<",
"1",
":",
"split_offset",
"=",
"max_line_wrap_length",
"self",
".",
"_append_to_data_parts",
"(",
"line",
",",
"offset",
",",
"offset",
"+",
"split_offset",
")",
"offset",
"+=",
"split_offset",
"# Add any remaining data (guarunteed to be max_line_wrap_length long or shorter) to self.string_parts",
"self",
".",
"_append_to_data_parts",
"(",
"line",
",",
"offset",
",",
"offset",
"+",
"len",
"(",
"line",
"[",
"offset",
":",
"]",
")",
")",
"# Append self.string_parts to formatted_line; each part seperated by delim",
"formatted_line",
"+=",
"delim",
".",
"join",
"(",
"self",
".",
"string_parts",
")",
"else",
":",
"formatted_line",
"=",
"line",
"return",
"formatted_line"
] | https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/core/display.py#L171-L214 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py | python | replaceWith | (replStr) | return lambda s,l,t: [replStr] | Helper method for common parse actions that simply return a literal value. Especially
useful when used with C{L{transformString<ParserElement.transformString>}()}.
Example::
num = Word(nums).setParseAction(lambda toks: int(toks[0]))
na = oneOf("N/A NA").setParseAction(replaceWith(math.nan))
term = na | num
OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] | Helper method for common parse actions that simply return a literal value. Especially
useful when used with C{L{transformString<ParserElement.transformString>}()}. | [
"Helper",
"method",
"for",
"common",
"parse",
"actions",
"that",
"simply",
"return",
"a",
"literal",
"value",
".",
"Especially",
"useful",
"when",
"used",
"with",
"C",
"{",
"L",
"{",
"transformString<ParserElement",
".",
"transformString",
">",
"}",
"()",
"}",
"."
] | def replaceWith(replStr):
"""
Helper method for common parse actions that simply return a literal value. Especially
useful when used with C{L{transformString<ParserElement.transformString>}()}.
Example::
num = Word(nums).setParseAction(lambda toks: int(toks[0]))
na = oneOf("N/A NA").setParseAction(replaceWith(math.nan))
term = na | num
OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234]
"""
return lambda s,l,t: [replStr] | [
"def",
"replaceWith",
"(",
"replStr",
")",
":",
"return",
"lambda",
"s",
",",
"l",
",",
"t",
":",
"[",
"replStr",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L4756-L4768 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | xmlNode.lsOneNode | (self, output) | Dump to @output the type and name of @node. | Dump to | [
"Dump",
"to"
] | def lsOneNode(self, output):
"""Dump to @output the type and name of @node. """
libxml2mod.xmlLsOneNode(output, self._o) | [
"def",
"lsOneNode",
"(",
"self",
",",
"output",
")",
":",
"libxml2mod",
".",
"xmlLsOneNode",
"(",
"output",
",",
"self",
".",
"_o",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2277-L2279 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/web.py | python | RequestHandler.reverse_url | (self, name: str, *args: Any) | return self.application.reverse_url(name, *args) | Alias for `Application.reverse_url`. | Alias for `Application.reverse_url`. | [
"Alias",
"for",
"Application",
".",
"reverse_url",
"."
] | def reverse_url(self, name: str, *args: Any) -> str:
"""Alias for `Application.reverse_url`."""
return self.application.reverse_url(name, *args) | [
"def",
"reverse_url",
"(",
"self",
",",
"name",
":",
"str",
",",
"*",
"args",
":",
"Any",
")",
"->",
"str",
":",
"return",
"self",
".",
"application",
".",
"reverse_url",
"(",
"name",
",",
"*",
"args",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/web.py#L1592-L1594 | |
kungfu-origin/kungfu | 90c84b2b590855654cb9a6395ed050e0f7763512 | core/deps/SQLiteCpp-2.3.0/cpplint.py | python | FindNextMultiLineCommentStart | (lines, lineix) | return len(lines) | Find the beginning marker for a multiline comment. | Find the beginning marker for a multiline comment. | [
"Find",
"the",
"beginning",
"marker",
"for",
"a",
"multiline",
"comment",
"."
] | def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines) | [
"def",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'/*'",
")",
":",
"# Only return this marker if the comment goes beyond this line",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"find",
"(",
"'*/'",
",",
"2",
")",
"<",
"0",
":",
"return",
"lineix",
"lineix",
"+=",
"1",
"return",
"len",
"(",
"lines",
")"
] | https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L1127-L1135 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | Geometry3D.set | (self, arg2) | return _robotsim.Geometry3D_set(self, arg2) | set(Geometry3D self, Geometry3D arg2)
Copies the geometry of the argument into this geometry. | set(Geometry3D self, Geometry3D arg2) | [
"set",
"(",
"Geometry3D",
"self",
"Geometry3D",
"arg2",
")"
] | def set(self, arg2):
"""
set(Geometry3D self, Geometry3D arg2)
Copies the geometry of the argument into this geometry.
"""
return _robotsim.Geometry3D_set(self, arg2) | [
"def",
"set",
"(",
"self",
",",
"arg2",
")",
":",
"return",
"_robotsim",
".",
"Geometry3D_set",
"(",
"self",
",",
"arg2",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L1912-L1921 | |
facebook/proxygen | a9ca025af207787815cb01eee1971cd572c7a81e | build/fbcode_builder/utils.py | python | _inner_read_config | (path) | return read_fbcode_builder_config(full_path) | Helper to read a named config file.
The grossness with the global is a workaround for this python bug:
https://bugs.python.org/issue21591
The bug prevents us from defining either a local function or a lambda
in the scope of read_fbcode_builder_config below. | Helper to read a named config file.
The grossness with the global is a workaround for this python bug:
https://bugs.python.org/issue21591
The bug prevents us from defining either a local function or a lambda
in the scope of read_fbcode_builder_config below. | [
"Helper",
"to",
"read",
"a",
"named",
"config",
"file",
".",
"The",
"grossness",
"with",
"the",
"global",
"is",
"a",
"workaround",
"for",
"this",
"python",
"bug",
":",
"https",
":",
"//",
"bugs",
".",
"python",
".",
"org",
"/",
"issue21591",
"The",
"bug",
"prevents",
"us",
"from",
"defining",
"either",
"a",
"local",
"function",
"or",
"a",
"lambda",
"in",
"the",
"scope",
"of",
"read_fbcode_builder_config",
"below",
"."
] | def _inner_read_config(path):
"""
Helper to read a named config file.
The grossness with the global is a workaround for this python bug:
https://bugs.python.org/issue21591
The bug prevents us from defining either a local function or a lambda
in the scope of read_fbcode_builder_config below.
"""
global _project_dir
full_path = os.path.join(_project_dir, path)
return read_fbcode_builder_config(full_path) | [
"def",
"_inner_read_config",
"(",
"path",
")",
":",
"global",
"_project_dir",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_project_dir",
",",
"path",
")",
"return",
"read_fbcode_builder_config",
"(",
"full_path",
")"
] | https://github.com/facebook/proxygen/blob/a9ca025af207787815cb01eee1971cd572c7a81e/build/fbcode_builder/utils.py#L37-L47 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.newDocText | (self, content) | return __tmp | Creation of a new text node within a document. | Creation of a new text node within a document. | [
"Creation",
"of",
"a",
"new",
"text",
"node",
"within",
"a",
"document",
"."
] | def newDocText(self, content):
"""Creation of a new text node within a document. """
ret = libxml2mod.xmlNewDocText(self._o, content)
if ret is None:raise treeError('xmlNewDocText() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newDocText",
"(",
"self",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocText",
"(",
"self",
".",
"_o",
",",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewDocText() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4324-L4329 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py | python | X509Name.__repr__ | (self) | return "<X509Name object '%s'>" % (
_native(_ffi.string(result_buffer)),) | String representation of an X509Name | String representation of an X509Name | [
"String",
"representation",
"of",
"an",
"X509Name"
] | def __repr__(self):
"""
String representation of an X509Name
"""
result_buffer = _ffi.new("char[]", 512)
format_result = _lib.X509_NAME_oneline(
self._name, result_buffer, len(result_buffer))
_openssl_assert(format_result != _ffi.NULL)
return "<X509Name object '%s'>" % (
_native(_ffi.string(result_buffer)),) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"result_buffer",
"=",
"_ffi",
".",
"new",
"(",
"\"char[]\"",
",",
"512",
")",
"format_result",
"=",
"_lib",
".",
"X509_NAME_oneline",
"(",
"self",
".",
"_name",
",",
"result_buffer",
",",
"len",
"(",
"result_buffer",
")",
")",
"_openssl_assert",
"(",
"format_result",
"!=",
"_ffi",
".",
"NULL",
")",
"return",
"\"<X509Name object '%s'>\"",
"%",
"(",
"_native",
"(",
"_ffi",
".",
"string",
"(",
"result_buffer",
")",
")",
",",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py#L636-L646 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/serverui/sdhashsrv/sdhashsrv.py | python | Client.displayResultStatus | (self, resultID) | return self.recv_displayResultStatus() | Parameters:
- resultID | Parameters:
- resultID | [
"Parameters",
":",
"-",
"resultID"
] | def displayResultStatus(self, resultID):
"""
Parameters:
- resultID
"""
self.send_displayResultStatus(resultID)
return self.recv_displayResultStatus() | [
"def",
"displayResultStatus",
"(",
"self",
",",
"resultID",
")",
":",
"self",
".",
"send_displayResultStatus",
"(",
"resultID",
")",
"return",
"self",
".",
"recv_displayResultStatus",
"(",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/serverui/sdhashsrv/sdhashsrv.py#L592-L598 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | PyAuiTabArt._setCallbackInfo | (*args, **kwargs) | return _aui.PyAuiTabArt__setCallbackInfo(*args, **kwargs) | _setCallbackInfo(self, PyObject self, PyObject _class) | _setCallbackInfo(self, PyObject self, PyObject _class) | [
"_setCallbackInfo",
"(",
"self",
"PyObject",
"self",
"PyObject",
"_class",
")"
] | def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _aui.PyAuiTabArt__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"PyAuiTabArt__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L2431-L2433 | |
Yaafe/Yaafe | f5ed847bdbf540b47e8fe1980dddfb5509ae7f9d | src_python/yaafelib/engine.py | python | Engine.readAllOutputs | (self) | return res | Read all outputs.
:return: dictionary with output name as key and numpy.array
as value. | Read all outputs. | [
"Read",
"all",
"outputs",
"."
] | def readAllOutputs(self):
"""
Read all outputs.
:return: dictionary with output name as key and numpy.array
as value.
"""
res = {}
oList = yc.engine_getOutputList(self.ptr)
for o in iterPtrList(oList):
res[to_str(o)] = self.readOutput(o)
return res | [
"def",
"readAllOutputs",
"(",
"self",
")",
":",
"res",
"=",
"{",
"}",
"oList",
"=",
"yc",
".",
"engine_getOutputList",
"(",
"self",
".",
"ptr",
")",
"for",
"o",
"in",
"iterPtrList",
"(",
"oList",
")",
":",
"res",
"[",
"to_str",
"(",
"o",
")",
"]",
"=",
"self",
".",
"readOutput",
"(",
"o",
")",
"return",
"res"
] | https://github.com/Yaafe/Yaafe/blob/f5ed847bdbf540b47e8fe1980dddfb5509ae7f9d/src_python/yaafelib/engine.py#L256-L267 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/environment.py | python | Environment.extend | (self, **attributes) | Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance. | Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance. | [
"Add",
"the",
"items",
"to",
"the",
"instance",
"of",
"the",
"environment",
"if",
"they",
"do",
"not",
"exist",
"yet",
".",
"This",
"is",
"used",
"by",
":",
"ref",
":",
"extensions",
"<writing",
"-",
"extensions",
">",
"to",
"register",
"callbacks",
"and",
"configuration",
"values",
"without",
"breaking",
"inheritance",
"."
] | def extend(self, **attributes):
"""Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance.
"""
for key, value in iteritems(attributes):
if not hasattr(self, key):
setattr(self, key, value) | [
"def",
"extend",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"attributes",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"key",
")",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"value",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/environment.py#L347-L354 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/special/basic.py | python | lqmn | (m, n, z) | return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)] | Associated Legendre function of the second kind, Qmn(z).
Computes the associated Legendre function of the second kind of order m and
degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
Parameters
----------
m : int
``|m| <= n``; the order of the Legendre function.
n : int
where ``n >= 0``; the degree of the Legendre function. Often
called ``l`` (lower case L) in descriptions of the associated
Legendre function
z : complex
Input value.
Returns
-------
Qmn_z : (m+1, n+1) array
Values for all orders 0..m and degrees 0..n
Qmn_d_z : (m+1, n+1) array
Derivatives for all orders 0..m and degrees 0..n
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html | Associated Legendre function of the second kind, Qmn(z). | [
"Associated",
"Legendre",
"function",
"of",
"the",
"second",
"kind",
"Qmn",
"(",
"z",
")",
"."
] | def lqmn(m, n, z):
"""Associated Legendre function of the second kind, Qmn(z).
Computes the associated Legendre function of the second kind of order m and
degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
Parameters
----------
m : int
``|m| <= n``; the order of the Legendre function.
n : int
where ``n >= 0``; the degree of the Legendre function. Often
called ``l`` (lower case L) in descriptions of the associated
Legendre function
z : complex
Input value.
Returns
-------
Qmn_z : (m+1, n+1) array
Values for all orders 0..m and degrees 0..n
Qmn_d_z : (m+1, n+1) array
Derivatives for all orders 0..m and degrees 0..n
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(m) or (m < 0):
raise ValueError("m must be a non-negative integer.")
if not isscalar(n) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if not isscalar(z):
raise ValueError("z must be scalar.")
m = int(m)
n = int(n)
# Ensure neither m nor n == 0
mm = max(1, m)
nn = max(1, n)
if iscomplex(z):
q, qd = specfun.clqmn(mm, nn, z)
else:
q, qd = specfun.lqmn(mm, nn, z)
return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)] | [
"def",
"lqmn",
"(",
"m",
",",
"n",
",",
"z",
")",
":",
"if",
"not",
"isscalar",
"(",
"m",
")",
"or",
"(",
"m",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"m must be a non-negative integer.\"",
")",
"if",
"not",
"isscalar",
"(",
"n",
")",
"or",
"(",
"n",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"n must be a non-negative integer.\"",
")",
"if",
"not",
"isscalar",
"(",
"z",
")",
":",
"raise",
"ValueError",
"(",
"\"z must be scalar.\"",
")",
"m",
"=",
"int",
"(",
"m",
")",
"n",
"=",
"int",
"(",
"n",
")",
"# Ensure neither m nor n == 0",
"mm",
"=",
"max",
"(",
"1",
",",
"m",
")",
"nn",
"=",
"max",
"(",
"1",
",",
"n",
")",
"if",
"iscomplex",
"(",
"z",
")",
":",
"q",
",",
"qd",
"=",
"specfun",
".",
"clqmn",
"(",
"mm",
",",
"nn",
",",
"z",
")",
"else",
":",
"q",
",",
"qd",
"=",
"specfun",
".",
"lqmn",
"(",
"mm",
",",
"nn",
",",
"z",
")",
"return",
"q",
"[",
":",
"(",
"m",
"+",
"1",
")",
",",
":",
"(",
"n",
"+",
"1",
")",
"]",
",",
"qd",
"[",
":",
"(",
"m",
"+",
"1",
")",
",",
":",
"(",
"n",
"+",
"1",
")",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/special/basic.py#L1497-L1547 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/compose/_target.py | python | TransformedTargetRegressor.predict | (self, X) | return pred_trans | Predict using the base regressor, applying inverse.
The regressor is used to predict and the ``inverse_func`` or
``inverse_transform`` is applied before returning the prediction.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
Returns
-------
y_hat : array, shape = (n_samples,)
Predicted values. | Predict using the base regressor, applying inverse. | [
"Predict",
"using",
"the",
"base",
"regressor",
"applying",
"inverse",
"."
] | def predict(self, X):
"""Predict using the base regressor, applying inverse.
The regressor is used to predict and the ``inverse_func`` or
``inverse_transform`` is applied before returning the prediction.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Samples.
Returns
-------
y_hat : array, shape = (n_samples,)
Predicted values.
"""
check_is_fitted(self)
pred = self.regressor_.predict(X)
if pred.ndim == 1:
pred_trans = self.transformer_.inverse_transform(
pred.reshape(-1, 1))
else:
pred_trans = self.transformer_.inverse_transform(pred)
if (self._training_dim == 1 and
pred_trans.ndim == 2 and pred_trans.shape[1] == 1):
pred_trans = pred_trans.squeeze(axis=1)
return pred_trans | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
")",
"pred",
"=",
"self",
".",
"regressor_",
".",
"predict",
"(",
"X",
")",
"if",
"pred",
".",
"ndim",
"==",
"1",
":",
"pred_trans",
"=",
"self",
".",
"transformer_",
".",
"inverse_transform",
"(",
"pred",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
")",
"else",
":",
"pred_trans",
"=",
"self",
".",
"transformer_",
".",
"inverse_transform",
"(",
"pred",
")",
"if",
"(",
"self",
".",
"_training_dim",
"==",
"1",
"and",
"pred_trans",
".",
"ndim",
"==",
"2",
"and",
"pred_trans",
".",
"shape",
"[",
"1",
"]",
"==",
"1",
")",
":",
"pred_trans",
"=",
"pred_trans",
".",
"squeeze",
"(",
"axis",
"=",
"1",
")",
"return",
"pred_trans"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/compose/_target.py#L205-L233 | |
LARG/HFO | b8b2a1d462823c6732f4d5581aa7fe2e371d55cb | hfo/hfo.py | python | HFOEnvironment.getUnum | (self) | return hfo_lib.getUnum(self.obj) | Returns the uniform number of the agent | Returns the uniform number of the agent | [
"Returns",
"the",
"uniform",
"number",
"of",
"the",
"agent"
] | def getUnum(self):
""" Returns the uniform number of the agent """
return hfo_lib.getUnum(self.obj) | [
"def",
"getUnum",
"(",
"self",
")",
":",
"return",
"hfo_lib",
".",
"getUnum",
"(",
"self",
".",
"obj",
")"
] | https://github.com/LARG/HFO/blob/b8b2a1d462823c6732f4d5581aa7fe2e371d55cb/hfo/hfo.py#L189-L191 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py | python | _Condition.wait | (self, timeout=None) | Wait until notified or until a timeout occurs.
If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is
awakened by a notify() or notifyAll() call for the same condition
variable in another thread, or until the optional timeout occurs. Once
awakened or timed out, it re-acquires the lock and returns.
When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
When the underlying lock is an RLock, it is not released using its
release() method, since this may not actually unlock the lock when it
was acquired multiple times recursively. Instead, an internal interface
of the RLock class is used, which really unlocks it even when it has
been recursively acquired several times. Another internal interface is
then used to restore the recursion level when the lock is reacquired. | Wait until notified or until a timeout occurs. | [
"Wait",
"until",
"notified",
"or",
"until",
"a",
"timeout",
"occurs",
"."
] | def wait(self, timeout=None):
"""Wait until notified or until a timeout occurs.
If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is
awakened by a notify() or notifyAll() call for the same condition
variable in another thread, or until the optional timeout occurs. Once
awakened or timed out, it re-acquires the lock and returns.
When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
When the underlying lock is an RLock, it is not released using its
release() method, since this may not actually unlock the lock when it
was acquired multiple times recursively. Instead, an internal interface
of the RLock class is used, which really unlocks it even when it has
been recursively acquired several times. Another internal interface is
then used to restore the recursion level when the lock is reacquired.
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
waiter = _allocate_lock()
waiter.acquire()
self.__waiters.append(waiter)
saved_state = self._release_save()
try: # restore state no matter what (e.g., KeyboardInterrupt)
if timeout is None:
waiter.acquire()
if __debug__:
self._note("%s.wait(): got it", self)
else:
# Balancing act: We can't afford a pure busy loop, so we
# have to sleep; but if we sleep the whole timeout time,
# we'll be unresponsive. The scheme here sleeps very
# little at first, longer as time goes on, but never longer
# than 20 times per second (or the timeout time remaining).
endtime = _time() + timeout
delay = 0.0005 # 500 us -> initial delay of 1 ms
while True:
gotit = waiter.acquire(0)
if gotit:
break
remaining = endtime - _time()
if remaining <= 0:
break
delay = min(delay * 2, remaining, .05)
_sleep(delay)
if not gotit:
if __debug__:
self._note("%s.wait(%s): timed out", self, timeout)
try:
self.__waiters.remove(waiter)
except ValueError:
pass
else:
if __debug__:
self._note("%s.wait(%s): got it", self, timeout)
finally:
self._acquire_restore(saved_state) | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_owned",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"cannot wait on un-acquired lock\"",
")",
"waiter",
"=",
"_allocate_lock",
"(",
")",
"waiter",
".",
"acquire",
"(",
")",
"self",
".",
"__waiters",
".",
"append",
"(",
"waiter",
")",
"saved_state",
"=",
"self",
".",
"_release_save",
"(",
")",
"try",
":",
"# restore state no matter what (e.g., KeyboardInterrupt)",
"if",
"timeout",
"is",
"None",
":",
"waiter",
".",
"acquire",
"(",
")",
"if",
"__debug__",
":",
"self",
".",
"_note",
"(",
"\"%s.wait(): got it\"",
",",
"self",
")",
"else",
":",
"# Balancing act: We can't afford a pure busy loop, so we",
"# have to sleep; but if we sleep the whole timeout time,",
"# we'll be unresponsive. The scheme here sleeps very",
"# little at first, longer as time goes on, but never longer",
"# than 20 times per second (or the timeout time remaining).",
"endtime",
"=",
"_time",
"(",
")",
"+",
"timeout",
"delay",
"=",
"0.0005",
"# 500 us -> initial delay of 1 ms",
"while",
"True",
":",
"gotit",
"=",
"waiter",
".",
"acquire",
"(",
"0",
")",
"if",
"gotit",
":",
"break",
"remaining",
"=",
"endtime",
"-",
"_time",
"(",
")",
"if",
"remaining",
"<=",
"0",
":",
"break",
"delay",
"=",
"min",
"(",
"delay",
"*",
"2",
",",
"remaining",
",",
".05",
")",
"_sleep",
"(",
"delay",
")",
"if",
"not",
"gotit",
":",
"if",
"__debug__",
":",
"self",
".",
"_note",
"(",
"\"%s.wait(%s): timed out\"",
",",
"self",
",",
"timeout",
")",
"try",
":",
"self",
".",
"__waiters",
".",
"remove",
"(",
"waiter",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"if",
"__debug__",
":",
"self",
".",
"_note",
"(",
"\"%s.wait(%s): got it\"",
",",
"self",
",",
"timeout",
")",
"finally",
":",
"self",
".",
"_acquire_restore",
"(",
"saved_state",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py#L308-L370 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewModelNotifier.ItemsAdded | (*args, **kwargs) | return _dataview.DataViewModelNotifier_ItemsAdded(*args, **kwargs) | ItemsAdded(self, DataViewItem parent, DataViewItemArray items) -> bool
Override this to be informed that several items have been added to the model. | ItemsAdded(self, DataViewItem parent, DataViewItemArray items) -> bool | [
"ItemsAdded",
"(",
"self",
"DataViewItem",
"parent",
"DataViewItemArray",
"items",
")",
"-",
">",
"bool"
] | def ItemsAdded(*args, **kwargs):
"""
ItemsAdded(self, DataViewItem parent, DataViewItemArray items) -> bool
Override this to be informed that several items have been added to the model.
"""
return _dataview.DataViewModelNotifier_ItemsAdded(*args, **kwargs) | [
"def",
"ItemsAdded",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModelNotifier_ItemsAdded",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L216-L222 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/dtypes/common.py | python | is_scipy_sparse | (arr) | return _is_scipy_sparse(arr) | Check whether an array-like is a scipy.sparse.spmatrix instance.
Parameters
----------
arr : array-like
The array-like to check.
Returns
-------
boolean
Whether or not the array-like is a scipy.sparse.spmatrix instance.
Notes
-----
If scipy is not installed, this function will always return False.
Examples
--------
>>> from scipy.sparse import bsr_matrix
>>> is_scipy_sparse(bsr_matrix([1, 2, 3]))
True
>>> is_scipy_sparse(pd.arrays.SparseArray([1, 2, 3]))
False | Check whether an array-like is a scipy.sparse.spmatrix instance. | [
"Check",
"whether",
"an",
"array",
"-",
"like",
"is",
"a",
"scipy",
".",
"sparse",
".",
"spmatrix",
"instance",
"."
] | def is_scipy_sparse(arr) -> bool:
"""
Check whether an array-like is a scipy.sparse.spmatrix instance.
Parameters
----------
arr : array-like
The array-like to check.
Returns
-------
boolean
Whether or not the array-like is a scipy.sparse.spmatrix instance.
Notes
-----
If scipy is not installed, this function will always return False.
Examples
--------
>>> from scipy.sparse import bsr_matrix
>>> is_scipy_sparse(bsr_matrix([1, 2, 3]))
True
>>> is_scipy_sparse(pd.arrays.SparseArray([1, 2, 3]))
False
"""
global _is_scipy_sparse
if _is_scipy_sparse is None:
try:
from scipy.sparse import issparse as _is_scipy_sparse
except ImportError:
_is_scipy_sparse = lambda _: False
assert _is_scipy_sparse is not None
return _is_scipy_sparse(arr) | [
"def",
"is_scipy_sparse",
"(",
"arr",
")",
"->",
"bool",
":",
"global",
"_is_scipy_sparse",
"if",
"_is_scipy_sparse",
"is",
"None",
":",
"try",
":",
"from",
"scipy",
".",
"sparse",
"import",
"issparse",
"as",
"_is_scipy_sparse",
"except",
"ImportError",
":",
"_is_scipy_sparse",
"=",
"lambda",
"_",
":",
"False",
"assert",
"_is_scipy_sparse",
"is",
"not",
"None",
"return",
"_is_scipy_sparse",
"(",
"arr",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/common.py#L238-L273 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/tools/transformers/gpt2_beamsearch_helper.py | python | Gpt2BeamSearchHelper.onnxruntime_inference | (ort_session, inputs: Gpt2BeamSearchInputs, total_runs: int = 0) | return ort_outputs, average_latency | Run inference of ONNX model, and returns average latency in ms when total_runs > 0 besides outputs. | Run inference of ONNX model, and returns average latency in ms when total_runs > 0 besides outputs. | [
"Run",
"inference",
"of",
"ONNX",
"model",
"and",
"returns",
"average",
"latency",
"in",
"ms",
"when",
"total_runs",
">",
"0",
"besides",
"outputs",
"."
] | def onnxruntime_inference(ort_session, inputs: Gpt2BeamSearchInputs, total_runs: int = 0):
"""Run inference of ONNX model, and returns average latency in ms when total_runs > 0 besides outputs."""
logger.debug(f"start onnxruntime_inference")
ort_inputs = {"input_ids": numpy.ascontiguousarray(inputs.input_ids.cpu().numpy())}
if inputs.position_ids is not None:
ort_inputs["position_ids"] = numpy.ascontiguousarray(inputs.position_ids.cpu().numpy())
if inputs.attention_mask is not None:
ort_inputs["attention_mask"] = numpy.ascontiguousarray(inputs.attention_mask.cpu().numpy())
if inputs.beam_select_idx is not None:
ort_inputs["beam_select_idx"] = numpy.ascontiguousarray(inputs.beam_select_idx.cpu().numpy())
if inputs.input_log_probs is not None:
ort_inputs["input_log_probs"] = numpy.ascontiguousarray(inputs.input_log_probs.cpu().numpy())
if inputs.input_unfinished_sents is not None:
ort_inputs["input_unfinished_sents"] = numpy.ascontiguousarray(inputs.input_unfinished_sents.cpu().numpy())
if inputs.prev_step_results is not None:
ort_inputs["prev_step_results"] = numpy.ascontiguousarray(inputs.prev_step_results.cpu().numpy())
if inputs.prev_step_scores is not None:
ort_inputs["prev_step_scores"] = numpy.ascontiguousarray(inputs.prev_step_scores.cpu().numpy())
if inputs.past is not None:
for i, past_i in enumerate(inputs.past):
ort_inputs[f"past_{i}"] = numpy.ascontiguousarray(past_i.cpu().numpy())
ort_outputs = ort_session.run(None, ort_inputs)
if total_runs == 0:
return ort_outputs
latency = []
for _ in range(total_runs):
start = time.time()
ort_outputs = ort_session.run(None, ort_inputs)
latency.append(time.time() - start)
average_latency = sum(latency) * 1000 / len(latency)
logger.debug("OnnxRuntime Inference time = {} ms".format(format(average_latency, ".2f")))
return ort_outputs, average_latency | [
"def",
"onnxruntime_inference",
"(",
"ort_session",
",",
"inputs",
":",
"Gpt2BeamSearchInputs",
",",
"total_runs",
":",
"int",
"=",
"0",
")",
":",
"logger",
".",
"debug",
"(",
"f\"start onnxruntime_inference\"",
")",
"ort_inputs",
"=",
"{",
"\"input_ids\"",
":",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"input_ids",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"}",
"if",
"inputs",
".",
"position_ids",
"is",
"not",
"None",
":",
"ort_inputs",
"[",
"\"position_ids\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"position_ids",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"if",
"inputs",
".",
"attention_mask",
"is",
"not",
"None",
":",
"ort_inputs",
"[",
"\"attention_mask\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"attention_mask",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"if",
"inputs",
".",
"beam_select_idx",
"is",
"not",
"None",
":",
"ort_inputs",
"[",
"\"beam_select_idx\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"beam_select_idx",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"if",
"inputs",
".",
"input_log_probs",
"is",
"not",
"None",
":",
"ort_inputs",
"[",
"\"input_log_probs\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"input_log_probs",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"if",
"inputs",
".",
"input_unfinished_sents",
"is",
"not",
"None",
":",
"ort_inputs",
"[",
"\"input_unfinished_sents\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"input_unfinished_sents",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"if",
"inputs",
".",
"prev_step_results",
"is",
"not",
"None",
":",
"ort_inputs",
"[",
"\"prev_step_results\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"prev_step_results",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"if",
"inputs",
".",
"prev_step_scores",
"is",
"not",
"None",
":",
"ort_inputs",
"[",
"\"prev_step_scores\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"inputs",
".",
"prev_step_scores",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"if",
"inputs",
".",
"past",
"is",
"not",
"None",
":",
"for",
"i",
",",
"past_i",
"in",
"enumerate",
"(",
"inputs",
".",
"past",
")",
":",
"ort_inputs",
"[",
"f\"past_{i}\"",
"]",
"=",
"numpy",
".",
"ascontiguousarray",
"(",
"past_i",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
")",
"ort_outputs",
"=",
"ort_session",
".",
"run",
"(",
"None",
",",
"ort_inputs",
")",
"if",
"total_runs",
"==",
"0",
":",
"return",
"ort_outputs",
"latency",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"total_runs",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"ort_outputs",
"=",
"ort_session",
".",
"run",
"(",
"None",
",",
"ort_inputs",
")",
"latency",
".",
"append",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
"average_latency",
"=",
"sum",
"(",
"latency",
")",
"*",
"1000",
"/",
"len",
"(",
"latency",
")",
"logger",
".",
"debug",
"(",
"\"OnnxRuntime Inference time = {} ms\"",
".",
"format",
"(",
"format",
"(",
"average_latency",
",",
"\".2f\"",
")",
")",
")",
"return",
"ort_outputs",
",",
"average_latency"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/transformers/gpt2_beamsearch_helper.py#L646-L683 | |
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py | python | _DropCommonSuffixes | (filename) | return os.path.splitext(filename)[0] | Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed. | Drops common suffixes like _test.cc or -inl.h from filename. | [
"Drops",
"common",
"suffixes",
"like",
"_test",
".",
"cc",
"or",
"-",
"inl",
".",
"h",
"from",
"filename",
"."
] | def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed.
"""
for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
'inl.h', 'impl.h', 'internal.h'):
if (filename.endswith(suffix) and len(filename) > len(suffix) and
filename[-len(suffix) - 1] in ('-', '_')):
return filename[:-len(suffix) - 1]
return os.path.splitext(filename)[0] | [
"def",
"_DropCommonSuffixes",
"(",
"filename",
")",
":",
"for",
"suffix",
"in",
"(",
"'test.cc'",
",",
"'regtest.cc'",
",",
"'unittest.cc'",
",",
"'inl.h'",
",",
"'impl.h'",
",",
"'internal.h'",
")",
":",
"if",
"(",
"filename",
".",
"endswith",
"(",
"suffix",
")",
"and",
"len",
"(",
"filename",
")",
">",
"len",
"(",
"suffix",
")",
"and",
"filename",
"[",
"-",
"len",
"(",
"suffix",
")",
"-",
"1",
"]",
"in",
"(",
"'-'",
",",
"'_'",
")",
")",
":",
"return",
"filename",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"-",
"1",
"]",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]"
] | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L3580-L3604 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | ParseResults.append | (self, item) | Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] | [] | def append(self, item):
"""
Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
"""
self.__toklist.append(item) | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"__toklist",
".",
"append",
"(",
"item",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L1599-L1625 | |||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/blocks/robotcontroller.py | python | RobotControllerIO.makeCommand | (self) | return self.retval | Returns the command from previous setXCommand() calls. | Returns the command from previous setXCommand() calls. | [
"Returns",
"the",
"command",
"from",
"previous",
"setXCommand",
"()",
"calls",
"."
] | def makeCommand(self):
"""Returns the command from previous setXCommand() calls."""
return self.retval | [
"def",
"makeCommand",
"(",
"self",
")",
":",
"return",
"self",
".",
"retval"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/blocks/robotcontroller.py#L233-L235 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ExtractIncludesFromCFlags | (self, cflags) | return (clean_cflags, include_paths) | Extract includes "-I..." out from cflags
Args:
cflags: A list of compiler flags, which may be mixed with "-I.."
Returns:
A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed. | Extract includes "-I..." out from cflags | [
"Extract",
"includes",
"-",
"I",
"...",
"out",
"from",
"cflags"
] | def ExtractIncludesFromCFlags(self, cflags):
"""Extract includes "-I..." out from cflags
Args:
cflags: A list of compiler flags, which may be mixed with "-I.."
Returns:
A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed.
"""
clean_cflags = []
include_paths = []
for flag in cflags:
if flag.startswith("-I"):
include_paths.append(flag[2:])
else:
clean_cflags.append(flag)
return (clean_cflags, include_paths) | [
"def",
"ExtractIncludesFromCFlags",
"(",
"self",
",",
"cflags",
")",
":",
"clean_cflags",
"=",
"[",
"]",
"include_paths",
"=",
"[",
"]",
"for",
"flag",
"in",
"cflags",
":",
"if",
"flag",
".",
"startswith",
"(",
"\"-I\"",
")",
":",
"include_paths",
".",
"append",
"(",
"flag",
"[",
"2",
":",
"]",
")",
"else",
":",
"clean_cflags",
".",
"append",
"(",
"flag",
")",
"return",
"(",
"clean_cflags",
",",
"include_paths",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L766-L782 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetCflagsCC | (self, config) | return ['/TP'] + self._GetPchFlags(config, '.cc') | Returns the flags that need to be added to .cc compilations. | Returns the flags that need to be added to .cc compilations. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"cc",
"compilations",
"."
] | def GetCflagsCC(self, config):
"""Returns the flags that need to be added to .cc compilations."""
config = self._TargetConfig(config)
return ['/TP'] + self._GetPchFlags(config, '.cc') | [
"def",
"GetCflagsCC",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"return",
"[",
"'/TP'",
"]",
"+",
"self",
".",
"_GetPchFlags",
"(",
"config",
",",
"'.cc'",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/msvs_emulation.py#L516-L519 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/protobuf/python/stubout.py | python | StubOutForTesting.SmartUnsetAll | (self) | Reverses all the SmartSet() calls, restoring things to their original
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
have no effect if no SmartSet() calls have been made. | Reverses all the SmartSet() calls, restoring things to their original
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
have no effect if no SmartSet() calls have been made. | [
"Reverses",
"all",
"the",
"SmartSet",
"()",
"calls",
"restoring",
"things",
"to",
"their",
"original",
"definition",
".",
"Its",
"okay",
"to",
"call",
"SmartUnsetAll",
"()",
"repeatedly",
"as",
"later",
"calls",
"have",
"no",
"effect",
"if",
"no",
"SmartSet",
"()",
"calls",
"have",
"been",
"made",
"."
] | def SmartUnsetAll(self):
"""Reverses all the SmartSet() calls, restoring things to their original
definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
have no effect if no SmartSet() calls have been made.
"""
self.stubs.reverse()
for args in self.stubs:
setattr(*args)
self.stubs = [] | [
"def",
"SmartUnsetAll",
"(",
"self",
")",
":",
"self",
".",
"stubs",
".",
"reverse",
"(",
")",
"for",
"args",
"in",
"self",
".",
"stubs",
":",
"setattr",
"(",
"*",
"args",
")",
"self",
".",
"stubs",
"=",
"[",
"]"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/stubout.py#L96-L107 | ||
google/ml-metadata | b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d | ml_metadata/metadata_store/types.py | python | Execution.save_execution | (self, store: metadata_store.MetadataStore) | Saves the type and the properties of the execution. | Saves the type and the properties of the execution. | [
"Saves",
"the",
"type",
"and",
"the",
"properties",
"of",
"the",
"execution",
"."
] | def save_execution(self, store: metadata_store.MetadataStore):
"""Saves the type and the properties of the execution."""
if not self.type.type.HasField("id"):
if self.execution.HasField("type_id"):
# In order to avoid committing a new execution type into the database
# when the type id of the execution does not match the type in the
# database, we check here.
[local_type] = store.get_execution_types_by_id([self.execution.type_id])
# Revisit checking input and output types when b/124322020 is resolved.
if not _types_are_equal(local_type, self.type):
raise ValueError(
"ArtifactType in database with artifact's type_id does not match ArtifactType"
)
else:
self.type.id = self.execution.type_id
else:
assert not self.execution.HasField("type_id")
self.type.save(store)
self.execution.type_id = self.type.type.id
assert self.execution.type_id == self.type.id
[execution_id] = store.put_executions([self.execution])
self.execution.id = execution_id | [
"def",
"save_execution",
"(",
"self",
",",
"store",
":",
"metadata_store",
".",
"MetadataStore",
")",
":",
"if",
"not",
"self",
".",
"type",
".",
"type",
".",
"HasField",
"(",
"\"id\"",
")",
":",
"if",
"self",
".",
"execution",
".",
"HasField",
"(",
"\"type_id\"",
")",
":",
"# In order to avoid committing a new execution type into the database",
"# when the type id of the execution does not match the type in the",
"# database, we check here.",
"[",
"local_type",
"]",
"=",
"store",
".",
"get_execution_types_by_id",
"(",
"[",
"self",
".",
"execution",
".",
"type_id",
"]",
")",
"# Revisit checking input and output types when b/124322020 is resolved.",
"if",
"not",
"_types_are_equal",
"(",
"local_type",
",",
"self",
".",
"type",
")",
":",
"raise",
"ValueError",
"(",
"\"ArtifactType in database with artifact's type_id does not match ArtifactType\"",
")",
"else",
":",
"self",
".",
"type",
".",
"id",
"=",
"self",
".",
"execution",
".",
"type_id",
"else",
":",
"assert",
"not",
"self",
".",
"execution",
".",
"HasField",
"(",
"\"type_id\"",
")",
"self",
".",
"type",
".",
"save",
"(",
"store",
")",
"self",
".",
"execution",
".",
"type_id",
"=",
"self",
".",
"type",
".",
"type",
".",
"id",
"assert",
"self",
".",
"execution",
".",
"type_id",
"==",
"self",
".",
"type",
".",
"id",
"[",
"execution_id",
"]",
"=",
"store",
".",
"put_executions",
"(",
"[",
"self",
".",
"execution",
"]",
")",
"self",
".",
"execution",
".",
"id",
"=",
"execution_id"
] | https://github.com/google/ml-metadata/blob/b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d/ml_metadata/metadata_store/types.py#L1168-L1189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.