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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
githubharald/CTCWordBeamSearch | 43567e5b06dd43bdcbec452f5099171c81f5e737 | extras/prototype/Beam.py | python | BeamList.getBestBeams | (self, num) | return sorted(u, reverse=True, key=lambda x: x.getPrTotal() * (x.getPrTextual() ** lmWeight))[:num] | return best beams, specify the max. number of beams to be returned (beam width) | return best beams, specify the max. number of beams to be returned (beam width) | [
"return",
"best",
"beams",
"specify",
"the",
"max",
".",
"number",
"of",
"beams",
"to",
"be",
"returned",
"(",
"beam",
"width",
")"
] | def getBestBeams(self, num):
"return best beams, specify the max. number of beams to be returned (beam width)"
u = [v for (_, v) in self.beams.items()]
lmWeight = 1
return sorted(u, reverse=True, key=lambda x: x.getPrTotal() * (x.getPrTextual() ** lmWeight))[:num] | [
"def",
"getBestBeams",
"(",
"self",
",",
"num",
")",
":",
"u",
"=",
"[",
"v",
"for",
"(",
"_",
",",
"v",
")",
"in",
"self",
".",
"beams",
".",
"items",
"(",
")",
"]",
"lmWeight",
"=",
"1",
"return",
"sorted",
"(",
"u",
",",
"reverse",
"=",
"T... | https://github.com/githubharald/CTCWordBeamSearch/blob/43567e5b06dd43bdcbec452f5099171c81f5e737/extras/prototype/Beam.py#L140-L144 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | WidgetSet.add | (self, subwidget) | return _robotsim.WidgetSet_add(self, subwidget) | add(WidgetSet self, Widget subwidget) | add(WidgetSet self, Widget subwidget) | [
"add",
"(",
"WidgetSet",
"self",
"Widget",
"subwidget",
")"
] | def add(self, subwidget):
"""
add(WidgetSet self, Widget subwidget)
"""
return _robotsim.WidgetSet_add(self, subwidget) | [
"def",
"add",
"(",
"self",
",",
"subwidget",
")",
":",
"return",
"_robotsim",
".",
"WidgetSet_add",
"(",
"self",
",",
"subwidget",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L3124-L3131 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/cross_validation.py | python | _safe_split | (estimator, X, y, indices, train_indices=None) | return X_subset, y_subset | Create subset of dataset and properly handle kernels. | Create subset of dataset and properly handle kernels. | [
"Create",
"subset",
"of",
"dataset",
"and",
"properly",
"handle",
"kernels",
"."
] | def _safe_split(estimator, X, y, indices, train_indices=None):
"""Create subset of dataset and properly handle kernels."""
if hasattr(estimator, 'kernel') and callable(estimator.kernel) \
and not isinstance(estimator.kernel, GPKernel):
# cannot compute the kernel values with custom function
raise ValueError("Cannot use a custom kernel function. "
"Precompute the kernel matrix instead.")
if not hasattr(X, "shape"):
if getattr(estimator, "_pairwise", False):
raise ValueError("Precomputed kernels or affinity matrices have "
"to be passed as arrays or sparse matrices.")
X_subset = [X[idx] for idx in indices]
else:
if getattr(estimator, "_pairwise", False):
# X is a precomputed square kernel matrix
if X.shape[0] != X.shape[1]:
raise ValueError("X should be a square kernel matrix")
if train_indices is None:
X_subset = X[np.ix_(indices, indices)]
else:
X_subset = X[np.ix_(indices, train_indices)]
else:
X_subset = safe_indexing(X, indices)
if y is not None:
y_subset = safe_indexing(y, indices)
else:
y_subset = None
return X_subset, y_subset | [
"def",
"_safe_split",
"(",
"estimator",
",",
"X",
",",
"y",
",",
"indices",
",",
"train_indices",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"estimator",
",",
"'kernel'",
")",
"and",
"callable",
"(",
"estimator",
".",
"kernel",
")",
"and",
"not",
"is... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/cross_validation.py#L1703-L1733 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/ndarray/ndarray.py | python | NDArray.asscalar | (self) | return self.asnumpy()[0] | Returns a scalar whose value is copied from this array.
This function is equivalent to ``self.asnumpy()[0]``. This NDArray must have shape (1,).
Examples
--------
>>> x = mx.nd.ones((1,), dtype='int32')
>>> x.asscalar()
1
>>> type(x.asscalar())
<type 'numpy.int32'> | Returns a scalar whose value is copied from this array. | [
"Returns",
"a",
"scalar",
"whose",
"value",
"is",
"copied",
"from",
"this",
"array",
"."
] | def asscalar(self):
"""Returns a scalar whose value is copied from this array.
This function is equivalent to ``self.asnumpy()[0]``. This NDArray must have shape (1,).
Examples
--------
>>> x = mx.nd.ones((1,), dtype='int32')
>>> x.asscalar()
1
>>> type(x.asscalar())
<type 'numpy.int32'>
"""
if self.shape != (1,):
raise ValueError("The current array is not a scalar")
return self.asnumpy()[0] | [
"def",
"asscalar",
"(",
"self",
")",
":",
"if",
"self",
".",
"shape",
"!=",
"(",
"1",
",",
")",
":",
"raise",
"ValueError",
"(",
"\"The current array is not a scalar\"",
")",
"return",
"self",
".",
"asnumpy",
"(",
")",
"[",
"0",
"]"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L2023-L2038 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/yaml/__init__.py | python | compose_all | (stream, Loader=Loader) | Parse all YAML documents in a stream
and produce corresponding representation trees. | Parse all YAML documents in a stream
and produce corresponding representation trees. | [
"Parse",
"all",
"YAML",
"documents",
"in",
"a",
"stream",
"and",
"produce",
"corresponding",
"representation",
"trees",
"."
] | def compose_all(stream, Loader=Loader):
"""
Parse all YAML documents in a stream
and produce corresponding representation trees.
"""
loader = Loader(stream)
try:
while loader.check_node():
yield loader.get_node()
finally:
loader.dispose() | [
"def",
"compose_all",
"(",
"stream",
",",
"Loader",
"=",
"Loader",
")",
":",
"loader",
"=",
"Loader",
"(",
"stream",
")",
"try",
":",
"while",
"loader",
".",
"check_node",
"(",
")",
":",
"yield",
"loader",
".",
"get_node",
"(",
")",
"finally",
":",
"... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/yaml/__init__.py#L52-L62 | ||
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | python-threatexchange/threatexchange/cli/dataset/simple_serialization.py | python | HMASerialization.as_csv_row | (self) | return (self.indicator, self.indicator_id) + self.rollup.as_row() | indicator details and descriptor rollup without descriptor ID | indicator details and descriptor rollup without descriptor ID | [
"indicator",
"details",
"and",
"descriptor",
"rollup",
"without",
"descriptor",
"ID"
] | def as_csv_row(self) -> t.Tuple:
"""indicator details and descriptor rollup without descriptor ID"""
return (self.indicator, self.indicator_id) + self.rollup.as_row() | [
"def",
"as_csv_row",
"(",
"self",
")",
"->",
"t",
".",
"Tuple",
":",
"return",
"(",
"self",
".",
"indicator",
",",
"self",
".",
"indicator_id",
")",
"+",
"self",
".",
"rollup",
".",
"as_row",
"(",
")"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/cli/dataset/simple_serialization.py#L116-L118 | |
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/internal/decoder.py | python | Decoder.ReadFieldNumberAndWireType | (self) | return wire_format.UnpackTag(tag_and_type) | Reads a tag from the wire. Returns a (field_number, wire_type) pair. | Reads a tag from the wire. Returns a (field_number, wire_type) pair. | [
"Reads",
"a",
"tag",
"from",
"the",
"wire",
".",
"Returns",
"a",
"(",
"field_number",
"wire_type",
")",
"pair",
"."
] | def ReadFieldNumberAndWireType(self):
"""Reads a tag from the wire. Returns a (field_number, wire_type) pair."""
tag_and_type = self.ReadUInt32()
return wire_format.UnpackTag(tag_and_type) | [
"def",
"ReadFieldNumberAndWireType",
"(",
"self",
")",
":",
"tag_and_type",
"=",
"self",
".",
"ReadUInt32",
"(",
")",
"return",
"wire_format",
".",
"UnpackTag",
"(",
"tag_and_type",
")"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/decoder.py#L72-L75 | |
zhaoweicai/cascade-rcnn | 2252f46158ea6555868ca6fa5c221ea71d9b5e6c | python/caffe/draw.py | python | get_layer_label | (layer, rankdir) | return node_label | Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer | Define node label based on layer type. | [
"Define",
"node",
"label",
"based",
"on",
"layer",
"type",
"."
] | def get_layer_label(layer, rankdir):
"""Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer
"""
if rankdir in ('TB', 'BT'):
# If graph orientation is vertical, horizontal space is free and
# vertical space is not; separate words with spaces
separator = ' '
else:
# If graph orientation is horizontal, vertical space is free and
# horizontal space is not; separate words with newlines
separator = '\\n'
if layer.type == 'Convolution' or layer.type == 'Deconvolution':
# Outer double quotes needed or else colon characters don't parse
# properly
node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
layer.type,
separator,
layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size) else 1,
separator,
layer.convolution_param.stride[0] if len(layer.convolution_param.stride) else 1,
separator,
layer.convolution_param.pad[0] if len(layer.convolution_param.pad) else 0)
elif layer.type == 'Pooling':
pooling_types_dict = get_pooling_types_dict()
node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
pooling_types_dict[layer.pooling_param.pool],
layer.type,
separator,
layer.pooling_param.kernel_size,
separator,
layer.pooling_param.stride,
separator,
layer.pooling_param.pad)
else:
node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type)
return node_label | [
"def",
"get_layer_label",
"(",
"layer",
",",
"rankdir",
")",
":",
"if",
"rankdir",
"in",
"(",
"'TB'",
",",
"'BT'",
")",
":",
"# If graph orientation is vertical, horizontal space is free and",
"# vertical space is not; separate words with spaces",
"separator",
"=",
"' '",
... | https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/python/caffe/draw.py#L62-L114 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathSetupSheet.py | python | SetupSheet.expressionReference | (self) | return self.obj.Name | expressionReference() ... returns the string to be used in expressions | expressionReference() ... returns the string to be used in expressions | [
"expressionReference",
"()",
"...",
"returns",
"the",
"string",
"to",
"be",
"used",
"in",
"expressions"
] | def expressionReference(self):
"""expressionReference() ... returns the string to be used in expressions"""
# Using the Name here and not the Label (both would be valid) because the Name 'fails early'.
#
# If there is a Name/Label conflict and an expression is bound to the Name we'll get an error
# on creation (Property not found). Not good, but at least there's some indication that
# something's afoul.
#
# If the expression is based on the Label everything works out nicely - until the document is
# saved and loaded from disk. The Labels change in order to avoid the Name/Label conflict
# but the expression stays the same. If the user's lucky the expression is broken because the
# conflicting object doesn't have the properties reference by the expressions. If the user is
# not so lucky those properties also exist in the other object, there is no indication that
# anything is wrong but the expressions will substitute the values from the wrong object.
#
# I prefer the question: "why do I get this error when I create ..." over "my cnc machine just
# rammed it's tool head into the table ..." or even "I saved my file and now it's corrupt..."
#
# https://forum.freecadweb.org/viewtopic.php?f=10&t=24839
# https://forum.freecadweb.org/viewtopic.php?f=10&t=24845
return self.obj.Name | [
"def",
"expressionReference",
"(",
"self",
")",
":",
"# Using the Name here and not the Label (both would be valid) because the Name 'fails early'.",
"#",
"# If there is a Name/Label conflict and an expression is bound to the Name we'll get an error",
"# on creation (Property not found). Not good,... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathSetupSheet.py#L345-L365 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/instrument.py | python | Instrument.risk_limit | (self) | return self._risk_limit | Gets the risk_limit of this Instrument. # noqa: E501
:return: The risk_limit of this Instrument. # noqa: E501
:rtype: float | Gets the risk_limit of this Instrument. # noqa: E501 | [
"Gets",
"the",
"risk_limit",
"of",
"this",
"Instrument",
".",
"#",
"noqa",
":",
"E501"
] | def risk_limit(self):
"""Gets the risk_limit of this Instrument. # noqa: E501
:return: The risk_limit of this Instrument. # noqa: E501
:rtype: float
"""
return self._risk_limit | [
"def",
"risk_limit",
"(",
"self",
")",
":",
"return",
"self",
".",
"_risk_limit"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument.py#L1360-L1367 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/functional/nn.py | python | one_hot | (inp: Tensor, num_classes: int) | return result | r"""Performs one-hot encoding for the input tensor.
Args:
inp: input tensor.
num_classes: number of classes denotes the last dimension of the output tensor.
Examples:
.. testcode::
import numpy as np
from megengine import tensor
import megengine.functional as F
x = tensor(np.arange(1, 4, dtype=np.int32))
out = F.one_hot(x, num_classes=4)
print(out.numpy())
Outputs:
.. testoutput::
[[0 1 0 0]
[0 0 1 0]
[0 0 0 1]] | r"""Performs one-hot encoding for the input tensor. | [
"r",
"Performs",
"one",
"-",
"hot",
"encoding",
"for",
"the",
"input",
"tensor",
"."
] | def one_hot(inp: Tensor, num_classes: int) -> Tensor:
r"""Performs one-hot encoding for the input tensor.
Args:
inp: input tensor.
num_classes: number of classes denotes the last dimension of the output tensor.
Examples:
.. testcode::
import numpy as np
from megengine import tensor
import megengine.functional as F
x = tensor(np.arange(1, 4, dtype=np.int32))
out = F.one_hot(x, num_classes=4)
print(out.numpy())
Outputs:
.. testoutput::
[[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]
"""
zeros_tensor = zeros(
list(inp.shape) + [num_classes], dtype=inp.dtype, device=inp.device
)
ones_tensor = ones(list(inp.shape) + [1], dtype=inp.dtype, device=inp.device)
op = builtin.IndexingSetOneHot(axis=inp.ndim)
(result,) = apply(op, zeros_tensor, inp, ones_tensor)
return result | [
"def",
"one_hot",
"(",
"inp",
":",
"Tensor",
",",
"num_classes",
":",
"int",
")",
"->",
"Tensor",
":",
"zeros_tensor",
"=",
"zeros",
"(",
"list",
"(",
"inp",
".",
"shape",
")",
"+",
"[",
"num_classes",
"]",
",",
"dtype",
"=",
"inp",
".",
"dtype",
"... | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/nn.py#L1517-L1551 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/searchengine.py | python | SearchEngine.__init__ | (self, root) | Initialize Variables that save search state.
The dialogs bind these to the UI elements present in the dialogs. | Initialize Variables that save search state. | [
"Initialize",
"Variables",
"that",
"save",
"search",
"state",
"."
] | def __init__(self, root):
'''Initialize Variables that save search state.
The dialogs bind these to the UI elements present in the dialogs.
'''
self.root = root # need for report_error()
self.patvar = StringVar(root, '') # search pattern
self.revar = BooleanVar(root, False) # regular expression?
self.casevar = BooleanVar(root, False) # match case?
self.wordvar = BooleanVar(root, False) # match whole word?
self.wrapvar = BooleanVar(root, True) # wrap around buffer?
self.backvar = BooleanVar(root, False) | [
"def",
"__init__",
"(",
"self",
",",
"root",
")",
":",
"self",
".",
"root",
"=",
"root",
"# need for report_error()",
"self",
".",
"patvar",
"=",
"StringVar",
"(",
"root",
",",
"''",
")",
"# search pattern",
"self",
".",
"revar",
"=",
"BooleanVar",
"(",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/searchengine.py#L22-L33 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | GraphicsPath.GetBox | (*args, **kwargs) | return _gdi_.GraphicsPath_GetBox(*args, **kwargs) | GetBox(self) -> Rect2D
Gets the bounding box enclosing all points (possibly including control
points) | GetBox(self) -> Rect2D | [
"GetBox",
"(",
"self",
")",
"-",
">",
"Rect2D"
] | def GetBox(*args, **kwargs):
"""
GetBox(self) -> Rect2D
Gets the bounding box enclosing all points (possibly including control
points)
"""
return _gdi_.GraphicsPath_GetBox(*args, **kwargs) | [
"def",
"GetBox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsPath_GetBox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L5861-L5868 | |
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | python/pyarrow/pandas_compat.py | python | get_column_metadata | (column, name, arrow_type, field_name) | return {
'name': name,
'field_name': 'None' if field_name is None else field_name,
'pandas_type': logical_type,
'numpy_type': string_dtype,
'metadata': extra_metadata,
} | Construct the metadata for a given column
Parameters
----------
column : pandas.Series or pandas.Index
name : str
arrow_type : pyarrow.DataType
field_name : str
Equivalent to `name` when `column` is a `Series`, otherwise if `column`
is a pandas Index then `field_name` will not be the same as `name`.
This is the name of the field in the arrow Table's schema.
Returns
-------
dict | Construct the metadata for a given column | [
"Construct",
"the",
"metadata",
"for",
"a",
"given",
"column"
] | def get_column_metadata(column, name, arrow_type, field_name):
"""Construct the metadata for a given column
Parameters
----------
column : pandas.Series or pandas.Index
name : str
arrow_type : pyarrow.DataType
field_name : str
Equivalent to `name` when `column` is a `Series`, otherwise if `column`
is a pandas Index then `field_name` will not be the same as `name`.
This is the name of the field in the arrow Table's schema.
Returns
-------
dict
"""
logical_type = get_logical_type(arrow_type)
string_dtype, extra_metadata = get_extension_dtype_info(column)
if logical_type == 'decimal':
extra_metadata = {
'precision': arrow_type.precision,
'scale': arrow_type.scale,
}
string_dtype = 'object'
if name is not None and not isinstance(name, str):
raise TypeError(
'Column name must be a string. Got column {} of type {}'.format(
name, type(name).__name__
)
)
assert field_name is None or isinstance(field_name, str), \
str(type(field_name))
return {
'name': name,
'field_name': 'None' if field_name is None else field_name,
'pandas_type': logical_type,
'numpy_type': string_dtype,
'metadata': extra_metadata,
} | [
"def",
"get_column_metadata",
"(",
"column",
",",
"name",
",",
"arrow_type",
",",
"field_name",
")",
":",
"logical_type",
"=",
"get_logical_type",
"(",
"arrow_type",
")",
"string_dtype",
",",
"extra_metadata",
"=",
"get_extension_dtype_info",
"(",
"column",
")",
"... | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/pandas_compat.py#L139-L181 | |
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/generator/make.py | python | StringToMakefileVariable | (string) | return re.sub('[^a-zA-Z0-9_]', '_', string) | Convert a string to a value that is acceptable as a make variable name. | Convert a string to a value that is acceptable as a make variable name. | [
"Convert",
"a",
"string",
"to",
"a",
"value",
"that",
"is",
"acceptable",
"as",
"a",
"make",
"variable",
"name",
"."
] | def StringToMakefileVariable(string):
"""Convert a string to a value that is acceptable as a make variable name."""
return re.sub('[^a-zA-Z0-9_]', '_', string) | [
"def",
"StringToMakefileVariable",
"(",
"string",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'[^a-zA-Z0-9_]'",
",",
"'_'",
",",
"string",
")"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/generator/make.py#L601-L603 | |
simon-anders/htseq | 5ba0507ea237e2e067ea79fb28febbc56a37f0d4 | python3/HTSeq/scripts/count.py | python | count_reads_in_features | (
sam_filenames,
gff_filename,
order,
max_buffer_size,
stranded,
overlap_mode,
multimapped_mode,
secondary_alignment_mode,
supplementary_alignment_mode,
feature_type,
id_attribute,
additional_attributes,
quiet,
minaqual,
samouts,
samout_format,
output_delimiter,
output_filename,
output_append,
nprocesses,
feature_query,
) | Count reads in features, parallelizing by file | Count reads in features, parallelizing by file | [
"Count",
"reads",
"in",
"features",
"parallelizing",
"by",
"file"
] | def count_reads_in_features(
sam_filenames,
gff_filename,
order,
max_buffer_size,
stranded,
overlap_mode,
multimapped_mode,
secondary_alignment_mode,
supplementary_alignment_mode,
feature_type,
id_attribute,
additional_attributes,
quiet,
minaqual,
samouts,
samout_format,
output_delimiter,
output_filename,
output_append,
nprocesses,
feature_query,
):
'''Count reads in features, parallelizing by file'''
def parse_feature_query(feature_query):
if '"' not in feature_query:
raise ValueError('Invalid feature query')
if '==' not in feature_query:
raise ValueError('Invalid feature query')
idx_quote1 = feature_query.find('"')
idx_quote2 = feature_query.rfind('"')
attr_name = feature_query[idx_quote1+1: idx_quote2]
idx_equal = feature_query[:idx_quote1].find('==')
attr_cat = feature_query[:idx_equal].strip()
return {
'attr_cat': attr_cat,
'attr_name': attr_name,
}
if samouts != []:
if len(samouts) != len(sam_filenames):
raise ValueError(
'Select the same number of input and output files')
# Try to open samout files early in case any of them has issues
if samout_format in ('SAM', 'sam'):
for samout in samouts:
with open(samout, 'w'):
pass
else:
# We don't have a template if the input is stdin
if (len(sam_filenames) != 1) or (sam_filenames[0] != '-'):
for sam_filename, samout in zip(sam_filenames, samouts):
with pysam.AlignmentFile(sam_filename, 'r') as sf:
with pysam.AlignmentFile(samout, 'w', template=sf):
pass
else:
samouts = [None for x in sam_filenames]
# Try to open samfiles to fail early in case any of them is not there
if (len(sam_filenames) != 1) or (sam_filenames[0] != '-'):
for sam_filename in sam_filenames:
with pysam.AlignmentFile(sam_filename, 'r') as sf:
pass
if feature_query is not None:
feature_qdic = parse_feature_query(feature_query)
features = HTSeq.GenomicArrayOfSets("auto", stranded != "no")
gff = HTSeq.GFF_Reader(gff_filename)
attributes = {}
i = 0
try:
for f in gff:
if f.type == feature_type:
try:
feature_id = f.attr[id_attribute]
except KeyError:
raise ValueError(
"Feature %s does not contain a '%s' attribute" %
(f.name, id_attribute))
if stranded != "no" and f.iv.strand == ".":
raise ValueError(
"Feature %s at %s does not have strand information but you are "
"running htseq-count in stranded mode. Use '--stranded=no'." %
(f.name, f.iv))
if feature_query is not None:
# Skip the features that don't even have the right attr
if feature_qdic['attr_cat'] not in f.attr:
continue
# Skip the ones with an attribute with a different name
# from the query (e.g. other genes)
if f.attr[feature_qdic['attr_cat']] != feature_qdic['attr_name']:
continue
features[f.iv] += feature_id
attributes[feature_id] = [
f.attr[attr] if attr in f.attr else ''
for attr in additional_attributes]
i += 1
if i % 100000 == 0 and not quiet:
sys.stderr.write("%d GFF lines processed.\n" % i)
sys.stderr.flush()
except:
sys.stderr.write(
"Error occured when processing GFF file (%s):\n" %
gff.get_line_number_string())
raise
feature_attr = sorted(attributes.keys())
if not quiet:
sys.stderr.write("%d GFF lines processed.\n" % i)
sys.stderr.flush()
if len(feature_attr) == 0:
sys.stderr.write(
"Warning: No features of type '%s' found.\n" % feature_type)
# Prepare arguments for counting function
args = []
for isam, (sam_filename, samout_filename) in enumerate(zip(sam_filenames, samouts)):
args.append((
isam,
sam_filename,
features,
feature_attr,
order,
max_buffer_size,
stranded,
overlap_mode,
multimapped_mode,
secondary_alignment_mode,
supplementary_alignment_mode,
feature_type,
id_attribute,
additional_attributes,
quiet,
minaqual,
samout_format,
samout_filename,
))
# Count reads
if nprocesses > 1:
with multiprocessing.Pool(nprocesses) as pool:
results = pool.starmap(count_reads_single_file, args)
results.sort(key=operator.itemgetter('isam'))
else:
results = list(itertools.starmap(count_reads_single_file, args))
# Write output
other_features = [
('__no_feature', 'empty'),
('__ambiguous', 'ambiguous'),
('__too_low_aQual', 'lowqual'),
('__not_aligned', 'notaligned'),
('__alignment_not_unique', 'nonunique'),
]
pad = ['' for attr in additional_attributes]
for ifn, fn in enumerate(feature_attr):
fields = [fn] + attributes[fn] + [str(r['counts'][fn]) for r in results]
line = output_delimiter.join(fields)
if output_filename == '':
print(line)
else:
omode = 'a' if output_append or (ifn > 0) else 'w'
with open(output_filename, omode) as f:
f.write(line)
f.write('\n')
for title, fn in other_features:
fields = [title] + pad + [str(r[fn]) for r in results]
line = output_delimiter.join(fields)
if output_filename == '':
print(line)
else:
with open(output_filename, 'a') as f:
f.write(line)
f.write('\n') | [
"def",
"count_reads_in_features",
"(",
"sam_filenames",
",",
"gff_filename",
",",
"order",
",",
"max_buffer_size",
",",
"stranded",
",",
"overlap_mode",
",",
"multimapped_mode",
",",
"secondary_alignment_mode",
",",
"supplementary_alignment_mode",
",",
"feature_type",
","... | https://github.com/simon-anders/htseq/blob/5ba0507ea237e2e067ea79fb28febbc56a37f0d4/python3/HTSeq/scripts/count.py#L322-L504 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/NinjaWriter.py | python | NinjaWriter.WriteSpec | (self) | return self.target | The entry point for NinjaWriter: write the build rules for a spec.
Returns a Target object, which represents the output paths for this spec.
Returns None if there are no outputs (e.g. a settings-only 'none' type
target). | The entry point for NinjaWriter: write the build rules for a spec. | [
"The",
"entry",
"point",
"for",
"NinjaWriter",
":",
"write",
"the",
"build",
"rules",
"for",
"a",
"spec",
"."
] | def WriteSpec(self):
"""
The entry point for NinjaWriter: write the build rules for a spec.
Returns a Target object, which represents the output paths for this spec.
Returns None if there are no outputs (e.g. a settings-only 'none' type
target).
"""
if self.flavor == 'mac':
self.xcode_settings = xcode_emulation.XcodeSettings(self.spec)
mac_toolchain_dir = self.generator_flags.get('mac_toolchain_dir', None)
if mac_toolchain_dir:
self.xcode_settings.mac_toolchain_dir = mac_toolchain_dir
if self.flavor == 'win':
self.msvs_settings = msvs_emulation.MsvsSettings(self.spec, self.generator_flags)
arch = self.msvs_settings.GetArch(self.config_name)
self.ninja.variable('arch', self.win_env[arch])
self.ninja.variable('cc', '$cl_' + arch)
self.ninja.variable('cxx', '$cl_' + arch)
self.ninja.variable('cc_host', '$cl_' + arch)
self.ninja.variable('cxx_host', '$cl_' + arch)
self.ninja.variable('asm', '$ml_' + arch)
if self.flavor == 'mac':
self.archs = self.xcode_settings.GetActiveArchs(self.config_name)
if len(self.archs) > 1:
self.arch_subninjas = dict(
(arch, ninja_syntax.Writer(OpenOutput(os.path.join(self.toplevel_build, self._SubninjaNameForArch(arch)))))
for arch in self.archs
)
# Compute pre-depends for all rules.
# actions_depends is the dependencies this target depends on before running any of its action/rule/copy steps.
# compile_depends is the dependencies this target depends on before running any of its compile steps.
actions_depends = []
compile_depends = []
# TODO(evan): it is rather confusing which things are lists and which
# are strings. Fix these.
if 'dependencies' in self.spec:
for dep in self.spec['dependencies']:
if dep in self.target_outputs:
target = self.target_outputs[dep]
actions_depends.append(target.PreActionInput(self.flavor))
compile_depends.append(target.PreCompileInput())
if target.uses_cpp:
self.target.uses_cpp = True
actions_depends = [d for d in actions_depends if d]
compile_depends = [d for d in compile_depends if d]
actions_depends = self._WriteCollapsedDependencies('actions_depends', actions_depends)
compile_depends = self._WriteCollapsedDependencies('compile_depends', compile_depends)
self.target.preaction_stamp = actions_depends
self.target.precompile_stamp = compile_depends
# Write out actions, rules, and copies. These must happen before we
# compile any sources, so compute a list of predependencies for sources
# while we do it.
extra_sources = []
mac_bundle_depends = []
self.target.actions_stamp = self._WriteActionsRulesCopies(self.spec, extra_sources, actions_depends, mac_bundle_depends)
# If we have actions/rules/copies, we depend directly on those, but
# otherwise we depend on dependent target's actions/rules/copies etc.
# We never need to explicitly depend on previous target's link steps,
# because no compile ever depends on them.
compile_depends_stamp = self.target.actions_stamp or compile_depends
# Write out the compilation steps, if any.
link_deps = []
try:
sources = extra_sources + self.spec.get('sources', [])
except TypeError:
print('extra_sources: ', str(extra_sources))
print('spec.get("sources"): ', str(self.spec.get('sources')))
raise
if sources:
if self.flavor == 'mac' and len(self.archs) > 1:
# Write subninja file containing compile and link commands scoped to
# a single arch if a fat binary is being built.
for arch in self.archs:
self.ninja.subninja(self._SubninjaNameForArch(arch))
if self.flavor == 'win':
gyp.msvs_emulation.VerifyMissingSources(sources, self.abs_build_dir, self.generator_flags, self._GypPathToNinja)
pch = gyp.msvs_emulation.PrecompiledHeader(self.msvs_settings, self.config_name, self._GypPathToNinja, self._GypPathToUniqueOutput, self.obj_ext)
else:
pch = gyp.xcode_emulation.MacPrefixHeader(self.xcode_settings, self._GypPathToNinja, lambda path, lang: self._GypPathToUniqueOutput(path + '-' + lang))
link_deps = self._WriteSources(self.config_name, self.config, sources, compile_depends_stamp, pch, self.spec)
# Some actions/rules output 'sources' that are already object files.
obj_outputs = [f for f in sources if f.endswith(self.obj_ext)]
if obj_outputs:
if self.flavor != 'mac' or len(self.archs) == 1:
link_deps += [self._GypPathToNinja(o) for o in obj_outputs]
else:
print("Warning: Actions/rules writing object files don't work with multi-arch targets, dropping. (target %s)" % self.spec['target_name'])
elif self.flavor == 'mac' and len(self.archs) > 1:
link_deps = OrderedDict((a, []) for a in self.archs)
compile_deps = self.target.actions_stamp or actions_depends
if self.flavor == 'win' and self.target.type == 'static_library':
self.target.component_objs = link_deps
self.target.compile_deps = compile_deps
# Write out a link step, if needed.
output = None
is_empty_bundle = not link_deps and not mac_bundle_depends
if link_deps or self.target.actions_stamp or actions_depends:
output = self._WriteTarget(self.spec, self.config_name, self.config, link_deps, compile_deps)
if self.is_mac_bundle:
mac_bundle_depends.append(output)
# Bundle all of the above together, if needed.
if self.is_mac_bundle:
output = self._WriteMacBundle(self.spec, mac_bundle_depends, is_empty_bundle)
if not output:
return None
assert self.target.FinalOutput(), output
return self.target | [
"def",
"WriteSpec",
"(",
"self",
")",
":",
"if",
"self",
".",
"flavor",
"==",
"'mac'",
":",
"self",
".",
"xcode_settings",
"=",
"xcode_emulation",
".",
"XcodeSettings",
"(",
"self",
".",
"spec",
")",
"mac_toolchain_dir",
"=",
"self",
".",
"generator_flags",
... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/NinjaWriter.py#L1250-L1370 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/linalg_ops.py | python | _MatrixSolveLsShapeHelper | (lhs_shape, rhs_shape) | return [lhs_shape[:-2].concatenate([lhs_shape[-1], rhs_shape[-1]])] | Shape inference helper function for least squares matrix solver ops. | Shape inference helper function for least squares matrix solver ops. | [
"Shape",
"inference",
"helper",
"function",
"for",
"least",
"squares",
"matrix",
"solver",
"ops",
"."
] | def _MatrixSolveLsShapeHelper(lhs_shape, rhs_shape):
"""Shape inference helper function for least squares matrix solver ops."""
# The matrices and right-hand sides must have the same number of rows.
lhs_shape[-2].assert_is_compatible_with(rhs_shape[-2])
return [lhs_shape[:-2].concatenate([lhs_shape[-1], rhs_shape[-1]])] | [
"def",
"_MatrixSolveLsShapeHelper",
"(",
"lhs_shape",
",",
"rhs_shape",
")",
":",
"# The matrices and right-hand sides must have the same number of rows.",
"lhs_shape",
"[",
"-",
"2",
"]",
".",
"assert_is_compatible_with",
"(",
"rhs_shape",
"[",
"-",
"2",
"]",
")",
"ret... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/linalg_ops.py#L187-L191 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py | python | _ToLocalPath | (toplevel_dir, path) | return path | Converts |path| to a path relative to |toplevel_dir|. | Converts |path| to a path relative to |toplevel_dir|. | [
"Converts",
"|path|",
"to",
"a",
"path",
"relative",
"to",
"|toplevel_dir|",
"."
] | def _ToLocalPath(toplevel_dir, path):
"""Converts |path| to a path relative to |toplevel_dir|."""
if path == toplevel_dir:
return ''
if path.startswith(toplevel_dir + '/'):
return path[len(toplevel_dir) + len('/'):]
return path | [
"def",
"_ToLocalPath",
"(",
"toplevel_dir",
",",
"path",
")",
":",
"if",
"path",
"==",
"toplevel_dir",
":",
"return",
"''",
"if",
"path",
".",
"startswith",
"(",
"toplevel_dir",
"+",
"'/'",
")",
":",
"return",
"path",
"[",
"len",
"(",
"toplevel_dir",
")"... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py#L169-L175 | |
BTCPrivate/BTCP-Rebase | c8c7fe6ac26b6fba71eae1c89cdc0d924f5c6d82 | contrib/devtools/update-translations.py | python | remove_invalid_characters | (s) | return FIX_RE.sub(b'', s) | Remove invalid characters from translation string | Remove invalid characters from translation string | [
"Remove",
"invalid",
"characters",
"from",
"translation",
"string"
] | def remove_invalid_characters(s):
'''Remove invalid characters from translation string'''
return FIX_RE.sub(b'', s) | [
"def",
"remove_invalid_characters",
"(",
"s",
")",
":",
"return",
"FIX_RE",
".",
"sub",
"(",
"b''",
",",
"s",
")"
] | https://github.com/BTCPrivate/BTCP-Rebase/blob/c8c7fe6ac26b6fba71eae1c89cdc0d924f5c6d82/contrib/devtools/update-translations.py#L114-L116 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | driver/python/pysequoiadb/replicagroup.py | python | replicagroup.create_node | (self, hostname, servicename, dbpath, config=None) | Create node in a given replica group.
Parameters:
Name Type Info:
hostname str The host name for the node.
servicename str The servicename for the node.
dbpath str The database path for the node.
config dict The configurations for the node.
Exceptions:
pysequoiadb.error.SDBBaseError | Create node in a given replica group. | [
"Create",
"node",
"in",
"a",
"given",
"replica",
"group",
"."
] | def create_node(self, hostname, servicename, dbpath, config=None):
"""Create node in a given replica group.
Parameters:
Name Type Info:
hostname str The host name for the node.
servicename str The servicename for the node.
dbpath str The database path for the node.
config dict The configurations for the node.
Exceptions:
pysequoiadb.error.SDBBaseError
"""
if not isinstance(hostname, str_type):
raise SDBTypeError("host must be an instance of str_type")
if not isinstance(servicename, str_type):
raise SDBTypeError("service name must be an instance of str_type")
if not isinstance(dbpath, str_type):
raise SDBTypeError("path must be an instance of str_type")
if config is not None and not isinstance(config, dict):
raise SDBTypeError("config must be an instance of dict")
if config is None:
config = {}
bson_options = bson.BSON.encode(config)
rc = sdb.gp_create_node(self._group, hostname, servicename,
dbpath, bson_options)
raise_if_error(rc, "Failed to create node") | [
"def",
"create_node",
"(",
"self",
",",
"hostname",
",",
"servicename",
",",
"dbpath",
",",
"config",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"hostname",
",",
"str_type",
")",
":",
"raise",
"SDBTypeError",
"(",
"\"host must be an instance of str... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/replicagroup.py#L237-L264 | ||
luca-m/emotime | 643a5c09144b515a102942a178a3b7ce0e2cdc92 | src/dataset/datasetTrain.py | python | dataset_run_training | (dsFolder, config, mode) | Start training | Start training | [
"Start",
"training"
] | def dataset_run_training(dsFolder, config, mode):
"""
Start training
"""
trainFldr = join(dsFolder, config['TRAIN_FOLDER'])
if mode == "ada":
smode = "ada"
classifFldr = join(dsFolder, config['CLASSIFIER_ADA_FOLDER'])
else:
smode = "svm"
classifFldr = join(dsFolder, config['CLASSIFIER_SVM_FOLDER'])
dataset_train(smode, trainFldr, classifFldr, config) | [
"def",
"dataset_run_training",
"(",
"dsFolder",
",",
"config",
",",
"mode",
")",
":",
"trainFldr",
"=",
"join",
"(",
"dsFolder",
",",
"config",
"[",
"'TRAIN_FOLDER'",
"]",
")",
"if",
"mode",
"==",
"\"ada\"",
":",
"smode",
"=",
"\"ada\"",
"classifFldr",
"="... | https://github.com/luca-m/emotime/blob/643a5c09144b515a102942a178a3b7ce0e2cdc92/src/dataset/datasetTrain.py#L48-L59 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/dtypes.py | python | DType._is_ref_dtype | (self) | return self._type_enum > 100 | Returns `True` if this `DType` represents a reference type. | Returns `True` if this `DType` represents a reference type. | [
"Returns",
"True",
"if",
"this",
"DType",
"represents",
"a",
"reference",
"type",
"."
] | def _is_ref_dtype(self):
"""Returns `True` if this `DType` represents a reference type."""
return self._type_enum > 100 | [
"def",
"_is_ref_dtype",
"(",
"self",
")",
":",
"return",
"self",
".",
"_type_enum",
">",
"100"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/dtypes.py#L86-L88 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | WindowList.__contains__ | (*args, **kwargs) | return _core_.WindowList___contains__(*args, **kwargs) | __contains__(self, Window obj) -> bool | __contains__(self, Window obj) -> bool | [
"__contains__",
"(",
"self",
"Window",
"obj",
")",
"-",
">",
"bool"
] | def __contains__(*args, **kwargs):
"""__contains__(self, Window obj) -> bool"""
return _core_.WindowList___contains__(*args, **kwargs) | [
"def",
"__contains__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"WindowList___contains__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L9063-L9065 | |
osquery/osquery | fd529718e48348853f708d56990720c3c84c7152 | tools/codegen/templite.py | python | Templite.__init__ | (self, text=None, filename=None,
encoding='utf-8', delimiters=None, caching=False) | Loads a template from string or file. | Loads a template from string or file. | [
"Loads",
"a",
"template",
"from",
"string",
"or",
"file",
"."
] | def __init__(self, text=None, filename=None,
encoding='utf-8', delimiters=None, caching=False):
"""Loads a template from string or file."""
if filename:
filename = os.path.abspath(filename)
mtime = os.path.getmtime(filename)
self.file = key = filename
elif text is not None:
self.file = mtime = None
key = hash(text)
else:
raise ValueError('either text or filename required')
# set attributes
self.encoding = encoding
self.caching = caching
if delimiters:
start, end = delimiters
if len(start) != 2 or len(end) != 2:
raise ValueError('each delimiter must be two characters long')
self.delimiters = delimiters
# check cache
cache = self.cache
if caching and key in cache and cache[key][0] == mtime:
self._code = cache[key][1]
return
# read file
if filename:
with open(filename) as fh:
text = fh.read()
self._code = self._compile(text)
if caching:
cache[key] = (mtime, self._code) | [
"def",
"__init__",
"(",
"self",
",",
"text",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"delimiters",
"=",
"None",
",",
"caching",
"=",
"False",
")",
":",
"if",
"filename",
":",
"filename",
"=",
"os",
".",
"path"... | https://github.com/osquery/osquery/blob/fd529718e48348853f708d56990720c3c84c7152/tools/codegen/templite.py#L37-L68 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/goat-latin.py | python | Solution.toGoatLatin | (self, S) | return " ".join(convert(S)) | :type S: str
:rtype: str | :type S: str
:rtype: str | [
":",
"type",
"S",
":",
"str",
":",
"rtype",
":",
"str"
] | def toGoatLatin(self, S):
"""
:type S: str
:rtype: str
"""
def convert(S):
vowel = set('aeiouAEIOU')
for i, word in enumerate(S.split(), 1):
if word[0] not in vowel:
word = word[1:] + word[:1]
yield word + 'ma' + 'a'*i
return " ".join(convert(S)) | [
"def",
"toGoatLatin",
"(",
"self",
",",
"S",
")",
":",
"def",
"convert",
"(",
"S",
")",
":",
"vowel",
"=",
"set",
"(",
"'aeiouAEIOU'",
")",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"S",
".",
"split",
"(",
")",
",",
"1",
")",
":",
"if",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/goat-latin.py#L8-L19 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/io/loader.py | python | read_Vector_raw | (text) | return [float(v) for v in items] | Reads a vector from a raw string 'v1 ... vn | Reads a vector from a raw string 'v1 ... vn | [
"Reads",
"a",
"vector",
"from",
"a",
"raw",
"string",
"v1",
"...",
"vn"
] | def read_Vector_raw(text):
"""Reads a vector from a raw string 'v1 ... vn'"""
items = text.split()
return [float(v) for v in items] | [
"def",
"read_Vector_raw",
"(",
"text",
")",
":",
"items",
"=",
"text",
".",
"split",
"(",
")",
"return",
"[",
"float",
"(",
"v",
")",
"for",
"v",
"in",
"items",
"]"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/io/loader.py#L171-L174 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/functional/external.py | python | cambricon_runtime_opr | (inputs, data, symbol, tensor_dim_mutable) | return apply(op, *inputs) | r"""Load a serialized Cambricon model as a runtime operator in MegEngine.
Args:
inputs: list of input tensors.
data: the serialized Cambricon model.
symbol: name of the function in Cambricon model.
tensor_dim_mutable: whether the input tensors' shapes are mutable
in ``cnrtModel_t``. | r"""Load a serialized Cambricon model as a runtime operator in MegEngine. | [
"r",
"Load",
"a",
"serialized",
"Cambricon",
"model",
"as",
"a",
"runtime",
"operator",
"in",
"MegEngine",
"."
] | def cambricon_runtime_opr(inputs, data, symbol, tensor_dim_mutable):
r"""Load a serialized Cambricon model as a runtime operator in MegEngine.
Args:
inputs: list of input tensors.
data: the serialized Cambricon model.
symbol: name of the function in Cambricon model.
tensor_dim_mutable: whether the input tensors' shapes are mutable
in ``cnrtModel_t``.
"""
op = builtin.CambriconRuntime(data, len(data), symbol, tensor_dim_mutable)
return apply(op, *inputs) | [
"def",
"cambricon_runtime_opr",
"(",
"inputs",
",",
"data",
",",
"symbol",
",",
"tensor_dim_mutable",
")",
":",
"op",
"=",
"builtin",
".",
"CambriconRuntime",
"(",
"data",
",",
"len",
"(",
"data",
")",
",",
"symbol",
",",
"tensor_dim_mutable",
")",
"return",... | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/external.py#L44-L56 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/appdirs.py | python | user_data_dir | (appname, roaming=False) | return path | r"""
Return full path to the user-specific data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user data directories are:
macOS: ~/Library/Application Support/<AppName>
if it exists, else ~/.config/<AppName>
Unix: ~/.local/share/<AppName> # or in
$XDG_DATA_HOME, if defined
Win XP (not roaming): C:\Documents and Settings\<username>\ ...
...Application Data\<AppName>
Win XP (roaming): C:\Documents and Settings\<username>\Local ...
...Settings\Application Data\<AppName>
Win 7 (not roaming): C:\\Users\<username>\AppData\Local\<AppName>
Win 7 (roaming): C:\\Users\<username>\AppData\Roaming\<AppName>
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
That means, by default "~/.local/share/<AppName>". | r"""
Return full path to the user-specific data dir for this application. | [
"r",
"Return",
"full",
"path",
"to",
"the",
"user",
"-",
"specific",
"data",
"dir",
"for",
"this",
"application",
"."
] | def user_data_dir(appname, roaming=False):
# type: (str, bool) -> str
r"""
Return full path to the user-specific data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user data directories are:
macOS: ~/Library/Application Support/<AppName>
if it exists, else ~/.config/<AppName>
Unix: ~/.local/share/<AppName> # or in
$XDG_DATA_HOME, if defined
Win XP (not roaming): C:\Documents and Settings\<username>\ ...
...Application Data\<AppName>
Win XP (roaming): C:\Documents and Settings\<username>\Local ...
...Settings\Application Data\<AppName>
Win 7 (not roaming): C:\\Users\<username>\AppData\Local\<AppName>
Win 7 (roaming): C:\\Users\<username>\AppData\Roaming\<AppName>
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
That means, by default "~/.local/share/<AppName>".
"""
if WINDOWS:
const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
path = os.path.join(os.path.normpath(_get_win_folder(const)), appname)
elif sys.platform == "darwin":
path = os.path.join(
expanduser('~/Library/Application Support/'),
appname,
) if os.path.isdir(os.path.join(
expanduser('~/Library/Application Support/'),
appname,
)
) else os.path.join(
expanduser('~/.config/'),
appname,
)
else:
path = os.path.join(
os.getenv('XDG_DATA_HOME', expanduser("~/.local/share")),
appname,
)
return path | [
"def",
"user_data_dir",
"(",
"appname",
",",
"roaming",
"=",
"False",
")",
":",
"# type: (str, bool) -> str",
"if",
"WINDOWS",
":",
"const",
"=",
"roaming",
"and",
"\"CSIDL_APPDATA\"",
"or",
"\"CSIDL_LOCAL_APPDATA\"",
"path",
"=",
"os",
".",
"path",
".",
"join",... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/appdirs.py#L70-L120 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/optimize/_basinhopping.py | python | basinhopping | (func, x0, niter=100, T=1.0, stepsize=0.5,
minimizer_kwargs=None, take_step=None, accept_test=None,
callback=None, interval=50, disp=False, niter_success=None,
seed=None) | return res | Find the global minimum of a function using the basin-hopping algorithm
Parameters
----------
func : callable ``f(x, *args)``
Function to be optimized. ``args`` can be passed as an optional item
in the dict ``minimizer_kwargs``
x0 : ndarray
Initial guess.
niter : integer, optional
The number of basin hopping iterations
T : float, optional
The "temperature" parameter for the accept or reject criterion. Higher
"temperatures" mean that larger jumps in function value will be
accepted. For best results ``T`` should be comparable to the
separation
(in function value) between local minima.
stepsize : float, optional
initial step size for use in the random displacement.
minimizer_kwargs : dict, optional
Extra keyword arguments to be passed to the minimizer
``scipy.optimize.minimize()`` Some important options could be:
method : str
The minimization method (e.g. ``"L-BFGS-B"``)
args : tuple
Extra arguments passed to the objective function (``func``) and
its derivatives (Jacobian, Hessian).
take_step : callable ``take_step(x)``, optional
Replace the default step taking routine with this routine. The default
step taking routine is a random displacement of the coordinates, but
other step taking algorithms may be better for some systems.
``take_step`` can optionally have the attribute ``take_step.stepsize``.
If this attribute exists, then ``basinhopping`` will adjust
``take_step.stepsize`` in order to try to optimize the global minimum
search.
accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional
Define a test which will be used to judge whether or not to accept the
step. This will be used in addition to the Metropolis test based on
"temperature" ``T``. The acceptable return values are True,
False, or ``"force accept"``. If any of the tests return False
then the step is rejected. If the latter, then this will override any
other tests in order to accept the step. This can be used, for example,
to forcefully escape from a local minimum that ``basinhopping`` is
trapped in.
callback : callable, ``callback(x, f, accept)``, optional
A callback function which will be called for all minima found. ``x``
and ``f`` are the coordinates and function value of the trial minimum,
and ``accept`` is whether or not that minimum was accepted. This can be
used, for example, to save the lowest N minima found. Also,
``callback`` can be used to specify a user defined stop criterion by
optionally returning True to stop the ``basinhopping`` routine.
interval : integer, optional
interval for how often to update the ``stepsize``
disp : bool, optional
Set to True to print status messages
niter_success : integer, optional
Stop the run if the global minimum candidate remains the same for this
number of iterations.
seed : int or `np.random.RandomState`, optional
If `seed` is not specified the `np.RandomState` singleton is used.
If `seed` is an int, a new `np.random.RandomState` instance is used,
seeded with seed.
If `seed` is already a `np.random.RandomState instance`, then that
`np.random.RandomState` instance is used.
Specify `seed` for repeatable minimizations. The random numbers
generated with this seed only affect the default Metropolis
`accept_test` and the default `take_step`. If you supply your own
`take_step` and `accept_test`, and these functions use random
number generation, then those functions are responsible for the state
of their random number generator.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object. Important
attributes are: ``x`` the solution array, ``fun`` the value of the
function at the solution, and ``message`` which describes the cause of
the termination. The ``OptimzeResult`` object returned by the selected
minimizer at the lowest minimum is also contained within this object
and can be accessed through the ``lowest_optimization_result`` attribute.
See `OptimizeResult` for a description of other attributes.
See Also
--------
minimize :
The local minimization function called once for each basinhopping step.
``minimizer_kwargs`` is passed to this routine.
Notes
-----
Basin-hopping is a stochastic algorithm which attempts to find the global
minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
[4]_. The algorithm in its current form was described by David Wales and
Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.
The algorithm is iterative with each cycle composed of the following
features
1) random perturbation of the coordinates
2) local minimization
3) accept or reject the new coordinates based on the minimized function
value
The acceptance test used here is the Metropolis criterion of standard Monte
Carlo algorithms, although there are many other possibilities [3]_.
This global minimization method has been shown to be extremely efficient
for a wide variety of problems in physics and chemistry. It is
particularly useful when the function has many minima separated by large
barriers. See the Cambridge Cluster Database
http://www-wales.ch.cam.ac.uk/CCD.html for databases of molecular systems
that have been optimized primarily using basin-hopping. This database
includes minimization problems exceeding 300 degrees of freedom.
See the free software program GMIN (http://www-wales.ch.cam.ac.uk/GMIN) for
a Fortran implementation of basin-hopping. This implementation has many
different variations of the procedure described above, including more
advanced step taking algorithms and alternate acceptance criterion.
For stochastic global optimization there is no way to determine if the true
global minimum has actually been found. Instead, as a consistency check,
the algorithm can be run from a number of different random starting points
to ensure the lowest minimum found in each example has converged to the
global minimum. For this reason ``basinhopping`` will by default simply
run for the number of iterations ``niter`` and return the lowest minimum
found. It is left to the user to ensure that this is in fact the global
minimum.
Choosing ``stepsize``: This is a crucial parameter in ``basinhopping`` and
depends on the problem being solved. Ideally it should be comparable to
the typical separation between local minima of the function being
optimized. ``basinhopping`` will, by default, adjust ``stepsize`` to find
an optimal value, but this may take many iterations. You will get quicker
results if you set a sensible value for ``stepsize``.
Choosing ``T``: The parameter ``T`` is the temperature used in the
metropolis criterion. Basinhopping steps are accepted with probability
``1`` if ``func(xnew) < func(xold)``, or otherwise with probability::
exp( -(func(xnew) - func(xold)) / T )
So, for best results, ``T`` should to be comparable to the typical
difference in function values between local minima.
.. versionadded:: 0.12.0
References
----------
.. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
Cambridge, UK.
.. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111.
.. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
1987, 84, 6611.
.. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
crystals, and biomolecules, Science, 1999, 285, 1368.
Examples
--------
The following example is a one-dimensional minimization problem, with many
local minima superimposed on a parabola.
>>> from scipy.optimize import basinhopping
>>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
>>> x0=[1.]
Basinhopping, internally, uses a local minimization algorithm. We will use
the parameter ``minimizer_kwargs`` to tell basinhopping which algorithm to
use and how to set up that minimizer. This parameter will be passed to
``scipy.optimize.minimize()``.
>>> minimizer_kwargs = {"method": "BFGS"}
>>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
... niter=200)
>>> print("global minimum: x = %.4f, f(x0) = %.4f" % (ret.x, ret.fun))
global minimum: x = -0.1951, f(x0) = -1.0009
Next consider a two-dimensional minimization problem. Also, this time we
will use gradient information to significantly speed up the search.
>>> def func2d(x):
... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
... 0.2) * x[0]
... df = np.zeros(2)
... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
... df[1] = 2. * x[1] + 0.2
... return f, df
We'll also use a different local minimization algorithm. Also we must tell
the minimizer that our function returns both energy and gradient (jacobian)
>>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
>>> x0 = [1.0, 1.0]
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=200)
>>> print("global minimum: x = [%.4f, %.4f], f(x0) = %.4f" % (ret.x[0],
... ret.x[1],
... ret.fun))
global minimum: x = [-0.1951, -0.1000], f(x0) = -1.0109
Here is an example using a custom step taking routine. Imagine you want
the first coordinate to take larger steps then the rest of the coordinates.
This can be implemented like so:
>>> class MyTakeStep(object):
... def __init__(self, stepsize=0.5):
... self.stepsize = stepsize
... def __call__(self, x):
... s = self.stepsize
... x[0] += np.random.uniform(-2.*s, 2.*s)
... x[1:] += np.random.uniform(-s, s, x[1:].shape)
... return x
Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
of ``stepsize`` to optimize the search. We'll use the same 2-D function as
before
>>> mytakestep = MyTakeStep()
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=200, take_step=mytakestep)
>>> print("global minimum: x = [%.4f, %.4f], f(x0) = %.4f" % (ret.x[0],
... ret.x[1],
... ret.fun))
global minimum: x = [-0.1951, -0.1000], f(x0) = -1.0109
Now let's do an example using a custom callback function which prints the
value of every minimum found
>>> def print_fun(x, f, accepted):
... print("at minimum %.4f accepted %d" % (f, int(accepted)))
We'll run it for only 10 basinhopping steps this time.
>>> np.random.seed(1)
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=10, callback=print_fun)
at minimum 0.4159 accepted 1
at minimum -0.9073 accepted 1
at minimum -0.1021 accepted 1
at minimum -0.1021 accepted 1
at minimum 0.9102 accepted 1
at minimum 0.9102 accepted 1
at minimum 2.2945 accepted 0
at minimum -0.1021 accepted 1
at minimum -1.0109 accepted 1
at minimum -1.0109 accepted 1
The minimum at -1.0109 is actually the global minimum, found already on the
8th iteration.
Now let's implement bounds on the problem using a custom ``accept_test``:
>>> class MyBounds(object):
... def __init__(self, xmax=[1.1,1.1], xmin=[-1.1,-1.1] ):
... self.xmax = np.array(xmax)
... self.xmin = np.array(xmin)
... def __call__(self, **kwargs):
... x = kwargs["x_new"]
... tmax = bool(np.all(x <= self.xmax))
... tmin = bool(np.all(x >= self.xmin))
... return tmax and tmin
>>> mybounds = MyBounds()
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=10, accept_test=mybounds) | Find the global minimum of a function using the basin-hopping algorithm | [
"Find",
"the",
"global",
"minimum",
"of",
"a",
"function",
"using",
"the",
"basin",
"-",
"hopping",
"algorithm"
] | def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5,
minimizer_kwargs=None, take_step=None, accept_test=None,
callback=None, interval=50, disp=False, niter_success=None,
seed=None):
"""
Find the global minimum of a function using the basin-hopping algorithm
Parameters
----------
func : callable ``f(x, *args)``
Function to be optimized. ``args`` can be passed as an optional item
in the dict ``minimizer_kwargs``
x0 : ndarray
Initial guess.
niter : integer, optional
The number of basin hopping iterations
T : float, optional
The "temperature" parameter for the accept or reject criterion. Higher
"temperatures" mean that larger jumps in function value will be
accepted. For best results ``T`` should be comparable to the
separation
(in function value) between local minima.
stepsize : float, optional
initial step size for use in the random displacement.
minimizer_kwargs : dict, optional
Extra keyword arguments to be passed to the minimizer
``scipy.optimize.minimize()`` Some important options could be:
method : str
The minimization method (e.g. ``"L-BFGS-B"``)
args : tuple
Extra arguments passed to the objective function (``func``) and
its derivatives (Jacobian, Hessian).
take_step : callable ``take_step(x)``, optional
Replace the default step taking routine with this routine. The default
step taking routine is a random displacement of the coordinates, but
other step taking algorithms may be better for some systems.
``take_step`` can optionally have the attribute ``take_step.stepsize``.
If this attribute exists, then ``basinhopping`` will adjust
``take_step.stepsize`` in order to try to optimize the global minimum
search.
accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional
Define a test which will be used to judge whether or not to accept the
step. This will be used in addition to the Metropolis test based on
"temperature" ``T``. The acceptable return values are True,
False, or ``"force accept"``. If any of the tests return False
then the step is rejected. If the latter, then this will override any
other tests in order to accept the step. This can be used, for example,
to forcefully escape from a local minimum that ``basinhopping`` is
trapped in.
callback : callable, ``callback(x, f, accept)``, optional
A callback function which will be called for all minima found. ``x``
and ``f`` are the coordinates and function value of the trial minimum,
and ``accept`` is whether or not that minimum was accepted. This can be
used, for example, to save the lowest N minima found. Also,
``callback`` can be used to specify a user defined stop criterion by
optionally returning True to stop the ``basinhopping`` routine.
interval : integer, optional
interval for how often to update the ``stepsize``
disp : bool, optional
Set to True to print status messages
niter_success : integer, optional
Stop the run if the global minimum candidate remains the same for this
number of iterations.
seed : int or `np.random.RandomState`, optional
If `seed` is not specified the `np.RandomState` singleton is used.
If `seed` is an int, a new `np.random.RandomState` instance is used,
seeded with seed.
If `seed` is already a `np.random.RandomState instance`, then that
`np.random.RandomState` instance is used.
Specify `seed` for repeatable minimizations. The random numbers
generated with this seed only affect the default Metropolis
`accept_test` and the default `take_step`. If you supply your own
`take_step` and `accept_test`, and these functions use random
number generation, then those functions are responsible for the state
of their random number generator.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object. Important
attributes are: ``x`` the solution array, ``fun`` the value of the
function at the solution, and ``message`` which describes the cause of
the termination. The ``OptimzeResult`` object returned by the selected
minimizer at the lowest minimum is also contained within this object
and can be accessed through the ``lowest_optimization_result`` attribute.
See `OptimizeResult` for a description of other attributes.
See Also
--------
minimize :
The local minimization function called once for each basinhopping step.
``minimizer_kwargs`` is passed to this routine.
Notes
-----
Basin-hopping is a stochastic algorithm which attempts to find the global
minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
[4]_. The algorithm in its current form was described by David Wales and
Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.
The algorithm is iterative with each cycle composed of the following
features
1) random perturbation of the coordinates
2) local minimization
3) accept or reject the new coordinates based on the minimized function
value
The acceptance test used here is the Metropolis criterion of standard Monte
Carlo algorithms, although there are many other possibilities [3]_.
This global minimization method has been shown to be extremely efficient
for a wide variety of problems in physics and chemistry. It is
particularly useful when the function has many minima separated by large
barriers. See the Cambridge Cluster Database
http://www-wales.ch.cam.ac.uk/CCD.html for databases of molecular systems
that have been optimized primarily using basin-hopping. This database
includes minimization problems exceeding 300 degrees of freedom.
See the free software program GMIN (http://www-wales.ch.cam.ac.uk/GMIN) for
a Fortran implementation of basin-hopping. This implementation has many
different variations of the procedure described above, including more
advanced step taking algorithms and alternate acceptance criterion.
For stochastic global optimization there is no way to determine if the true
global minimum has actually been found. Instead, as a consistency check,
the algorithm can be run from a number of different random starting points
to ensure the lowest minimum found in each example has converged to the
global minimum. For this reason ``basinhopping`` will by default simply
run for the number of iterations ``niter`` and return the lowest minimum
found. It is left to the user to ensure that this is in fact the global
minimum.
Choosing ``stepsize``: This is a crucial parameter in ``basinhopping`` and
depends on the problem being solved. Ideally it should be comparable to
the typical separation between local minima of the function being
optimized. ``basinhopping`` will, by default, adjust ``stepsize`` to find
an optimal value, but this may take many iterations. You will get quicker
results if you set a sensible value for ``stepsize``.
Choosing ``T``: The parameter ``T`` is the temperature used in the
metropolis criterion. Basinhopping steps are accepted with probability
``1`` if ``func(xnew) < func(xold)``, or otherwise with probability::
exp( -(func(xnew) - func(xold)) / T )
So, for best results, ``T`` should to be comparable to the typical
difference in function values between local minima.
.. versionadded:: 0.12.0
References
----------
.. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
Cambridge, UK.
.. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111.
.. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
1987, 84, 6611.
.. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
crystals, and biomolecules, Science, 1999, 285, 1368.
Examples
--------
The following example is a one-dimensional minimization problem, with many
local minima superimposed on a parabola.
>>> from scipy.optimize import basinhopping
>>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
>>> x0=[1.]
Basinhopping, internally, uses a local minimization algorithm. We will use
the parameter ``minimizer_kwargs`` to tell basinhopping which algorithm to
use and how to set up that minimizer. This parameter will be passed to
``scipy.optimize.minimize()``.
>>> minimizer_kwargs = {"method": "BFGS"}
>>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
... niter=200)
>>> print("global minimum: x = %.4f, f(x0) = %.4f" % (ret.x, ret.fun))
global minimum: x = -0.1951, f(x0) = -1.0009
Next consider a two-dimensional minimization problem. Also, this time we
will use gradient information to significantly speed up the search.
>>> def func2d(x):
... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
... 0.2) * x[0]
... df = np.zeros(2)
... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
... df[1] = 2. * x[1] + 0.2
... return f, df
We'll also use a different local minimization algorithm. Also we must tell
the minimizer that our function returns both energy and gradient (jacobian)
>>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
>>> x0 = [1.0, 1.0]
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=200)
>>> print("global minimum: x = [%.4f, %.4f], f(x0) = %.4f" % (ret.x[0],
... ret.x[1],
... ret.fun))
global minimum: x = [-0.1951, -0.1000], f(x0) = -1.0109
Here is an example using a custom step taking routine. Imagine you want
the first coordinate to take larger steps then the rest of the coordinates.
This can be implemented like so:
>>> class MyTakeStep(object):
... def __init__(self, stepsize=0.5):
... self.stepsize = stepsize
... def __call__(self, x):
... s = self.stepsize
... x[0] += np.random.uniform(-2.*s, 2.*s)
... x[1:] += np.random.uniform(-s, s, x[1:].shape)
... return x
Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
of ``stepsize`` to optimize the search. We'll use the same 2-D function as
before
>>> mytakestep = MyTakeStep()
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=200, take_step=mytakestep)
>>> print("global minimum: x = [%.4f, %.4f], f(x0) = %.4f" % (ret.x[0],
... ret.x[1],
... ret.fun))
global minimum: x = [-0.1951, -0.1000], f(x0) = -1.0109
Now let's do an example using a custom callback function which prints the
value of every minimum found
>>> def print_fun(x, f, accepted):
... print("at minimum %.4f accepted %d" % (f, int(accepted)))
We'll run it for only 10 basinhopping steps this time.
>>> np.random.seed(1)
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=10, callback=print_fun)
at minimum 0.4159 accepted 1
at minimum -0.9073 accepted 1
at minimum -0.1021 accepted 1
at minimum -0.1021 accepted 1
at minimum 0.9102 accepted 1
at minimum 0.9102 accepted 1
at minimum 2.2945 accepted 0
at minimum -0.1021 accepted 1
at minimum -1.0109 accepted 1
at minimum -1.0109 accepted 1
The minimum at -1.0109 is actually the global minimum, found already on the
8th iteration.
Now let's implement bounds on the problem using a custom ``accept_test``:
>>> class MyBounds(object):
... def __init__(self, xmax=[1.1,1.1], xmin=[-1.1,-1.1] ):
... self.xmax = np.array(xmax)
... self.xmin = np.array(xmin)
... def __call__(self, **kwargs):
... x = kwargs["x_new"]
... tmax = bool(np.all(x <= self.xmax))
... tmin = bool(np.all(x >= self.xmin))
... return tmax and tmin
>>> mybounds = MyBounds()
>>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
... niter=10, accept_test=mybounds)
"""
x0 = np.array(x0)
# set up the np.random.RandomState generator
rng = check_random_state(seed)
# set up minimizer
if minimizer_kwargs is None:
minimizer_kwargs = dict()
wrapped_minimizer = MinimizerWrapper(scipy.optimize.minimize, func,
**minimizer_kwargs)
# set up step taking algorithm
if take_step is not None:
if not isinstance(take_step, collections.Callable):
raise TypeError("take_step must be callable")
# if take_step.stepsize exists then use AdaptiveStepsize to control
# take_step.stepsize
if hasattr(take_step, "stepsize"):
take_step_wrapped = AdaptiveStepsize(take_step, interval=interval,
verbose=disp)
else:
take_step_wrapped = take_step
else:
# use default
displace = RandomDisplacement(stepsize=stepsize, random_state=rng)
take_step_wrapped = AdaptiveStepsize(displace, interval=interval,
verbose=disp)
# set up accept tests
if accept_test is not None:
if not isinstance(accept_test, collections.Callable):
raise TypeError("accept_test must be callable")
accept_tests = [accept_test]
else:
accept_tests = []
# use default
metropolis = Metropolis(T, random_state=rng)
accept_tests.append(metropolis)
if niter_success is None:
niter_success = niter + 2
bh = BasinHoppingRunner(x0, wrapped_minimizer, take_step_wrapped,
accept_tests, disp=disp)
# start main iteration loop
count, i = 0, 0
message = ["requested number of basinhopping iterations completed"
" successfully"]
for i in range(niter):
new_global_min = bh.one_cycle()
if isinstance(callback, collections.Callable):
# should we pass a copy of x?
val = callback(bh.xtrial, bh.energy_trial, bh.accept)
if val is not None:
if val:
message = ["callback function requested stop early by"
"returning True"]
break
count += 1
if new_global_min:
count = 0
elif count > niter_success:
message = ["success condition satisfied"]
break
# prepare return object
res = bh.res
res.lowest_optimization_result = bh.storage.get_lowest()
res.x = np.copy(res.lowest_optimization_result.x)
res.fun = res.lowest_optimization_result.fun
res.message = message
res.nit = i + 1
return res | [
"def",
"basinhopping",
"(",
"func",
",",
"x0",
",",
"niter",
"=",
"100",
",",
"T",
"=",
"1.0",
",",
"stepsize",
"=",
"0.5",
",",
"minimizer_kwargs",
"=",
"None",
",",
"take_step",
"=",
"None",
",",
"accept_test",
"=",
"None",
",",
"callback",
"=",
"N... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/_basinhopping.py#L311-L667 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/msvs_emulation.py | python | GenerateEnvironmentFiles | (toplevel_build_dir, generator_flags,
system_includes, open_out) | return cl_paths | It's not sufficient to have the absolute path to the compiler, linker,
etc. on Windows, as those tools rely on .dlls being in the PATH. We also
need to support both x86 and x64 compilers within the same build (to support
msvs_target_platform hackery). Different architectures require a different
compiler binary, and different supporting environment variables (INCLUDE,
LIB, LIBPATH). So, we extract the environment here, wrap all invocations
of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which
sets up the environment, and then we do not prefix the compiler with
an absolute path, instead preferring something like "cl.exe" in the rule
which will then run whichever the environment setup has put in the path.
When the following procedure to generate environment files does not
meet your requirement (e.g. for custom toolchains), you can pass
"-G ninja_use_custom_environment_files" to the gyp to suppress file
generation and use custom environment files prepared by yourself. | It's not sufficient to have the absolute path to the compiler, linker,
etc. on Windows, as those tools rely on .dlls being in the PATH. We also
need to support both x86 and x64 compilers within the same build (to support
msvs_target_platform hackery). Different architectures require a different
compiler binary, and different supporting environment variables (INCLUDE,
LIB, LIBPATH). So, we extract the environment here, wrap all invocations
of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which
sets up the environment, and then we do not prefix the compiler with
an absolute path, instead preferring something like "cl.exe" in the rule
which will then run whichever the environment setup has put in the path.
When the following procedure to generate environment files does not
meet your requirement (e.g. for custom toolchains), you can pass
"-G ninja_use_custom_environment_files" to the gyp to suppress file
generation and use custom environment files prepared by yourself. | [
"It",
"s",
"not",
"sufficient",
"to",
"have",
"the",
"absolute",
"path",
"to",
"the",
"compiler",
"linker",
"etc",
".",
"on",
"Windows",
"as",
"those",
"tools",
"rely",
"on",
".",
"dlls",
"being",
"in",
"the",
"PATH",
".",
"We",
"also",
"need",
"to",
... | def GenerateEnvironmentFiles(toplevel_build_dir, generator_flags,
system_includes, open_out):
"""It's not sufficient to have the absolute path to the compiler, linker,
etc. on Windows, as those tools rely on .dlls being in the PATH. We also
need to support both x86 and x64 compilers within the same build (to support
msvs_target_platform hackery). Different architectures require a different
compiler binary, and different supporting environment variables (INCLUDE,
LIB, LIBPATH). So, we extract the environment here, wrap all invocations
of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which
sets up the environment, and then we do not prefix the compiler with
an absolute path, instead preferring something like "cl.exe" in the rule
which will then run whichever the environment setup has put in the path.
When the following procedure to generate environment files does not
meet your requirement (e.g. for custom toolchains), you can pass
"-G ninja_use_custom_environment_files" to the gyp to suppress file
generation and use custom environment files prepared by yourself."""
archs = ('x86', 'x64')
if generator_flags.get('ninja_use_custom_environment_files', 0):
cl_paths = {}
for arch in archs:
cl_paths[arch] = 'cl.exe'
return cl_paths
vs = GetVSVersion(generator_flags)
cl_paths = {}
for arch in archs:
# Extract environment variables for subprocesses.
args = vs.SetupScript(arch)
args.extend(('&&', 'set'))
popen = subprocess.Popen(
args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
variables, _ = popen.communicate()
if PY3:
variables = variables.decode('utf-8')
if popen.returncode != 0:
raise Exception('"%s" failed with error %d' % (args, popen.returncode))
env = _ExtractImportantEnvironment(variables)
# Inject system includes from gyp files into INCLUDE.
if system_includes:
system_includes = system_includes | OrderedSet(
env.get('INCLUDE', '').split(';'))
env['INCLUDE'] = ';'.join(system_includes)
env_block = _FormatAsEnvironmentBlock(env)
f = open_out(os.path.join(toplevel_build_dir, 'environment.' + arch), 'wb')
f.write(env_block)
f.close()
# Find cl.exe location for this architecture.
args = vs.SetupScript(arch)
args.extend(('&&',
'for', '%i', 'in', '(cl.exe)', 'do', '@echo', 'LOC:%~$PATH:i'))
popen = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
output, _ = popen.communicate()
if PY3:
output = output.decode('utf-8')
cl_paths[arch] = _ExtractCLPath(output)
return cl_paths | [
"def",
"GenerateEnvironmentFiles",
"(",
"toplevel_build_dir",
",",
"generator_flags",
",",
"system_includes",
",",
"open_out",
")",
":",
"archs",
"=",
"(",
"'x86'",
",",
"'x64'",
")",
"if",
"generator_flags",
".",
"get",
"(",
"'ninja_use_custom_environment_files'",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/msvs_emulation.py#L1030-L1087 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/image/detection.py | python | DetRandomPadAug.__call__ | (self, src, label) | return (src, label) | Augmenter body | Augmenter body | [
"Augmenter",
"body"
] | def __call__(self, src, label):
"""Augmenter body"""
height, width, _ = src.shape
pad = self._random_pad_proposal(label, height, width)
if pad:
x, y, w, h, label = pad
src = copyMakeBorder(src, y, h-y-height, x, w-x-width, 16, values=self.pad_val)
return (src, label) | [
"def",
"__call__",
"(",
"self",
",",
"src",
",",
"label",
")",
":",
"height",
",",
"width",
",",
"_",
"=",
"src",
".",
"shape",
"pad",
"=",
"self",
".",
"_random_pad_proposal",
"(",
"label",
",",
"height",
",",
"width",
")",
"if",
"pad",
":",
"x",
... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/image/detection.py#L369-L376 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/xml_fix.py | python | _Replacement_write_data | (writer, data, is_attrib=False) | Writes datachars to writer. | Writes datachars to writer. | [
"Writes",
"datachars",
"to",
"writer",
"."
] | def _Replacement_write_data(writer, data, is_attrib=False):
"""Writes datachars to writer."""
data = data.replace("&", "&").replace("<", "<")
data = data.replace("\"", """).replace(">", ">")
if is_attrib:
data = data.replace(
"\r", "
").replace(
"\n", "
").replace(
"\t", "	")
writer.write(data) | [
"def",
"_Replacement_write_data",
"(",
"writer",
",",
"data",
",",
"is_attrib",
"=",
"False",
")",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
".",
"replace",
"(",
"\"<\"",
",",
"\"<\"",
")",
"data",
"=",
"data",
"... | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/xml_fix.py#L16-L25 | ||
Evolving-AI-Lab/fooling | 66f097dd6bd2eb6794ade3e187a7adfdf1887688 | caffe/scripts/cpp_lint.py | python | GetHeaderGuardCPPVariable | (filename) | return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' | Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file. | Returns the CPP variable that should be used as a header guard. | [
"Returns",
"the",
"CPP",
"variable",
"that",
"should",
"be",
"used",
"as",
"a",
"header",
"guard",
"."
] | def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
if _root:
file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' | [
"def",
"GetHeaderGuardCPPVariable",
"(",
"filename",
")",
":",
"# Restores original filename in case that cpplint is invoked from Emacs's",
"# flymake.",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.h$'",
",",
"'.h'",
",",
"filename",
")",
"filename",
"=",
"re",
... | https://github.com/Evolving-AI-Lab/fooling/blob/66f097dd6bd2eb6794ade3e187a7adfdf1887688/caffe/scripts/cpp_lint.py#L1384-L1405 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/image_ops.py | python | random_brightness | (image, max_delta, seed=None) | return adjust_brightness(image, delta) | Adjust the brightness of images by a random factor.
Equivalent to `adjust_brightness()` using a `delta` randomly picked in the
interval `[-max_delta, max_delta)`.
Args:
image: An image.
max_delta: float, must be non-negative.
seed: A Python integer. Used to create a random seed. See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
Returns:
The brightness-adjusted image.
Raises:
ValueError: if `max_delta` is negative. | Adjust the brightness of images by a random factor. | [
"Adjust",
"the",
"brightness",
"of",
"images",
"by",
"a",
"random",
"factor",
"."
] | def random_brightness(image, max_delta, seed=None):
"""Adjust the brightness of images by a random factor.
Equivalent to `adjust_brightness()` using a `delta` randomly picked in the
interval `[-max_delta, max_delta)`.
Args:
image: An image.
max_delta: float, must be non-negative.
seed: A Python integer. Used to create a random seed. See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
Returns:
The brightness-adjusted image.
Raises:
ValueError: if `max_delta` is negative.
"""
if max_delta < 0:
raise ValueError('max_delta must be non-negative.')
delta = random_ops.random_uniform([], -max_delta, max_delta, seed=seed)
return adjust_brightness(image, delta) | [
"def",
"random_brightness",
"(",
"image",
",",
"max_delta",
",",
"seed",
"=",
"None",
")",
":",
"if",
"max_delta",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'max_delta must be non-negative.'",
")",
"delta",
"=",
"random_ops",
".",
"random_uniform",
"(",
"[",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/image_ops.py#L876-L899 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/tcpros_pubsub.py | python | TCPROSHandler.set_tcp_nodelay | (self, resolved_name, tcp_nodelay) | @param resolved_name: resolved topic name
@type resolved_name: str
@param tcp_nodelay: If True, sets TCP_NODELAY on publisher's
socket (disables Nagle algorithm). This results in lower
latency publishing at the cost of efficiency.
@type tcp_nodelay: bool | @param resolved_name: resolved topic name
@type resolved_name: str | [
"@param",
"resolved_name",
":",
"resolved",
"topic",
"name",
"@type",
"resolved_name",
":",
"str"
] | def set_tcp_nodelay(self, resolved_name, tcp_nodelay):
"""
@param resolved_name: resolved topic name
@type resolved_name: str
@param tcp_nodelay: If True, sets TCP_NODELAY on publisher's
socket (disables Nagle algorithm). This results in lower
latency publishing at the cost of efficiency.
@type tcp_nodelay: bool
"""
self.tcp_nodelay_map[resolved_name] = tcp_nodelay | [
"def",
"set_tcp_nodelay",
"(",
"self",
",",
"resolved_name",
",",
"tcp_nodelay",
")",
":",
"self",
".",
"tcp_nodelay_map",
"[",
"resolved_name",
"]",
"=",
"tcp_nodelay"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_pubsub.py#L210-L220 | ||
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | platforms/nuttx/NuttX/tools/kconfiglib.py | python | Kconfig.load_config | (self, filename=None, replace=True, verbose=True) | return loaded_existing | Loads symbol values from a file in the .config format. Equivalent to
calling Symbol.set_value() to set each of the values.
"# CONFIG_FOO is not set" within a .config file sets the user value of
FOO to n. The C tools work the same way.
For each symbol, the Symbol.user_value attribute holds the value the
symbol was assigned in the .config file (if any). The user value might
differ from Symbol.str/tri_value if there are unsatisfied dependencies.
Calling this function also updates the Kconfig.missing_syms attribute
with a list of all assignments to undefined symbols within the
configuration file. Kconfig.missing_syms is cleared if 'replace' is
True, and appended to otherwise. See the documentation for
Kconfig.missing_syms as well.
Raises (possibly a subclass of) IOError on IO errors ('errno',
'strerror', and 'filename' are available). Note that IOError can be
caught as OSError on Python 3.
filename (default: None):
Path to load configuration from (a string). Respects $srctree if set
(see the class documentation).
If 'filename' is None (the default), the configuration file to load
(if any) is calculated automatically, giving the behavior you'd
usually want:
1. If the KCONFIG_CONFIG environment variable is set, it gives the
path to the configuration file to load. Otherwise, ".config" is
used. See standard_config_filename().
2. If the path from (1.) doesn't exist, the configuration file
given by kconf.defconfig_filename is loaded instead, which is
derived from the 'option defconfig_list' symbol.
3. If (1.) and (2.) fail to find a configuration file to load, no
configuration file is loaded, and symbols retain their current
values (e.g., their default values). This is not an error.
See the return value as well.
replace (default: True):
If True, all existing user values will be cleared before loading the
.config. Pass False to merge configurations.
verbose (default: True):
If True and filename is None (automatically infer configuration
file), a message will be printed to stdout telling which file got
loaded (or that no file got loaded). This is meant to reduce
boilerplate in tools.
Returns True if an existing configuration was loaded (that didn't come
from the 'option defconfig_list' symbol), and False otherwise. This is
mostly useful in conjunction with filename=None, as True will always be
returned otherwise. | Loads symbol values from a file in the .config format. Equivalent to
calling Symbol.set_value() to set each of the values. | [
"Loads",
"symbol",
"values",
"from",
"a",
"file",
"in",
"the",
".",
"config",
"format",
".",
"Equivalent",
"to",
"calling",
"Symbol",
".",
"set_value",
"()",
"to",
"set",
"each",
"of",
"the",
"values",
"."
] | def load_config(self, filename=None, replace=True, verbose=True):
"""
Loads symbol values from a file in the .config format. Equivalent to
calling Symbol.set_value() to set each of the values.
"# CONFIG_FOO is not set" within a .config file sets the user value of
FOO to n. The C tools work the same way.
For each symbol, the Symbol.user_value attribute holds the value the
symbol was assigned in the .config file (if any). The user value might
differ from Symbol.str/tri_value if there are unsatisfied dependencies.
Calling this function also updates the Kconfig.missing_syms attribute
with a list of all assignments to undefined symbols within the
configuration file. Kconfig.missing_syms is cleared if 'replace' is
True, and appended to otherwise. See the documentation for
Kconfig.missing_syms as well.
Raises (possibly a subclass of) IOError on IO errors ('errno',
'strerror', and 'filename' are available). Note that IOError can be
caught as OSError on Python 3.
filename (default: None):
Path to load configuration from (a string). Respects $srctree if set
(see the class documentation).
If 'filename' is None (the default), the configuration file to load
(if any) is calculated automatically, giving the behavior you'd
usually want:
1. If the KCONFIG_CONFIG environment variable is set, it gives the
path to the configuration file to load. Otherwise, ".config" is
used. See standard_config_filename().
2. If the path from (1.) doesn't exist, the configuration file
given by kconf.defconfig_filename is loaded instead, which is
derived from the 'option defconfig_list' symbol.
3. If (1.) and (2.) fail to find a configuration file to load, no
configuration file is loaded, and symbols retain their current
values (e.g., their default values). This is not an error.
See the return value as well.
replace (default: True):
If True, all existing user values will be cleared before loading the
.config. Pass False to merge configurations.
verbose (default: True):
If True and filename is None (automatically infer configuration
file), a message will be printed to stdout telling which file got
loaded (or that no file got loaded). This is meant to reduce
boilerplate in tools.
Returns True if an existing configuration was loaded (that didn't come
from the 'option defconfig_list' symbol), and False otherwise. This is
mostly useful in conjunction with filename=None, as True will always be
returned otherwise.
"""
loaded_existing = True
if filename is None:
filename = standard_config_filename()
if os.path.exists(filename):
if verbose:
print("Using existing configuration '{}' as base"
.format(filename))
else:
filename = self.defconfig_filename
if filename is None:
if verbose:
print("Using default symbol values as base")
return False
if verbose:
print("Using default configuration found in '{}' as "
"base".format(filename))
loaded_existing = False
# Disable the warning about assigning to symbols without prompts. This
# is normal and expected within a .config file.
self._warn_for_no_prompt = False
# This stub only exists to make sure _warn_for_no_prompt gets reenabled
try:
self._load_config(filename, replace)
except UnicodeDecodeError as e:
_decoding_error(e, filename)
finally:
self._warn_for_no_prompt = True
return loaded_existing | [
"def",
"load_config",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"replace",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"loaded_existing",
"=",
"True",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"standard_config_filename",
"(",
")",... | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/platforms/nuttx/NuttX/tools/kconfiglib.py#L1038-L1129 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | EntryPoint.parse_map | (cls, data, dist=None) | return maps | Parse a map of entry point groups | Parse a map of entry point groups | [
"Parse",
"a",
"map",
"of",
"entry",
"point",
"groups"
] | def parse_map(cls, data, dist=None):
"""Parse a map of entry point groups"""
if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for group, lines in data:
if group is None:
if not lines:
continue
raise ValueError("Entry points must be listed in groups")
group = group.strip()
if group in maps:
raise ValueError("Duplicate group name", group)
maps[group] = cls.parse_group(group, lines, dist)
return maps | [
"def",
"parse_map",
"(",
"cls",
",",
"data",
",",
"dist",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"data",
".",
"items",
"(",
")",
"else",
":",
"data",
"=",
"split_sections",
"(",
"data",
")",
"m... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L2520-L2536 | |
s9xie/hed | 94fb22f10cbfec8d84fbc0642b224022014b6bd6 | scripts/cpp_lint.py | python | _SetFilters | (filters) | Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die. | Sets the module's error-message filters. | [
"Sets",
"the",
"module",
"s",
"error",
"-",
"message",
"filters",
"."
] | def _SetFilters(filters):
"""Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.SetFilters(filters) | [
"def",
"_SetFilters",
"(",
"filters",
")",
":",
"_cpplint_state",
".",
"SetFilters",
"(",
"filters",
")"
] | https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/scripts/cpp_lint.py#L797-L807 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/base64.py | python | test | () | Small test program | Small test program | [
"Small",
"test",
"program"
] | def test():
"""Small test program"""
import sys, getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print """usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode
-e: encode (default)
-t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
sys.exit(2)
func = encode
for o, a in opts:
if o == '-e': func = encode
if o == '-d': func = decode
if o == '-u': func = decode
if o == '-t': test1(); return
if args and args[0] != '-':
func(open(args[0], 'rb'), sys.stdout)
else:
func(sys.stdin, sys.stdout) | [
"def",
"test",
"(",
")",
":",
"import",
"sys",
",",
"getopt",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"'deut'",
")",
"except",
"getopt",
".",
"error",
",",
"msg",
":",
"sy... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/base64.py#L326-L348 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/decimal.py | python | Context.remainder_near | (self, a, b) | return a.remainder_near(b, context=self) | Returns to be "a - b * n", where n is the integer nearest the exact
value of "x / b" (if two integers are equally near then the even one
is chosen). If the result is equal to 0 then its sign will be the
sign of a.
This operation will fail under the same conditions as integer division
(that is, if integer division on the same two operands would fail, the
remainder cannot be calculated).
>>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Decimal('-0.9')
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Decimal('-2')
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Decimal('1')
>>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Decimal('-1')
>>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Decimal('0.2')
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Decimal('0.1')
>>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Decimal('-0.3') | Returns to be "a - b * n", where n is the integer nearest the exact
value of "x / b" (if two integers are equally near then the even one
is chosen). If the result is equal to 0 then its sign will be the
sign of a. | [
"Returns",
"to",
"be",
"a",
"-",
"b",
"*",
"n",
"where",
"n",
"is",
"the",
"integer",
"nearest",
"the",
"exact",
"value",
"of",
"x",
"/",
"b",
"(",
"if",
"two",
"integers",
"are",
"equally",
"near",
"then",
"the",
"even",
"one",
"is",
"chosen",
")"... | def remainder_near(self, a, b):
"""Returns to be "a - b * n", where n is the integer nearest the exact
value of "x / b" (if two integers are equally near then the even one
is chosen). If the result is equal to 0 then its sign will be the
sign of a.
This operation will fail under the same conditions as integer division
(that is, if integer division on the same two operands would fail, the
remainder cannot be calculated).
>>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Decimal('-0.9')
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Decimal('-2')
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Decimal('1')
>>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Decimal('-1')
>>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Decimal('0.2')
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Decimal('0.1')
>>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Decimal('-0.3')
"""
return a.remainder_near(b, context=self) | [
"def",
"remainder_near",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"return",
"a",
".",
"remainder_near",
"(",
"b",
",",
"context",
"=",
"self",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L4709-L4734 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py | python | EC2Connection.unmonitor_instances | (self, instance_ids, dry_run=False) | return self.get_list('UnmonitorInstances', params,
[('item', InstanceInfo)], verb='POST') | Disable CloudWatch monitoring for the supplied instance.
:type instance_id: list of string
:param instance_id: The instance id
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: list
:return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo` | Disable CloudWatch monitoring for the supplied instance. | [
"Disable",
"CloudWatch",
"monitoring",
"for",
"the",
"supplied",
"instance",
"."
] | def unmonitor_instances(self, instance_ids, dry_run=False):
"""
Disable CloudWatch monitoring for the supplied instance.
:type instance_id: list of string
:param instance_id: The instance id
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: list
:return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
"""
params = {}
self.build_list_params(params, instance_ids, 'InstanceId')
if dry_run:
params['DryRun'] = 'true'
return self.get_list('UnmonitorInstances', params,
[('item', InstanceInfo)], verb='POST') | [
"def",
"unmonitor_instances",
"(",
"self",
",",
"instance_ids",
",",
"dry_run",
"=",
"False",
")",
":",
"params",
"=",
"{",
"}",
"self",
".",
"build_list_params",
"(",
"params",
",",
"instance_ids",
",",
"'InstanceId'",
")",
"if",
"dry_run",
":",
"params",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py#L3905-L3923 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/MilitaryAI.py | python | Allocator._regional_threat | (self) | return get_system_regional_threat(self.sys_id) | Threat derived from enemy supply lanes. | Threat derived from enemy supply lanes. | [
"Threat",
"derived",
"from",
"enemy",
"supply",
"lanes",
"."
] | def _regional_threat(self):
"""Threat derived from enemy supply lanes."""
return get_system_regional_threat(self.sys_id) | [
"def",
"_regional_threat",
"(",
"self",
")",
":",
"return",
"get_system_regional_threat",
"(",
"self",
".",
"sys_id",
")"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/MilitaryAI.py#L414-L416 | |
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | docs/examples/use_cases/tensorflow/efficientdet/model/backbone/efficientnet_model.py | python | round_repeats | (repeats, global_params, skip=False) | return int(math.ceil(multiplier * repeats)) | Round number of filters based on depth multiplier. | Round number of filters based on depth multiplier. | [
"Round",
"number",
"of",
"filters",
"based",
"on",
"depth",
"multiplier",
"."
] | def round_repeats(repeats, global_params, skip=False):
"""Round number of filters based on depth multiplier."""
multiplier = global_params.depth_coefficient
if skip or not multiplier:
return repeats
return int(math.ceil(multiplier * repeats)) | [
"def",
"round_repeats",
"(",
"repeats",
",",
"global_params",
",",
"skip",
"=",
"False",
")",
":",
"multiplier",
"=",
"global_params",
".",
"depth_coefficient",
"if",
"skip",
"or",
"not",
"multiplier",
":",
"return",
"repeats",
"return",
"int",
"(",
"math",
... | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/tensorflow/efficientdet/model/backbone/efficientnet_model.py#L143-L148 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/ssl.py | python | SSLSocket.connect_ex | (self, addr) | return self._real_connect(addr, True) | Connects to remote ADDR, and then wraps the connection in
an SSL channel. | Connects to remote ADDR, and then wraps the connection in
an SSL channel. | [
"Connects",
"to",
"remote",
"ADDR",
"and",
"then",
"wraps",
"the",
"connection",
"in",
"an",
"SSL",
"channel",
"."
] | def connect_ex(self, addr):
"""Connects to remote ADDR, and then wraps the connection in
an SSL channel."""
return self._real_connect(addr, True) | [
"def",
"connect_ex",
"(",
"self",
",",
"addr",
")",
":",
"return",
"self",
".",
"_real_connect",
"(",
"addr",
",",
"True",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ssl.py#L883-L886 | |
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | docs/doxygen/gmxtree.py | python | GromacsTree.find_include_file | (self, includedpath) | Find a file object corresponding to an include path. | Find a file object corresponding to an include path. | [
"Find",
"a",
"file",
"object",
"corresponding",
"to",
"an",
"include",
"path",
"."
] | def find_include_file(self, includedpath):
"""Find a file object corresponding to an include path."""
for testdir in ('src', 'src/external/thread_mpi/include',
'src/external/tng_io/include'):
testpath = os.path.join(testdir, includedpath)
if testpath in self._files:
return self._files[testpath] | [
"def",
"find_include_file",
"(",
"self",
",",
"includedpath",
")",
":",
"for",
"testdir",
"in",
"(",
"'src'",
",",
"'src/external/thread_mpi/include'",
",",
"'src/external/tng_io/include'",
")",
":",
"testpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"testdir... | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/docs/doxygen/gmxtree.py#L944-L950 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Calibration/ideal_tube.py | python | IdealTube.constructTubeFor3PointsMethod | (self, idealAP, idealBP, idealCP, activeTubeLen) | Construct and ideal tube for Merlin 3-point calibration
:param idealAP: Ideal left (AP) in pixels
:param idealBP: ideal right (BP) in pixels
:param idealCP: ideal centre (CP) in pixels
:param activeTubeLen: Active tube length in metres | Construct and ideal tube for Merlin 3-point calibration | [
"Construct",
"and",
"ideal",
"tube",
"for",
"Merlin",
"3",
"-",
"point",
"calibration"
] | def constructTubeFor3PointsMethod(self, idealAP, idealBP, idealCP, activeTubeLen):
"""
Construct and ideal tube for Merlin 3-point calibration
:param idealAP: Ideal left (AP) in pixels
:param idealBP: ideal right (BP) in pixels
:param idealCP: ideal centre (CP) in pixels
:param activeTubeLen: Active tube length in metres
"""
#Construct Ideal tube for 3 point calibration of MERLIN standard tube (code could be put into a function)
pixelLen = activeTubeLen/1024 # Pixel length
# we then convert idealAP, idealCP and idealBP to Y coordinates and put into ideal tube array
self.positions = np.array([idealAP*pixelLen - activeTubeLen/2,
idealCP*pixelLen - activeTubeLen/2, idealBP*pixelLen - activeTubeLen/2])
self.functionalForms = [2, 1, 2] | [
"def",
"constructTubeFor3PointsMethod",
"(",
"self",
",",
"idealAP",
",",
"idealBP",
",",
"idealCP",
",",
"activeTubeLen",
")",
":",
"#Construct Ideal tube for 3 point calibration of MERLIN standard tube (code could be put into a function)",
"pixelLen",
"=",
"activeTubeLen",
"/",... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Calibration/ideal_tube.py#L68-L84 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | default_fill_value | (obj) | Function to calculate default fill value for an object. | Function to calculate default fill value for an object. | [
"Function",
"to",
"calculate",
"default",
"fill",
"value",
"for",
"an",
"object",
"."
] | def default_fill_value (obj):
"Function to calculate default fill value for an object."
if isinstance(obj, float):
return default_real_fill_value
elif isinstance(obj, int) or isinstance(obj, long):
return default_integer_fill_value
elif isinstance(obj, bytes):
return default_character_fill_value
elif isinstance(obj, complex):
return default_complex_fill_value
elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
x = obj.dtype.char
if x in typecodes['Float']:
return default_real_fill_value
if x in typecodes['Integer']:
return default_integer_fill_value
if x in typecodes['Complex']:
return default_complex_fill_value
if x in typecodes['Character']:
return default_character_fill_value
if x in typecodes['UnsignedInteger']:
return umath.absolute(default_integer_fill_value)
return default_object_fill_value
else:
return default_object_fill_value | [
"def",
"default_fill_value",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"float",
")",
":",
"return",
"default_real_fill_value",
"elif",
"isinstance",
"(",
"obj",
",",
"int",
")",
"or",
"isinstance",
"(",
"obj",
",",
"long",
")",
":",
"ret... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L96-L120 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/srv/_GetGeographicMap.py | python | GetGeographicMapResponse.deserialize_numpy | (self, str, numpy) | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | [
"unpack",
"serialized",
"message",
"in",
"str",
"into",
"this",
"message",
"instance",
"using",
"numpy",
"for",
"array",
"types",
":",
"param",
"str",
":",
"byte",
"array",
"of",
"serialized",
"message",
"str",
":",
"param",
"numpy",
":",
"numpy",
"python",
... | def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
if self.map is None:
self.map = geographic_msgs.msg.GeographicMap()
end = 0
start = end
end += 1
(self.success,) = _struct_B.unpack(str[start:end])
self.success = bool(self.success)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.status = str[start:end].decode('utf-8')
else:
self.status = str[start:end]
_x = self
start = end
end += 12
(_x.map.header.seq, _x.map.header.stamp.secs, _x.map.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.map.header.frame_id = str[start:end].decode('utf-8')
else:
self.map.header.frame_id = str[start:end]
start = end
end += 16
self.map.id.uuid = str[start:end]
_x = self
start = end
end += 48
(_x.map.bounds.min_pt.latitude, _x.map.bounds.min_pt.longitude, _x.map.bounds.min_pt.altitude, _x.map.bounds.max_pt.latitude, _x.map.bounds.max_pt.longitude, _x.map.bounds.max_pt.altitude,) = _struct_6d.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.map.points = []
for i in range(0, length):
val1 = geographic_msgs.msg.WayPoint()
_v10 = val1.id
start = end
end += 16
_v10.uuid = str[start:end]
_v11 = val1.position
_x = _v11
start = end
end += 24
(_x.latitude, _x.longitude, _x.altitude,) = _struct_3d.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
val1.props = []
for i in range(0, length):
val2 = geographic_msgs.msg.KeyValue()
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val2.key = str[start:end].decode('utf-8')
else:
val2.key = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val2.value = str[start:end].decode('utf-8')
else:
val2.value = str[start:end]
val1.props.append(val2)
self.map.points.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.map.features = []
for i in range(0, length):
val1 = geographic_msgs.msg.MapFeature()
_v12 = val1.id
start = end
end += 16
_v12.uuid = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
val1.components = []
for i in range(0, length):
val2 = uuid_msgs.msg.UniqueID()
start = end
end += 16
val2.uuid = str[start:end]
val1.components.append(val2)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
val1.props = []
for i in range(0, length):
val2 = geographic_msgs.msg.KeyValue()
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val2.key = str[start:end].decode('utf-8')
else:
val2.key = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val2.value = str[start:end].decode('utf-8')
else:
val2.value = str[start:end]
val1.props.append(val2)
self.map.features.append(val1)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.map.props = []
for i in range(0, length):
val1 = geographic_msgs.msg.KeyValue()
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1.key = str[start:end].decode('utf-8')
else:
val1.key = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
val1.value = str[start:end].decode('utf-8')
else:
val1.value = str[start:end]
self.map.props.append(val1)
return self
except struct.error as e:
raise genpy.DeserializationError(e) | [
"def",
"deserialize_numpy",
"(",
"self",
",",
"str",
",",
"numpy",
")",
":",
"try",
":",
"if",
"self",
".",
"map",
"is",
"None",
":",
"self",
".",
"map",
"=",
"geographic_msgs",
".",
"msg",
".",
"GeographicMap",
"(",
")",
"end",
"=",
"0",
"start",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/srv/_GetGeographicMap.py#L779-L936 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/compile_utils.py | python | MetricsContainer.update_state | (self, y_true, y_pred, sample_weight=None) | Updates the state of per-output metrics. | Updates the state of per-output metrics. | [
"Updates",
"the",
"state",
"of",
"per",
"-",
"output",
"metrics",
"."
] | def update_state(self, y_true, y_pred, sample_weight=None):
"""Updates the state of per-output metrics."""
y_true = self._conform_to_outputs(y_pred, y_true)
sample_weight = self._conform_to_outputs(y_pred, sample_weight)
if not self._built:
self.build(y_pred, y_true)
y_pred = nest.flatten(y_pred)
y_true = nest.flatten(y_true) if y_true is not None else []
sample_weight = nest.flatten(sample_weight)
zip_args = (y_true, y_pred, sample_weight, self._metrics,
self._weighted_metrics)
for y_t, y_p, sw, metric_objs, weighted_metric_objs in zip(*zip_args):
# Ok to have no metrics for an output.
if (y_t is None or (all(m is None for m in metric_objs) and
all(wm is None for wm in weighted_metric_objs))):
continue
y_t, y_p, sw = match_dtype_and_rank(y_t, y_p, sw)
mask = get_mask(y_p)
sw = apply_mask(y_p, sw, mask)
for metric_obj in metric_objs:
if metric_obj is None:
continue
metric_obj.update_state(y_t, y_p, sample_weight=mask)
for weighted_metric_obj in weighted_metric_objs:
if weighted_metric_obj is None:
continue
weighted_metric_obj.update_state(y_t, y_p, sample_weight=sw) | [
"def",
"update_state",
"(",
"self",
",",
"y_true",
",",
"y_pred",
",",
"sample_weight",
"=",
"None",
")",
":",
"y_true",
"=",
"self",
".",
"_conform_to_outputs",
"(",
"y_pred",
",",
"y_true",
")",
"sample_weight",
"=",
"self",
".",
"_conform_to_outputs",
"("... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/compile_utils.py#L433-L465 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/execution.py | python | Execution.price | (self) | return self._price | Gets the price of this Execution. # noqa: E501
:return: The price of this Execution. # noqa: E501
:rtype: float | Gets the price of this Execution. # noqa: E501 | [
"Gets",
"the",
"price",
"of",
"this",
"Execution",
".",
"#",
"noqa",
":",
"E501"
] | def price(self):
"""Gets the price of this Execution. # noqa: E501
:return: The price of this Execution. # noqa: E501
:rtype: float
"""
return self._price | [
"def",
"price",
"(",
"self",
")",
":",
"return",
"self",
".",
"_price"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/execution.py#L576-L583 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter._WinIdlRule | (self, source, prebuild, outputs) | Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated. | Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated. | [
"Handle",
"the",
"implicit",
"VS",
".",
"idl",
"rule",
"for",
"one",
"source",
"file",
".",
"Fills",
"|outputs|",
"with",
"files",
"that",
"are",
"generated",
"."
] | def _WinIdlRule(self, source, prebuild, outputs):
"""Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated."""
outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData(
source, self.config_name)
outdir = self.GypPathToNinja(outdir)
def fix_path(path, rel=None):
path = os.path.join(outdir, path)
dirname, basename = os.path.split(source)
root, ext = os.path.splitext(basename)
path = self.ExpandRuleVariables(
path, root, dirname, source, ext, basename)
if rel:
path = os.path.relpath(path, rel)
return path
vars = [(name, fix_path(value, outdir)) for name, value in vars]
output = [fix_path(p) for p in output]
vars.append(('outdir', outdir))
vars.append(('idlflags', flags))
input = self.GypPathToNinja(source)
self.ninja.build(output, 'idl', input,
variables=vars, order_only=prebuild)
outputs.extend(output) | [
"def",
"_WinIdlRule",
"(",
"self",
",",
"source",
",",
"prebuild",
",",
"outputs",
")",
":",
"outdir",
",",
"output",
",",
"vars",
",",
"flags",
"=",
"self",
".",
"msvs_settings",
".",
"GetIdlBuildData",
"(",
"source",
",",
"self",
".",
"config_name",
")... | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/ninja.py#L504-L526 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py | python | IsStrCanonicalInt | (string) | return False | Returns True if |string| is in its canonical integer form.
The canonical form is such that str(int(string)) == string. | Returns True if |string| is in its canonical integer form. | [
"Returns",
"True",
"if",
"|string|",
"is",
"in",
"its",
"canonical",
"integer",
"form",
"."
] | def IsStrCanonicalInt(string):
"""Returns True if |string| is in its canonical integer form.
The canonical form is such that str(int(string)) == string.
"""
if type(string) is str:
# This function is called a lot so for maximum performance, avoid
# involving regexps which would otherwise make the code much
# shorter. Regexps would need twice the time of this function.
if string:
if string == "0":
return True
if string[0] == "-":
string = string[1:]
if not string:
return False
if '1' <= string[0] <= '9':
return string.isdigit()
return False | [
"def",
"IsStrCanonicalInt",
"(",
"string",
")",
":",
"if",
"type",
"(",
"string",
")",
"is",
"str",
":",
"# This function is called a lot so for maximum performance, avoid",
"# involving regexps which would otherwise make the code much",
"# shorter. Regexps would need twice the time ... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L646-L665 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListCtrl.SetItemBackgroundColour | (self, item, col) | Sets the item background colour.
:param `item`: the index of the item;
:param `col`: a valid :class:`Colour` object. | Sets the item background colour. | [
"Sets",
"the",
"item",
"background",
"colour",
"."
] | def SetItemBackgroundColour(self, item, col):
"""
Sets the item background colour.
:param `item`: the index of the item;
:param `col`: a valid :class:`Colour` object.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
info.SetBackgroundColour(col)
self._mainWin.SetItem(info) | [
"def",
"SetItemBackgroundColour",
"(",
"self",
",",
"item",
",",
"col",
")",
":",
"info",
"=",
"UltimateListItem",
"(",
")",
"info",
".",
"_itemId",
"=",
"item",
"info",
"=",
"self",
".",
"_mainWin",
".",
"GetItem",
"(",
"info",
")",
"info",
".",
"SetB... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L11679-L11691 | ||
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | utils/check-style.py | python | PatchChunk.dst_len | (self) | return len(self.dst()) | ! Get number of destinaton lines
@param self The current class
@return number of destination lines | ! Get number of destinaton lines | [
"!",
"Get",
"number",
"of",
"destinaton",
"lines"
] | def dst_len(self):
"""! Get number of destinaton lines
@param self The current class
@return number of destination lines
"""
return len(self.dst()) | [
"def",
"dst_len",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"dst",
"(",
")",
")"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/check-style.py#L280-L285 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | Grid.SetColSizes | (*args, **kwargs) | return _grid.Grid_SetColSizes(*args, **kwargs) | SetColSizes(self, GridSizesInfo sizeInfo) | SetColSizes(self, GridSizesInfo sizeInfo) | [
"SetColSizes",
"(",
"self",
"GridSizesInfo",
"sizeInfo",
")"
] | def SetColSizes(*args, **kwargs):
"""SetColSizes(self, GridSizesInfo sizeInfo)"""
return _grid.Grid_SetColSizes(*args, **kwargs) | [
"def",
"SetColSizes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_SetColSizes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L1854-L1856 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/utils.py | python | default_user_agent | (name="python-requests") | return '%s/%s' % (name, __version__) | Return a string representing the default user agent.
:rtype: str | Return a string representing the default user agent. | [
"Return",
"a",
"string",
"representing",
"the",
"default",
"user",
"agent",
"."
] | def default_user_agent(name="python-requests"):
"""
Return a string representing the default user agent.
:rtype: str
"""
return '%s/%s' % (name, __version__) | [
"def",
"default_user_agent",
"(",
"name",
"=",
"\"python-requests\"",
")",
":",
"return",
"'%s/%s'",
"%",
"(",
"name",
",",
"__version__",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/utils.py#L798-L804 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_siv.py | python | SivMode._create_ctr_cipher | (self, v) | return self._factory.new(
self._subkey_cipher,
self._factory.MODE_CTR,
initial_value=q,
nonce=b"",
**self._cipher_params) | Create a new CTR cipher from V in SIV mode | Create a new CTR cipher from V in SIV mode | [
"Create",
"a",
"new",
"CTR",
"cipher",
"from",
"V",
"in",
"SIV",
"mode"
] | def _create_ctr_cipher(self, v):
"""Create a new CTR cipher from V in SIV mode"""
v_int = bytes_to_long(v)
q = v_int & 0xFFFFFFFFFFFFFFFF7FFFFFFF7FFFFFFF
return self._factory.new(
self._subkey_cipher,
self._factory.MODE_CTR,
initial_value=q,
nonce=b"",
**self._cipher_params) | [
"def",
"_create_ctr_cipher",
"(",
"self",
",",
"v",
")",
":",
"v_int",
"=",
"bytes_to_long",
"(",
"v",
")",
"q",
"=",
"v_int",
"&",
"0xFFFFFFFFFFFFFFFF7FFFFFFF7FFFFFFF",
"return",
"self",
".",
"_factory",
".",
"new",
"(",
"self",
".",
"_subkey_cipher",
",",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_siv.py#L129-L139 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_uninstall.py | python | compress_for_rename | (paths) | return set(map(case_map.__getitem__, remaining)) | wildcards | Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk. | Returns a set containing the paths that need to be renamed. | [
"Returns",
"a",
"set",
"containing",
"the",
"paths",
"that",
"need",
"to",
"be",
"renamed",
"."
] | def compress_for_rename(paths):
# type: (Iterable[str]) -> Set[str]
"""Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk.
"""
case_map = {os.path.normcase(p): p for p in paths}
remaining = set(case_map)
unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len)
wildcards = set() # type: Set[str]
def norm_join(*a):
# type: (str) -> str
return os.path.normcase(os.path.join(*a))
for root in unchecked:
if any(os.path.normcase(root).startswith(w)
for w in wildcards):
# This directory has already been handled.
continue
all_files = set() # type: Set[str]
all_subdirs = set() # type: Set[str]
for dirname, subdirs, files in os.walk(root):
all_subdirs.update(norm_join(root, dirname, d)
for d in subdirs)
all_files.update(norm_join(root, dirname, f)
for f in files)
# If all the files we found are in our remaining set of files to
# remove, then remove them from the latter set and add a wildcard
# for the directory.
if not (all_files - remaining):
remaining.difference_update(all_files)
wildcards.add(root + os.sep)
return set(map(case_map.__getitem__, remaining)) | wildcards | [
"def",
"compress_for_rename",
"(",
"paths",
")",
":",
"# type: (Iterable[str]) -> Set[str]",
"case_map",
"=",
"{",
"os",
".",
"path",
".",
"normcase",
"(",
"p",
")",
":",
"p",
"for",
"p",
"in",
"paths",
"}",
"remaining",
"=",
"set",
"(",
"case_map",
")",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_uninstall.py#L249-L321 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/powderdata.py | python | PowderData.extract | (self) | return {key: {str(k): array for k, array in data.items()}
for key, data in self._data.items()} | Get tensor data as dict | Get tensor data as dict | [
"Get",
"tensor",
"data",
"as",
"dict"
] | def extract(self) -> PowderDict:
"""Get tensor data as dict"""
return {key: {str(k): array for k, array in data.items()}
for key, data in self._data.items()} | [
"def",
"extract",
"(",
"self",
")",
"->",
"PowderDict",
":",
"return",
"{",
"key",
":",
"{",
"str",
"(",
"k",
")",
":",
"array",
"for",
"k",
",",
"array",
"in",
"data",
".",
"items",
"(",
")",
"}",
"for",
"key",
",",
"data",
"in",
"self",
".",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/powderdata.py#L65-L68 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/chebyshev.py | python | chebdiv | (c1, c2) | Divide one Chebyshev series by another.
Returns the quotient-with-remainder of two Chebyshev series
`c1` / `c2`. The arguments are sequences of coefficients from lowest
order "term" to highest, e.g., [1,2,3] represents the series
``T_0 + 2*T_1 + 3*T_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Chebyshev series coefficients ordered from low to
high.
Returns
-------
[quo, rem] : ndarrays
Of Chebyshev series coefficients representing the quotient and
remainder.
See Also
--------
chebadd, chebsub, chebmulx, chebmul, chebpow
Notes
-----
In general, the (polynomial) division of one C-series by another
results in quotient and remainder terms that are not in the Chebyshev
polynomial basis set. Thus, to express these results as C-series, it
is typically necessary to "reproject" the results onto said basis
set, which typically produces "unintuitive" (but correct) results;
see Examples section below.
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not
(array([3.]), array([-8., -4.]))
>>> c2 = (0,1,2,3)
>>> C.chebdiv(c2,c1) # neither "intuitive"
(array([0., 2.]), array([-2., -4.])) | Divide one Chebyshev series by another. | [
"Divide",
"one",
"Chebyshev",
"series",
"by",
"another",
"."
] | def chebdiv(c1, c2):
"""
Divide one Chebyshev series by another.
Returns the quotient-with-remainder of two Chebyshev series
`c1` / `c2`. The arguments are sequences of coefficients from lowest
order "term" to highest, e.g., [1,2,3] represents the series
``T_0 + 2*T_1 + 3*T_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Chebyshev series coefficients ordered from low to
high.
Returns
-------
[quo, rem] : ndarrays
Of Chebyshev series coefficients representing the quotient and
remainder.
See Also
--------
chebadd, chebsub, chebmulx, chebmul, chebpow
Notes
-----
In general, the (polynomial) division of one C-series by another
results in quotient and remainder terms that are not in the Chebyshev
polynomial basis set. Thus, to express these results as C-series, it
is typically necessary to "reproject" the results onto said basis
set, which typically produces "unintuitive" (but correct) results;
see Examples section below.
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not
(array([3.]), array([-8., -4.]))
>>> c2 = (0,1,2,3)
>>> C.chebdiv(c2,c1) # neither "intuitive"
(array([0., 2.]), array([-2., -4.]))
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if c2[-1] == 0:
raise ZeroDivisionError()
# note: this is more efficient than `pu._div(chebmul, c1, c2)`
lc1 = len(c1)
lc2 = len(c2)
if lc1 < lc2:
return c1[:1]*0, c1
elif lc2 == 1:
return c1/c2[-1], c1[:1]*0
else:
z1 = _cseries_to_zseries(c1)
z2 = _cseries_to_zseries(c2)
quo, rem = _zseries_div(z1, z2)
quo = pu.trimseq(_zseries_to_cseries(quo))
rem = pu.trimseq(_zseries_to_cseries(rem))
return quo, rem | [
"def",
"chebdiv",
"(",
"c1",
",",
"c2",
")",
":",
"# c1, c2 are trimmed copies",
"[",
"c1",
",",
"c2",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"c1",
",",
"c2",
"]",
")",
"if",
"c2",
"[",
"-",
"1",
"]",
"==",
"0",
":",
"raise",
"ZeroDivisionEr... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/chebyshev.py#L750-L814 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/Tools/scripts/summarizeEdmComparisonLogfiles.py | python | summaryOK | (summary) | return (retval, {'count':count, 'compared':compared}) | returns a tuple. First value is true if summary hasn't found
any problems, else false. | returns a tuple. First value is true if summary hasn't found
any problems, else false. | [
"returns",
"a",
"tuple",
".",
"First",
"value",
"is",
"true",
"if",
"summary",
"hasn",
"t",
"found",
"any",
"problems",
"else",
"false",
"."
] | def summaryOK (summary):
"""returns a tuple. First value is true if summary hasn't found
any problems, else false."""
retval = True
count = -1
compared = summary.get('eventsCompared', -1)
if len( summary) != 2:
retval = False
for key,value in summary.items():
if countRE.search(key):
count = value
return (retval, {'count':count, 'compared':compared}) | [
"def",
"summaryOK",
"(",
"summary",
")",
":",
"retval",
"=",
"True",
"count",
"=",
"-",
"1",
"compared",
"=",
"summary",
".",
"get",
"(",
"'eventsCompared'",
",",
"-",
"1",
")",
"if",
"len",
"(",
"summary",
")",
"!=",
"2",
":",
"retval",
"=",
"Fals... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/Tools/scripts/summarizeEdmComparisonLogfiles.py#L13-L24 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/plots/axesfunctions.py | python | _setLabels1D | (axes,
workspace,
indices=None,
normalize_by_bin_width=True,
axis=MantidAxType.SPECTRUM) | helper function to automatically set axes labels for 1D plots | helper function to automatically set axes labels for 1D plots | [
"helper",
"function",
"to",
"automatically",
"set",
"axes",
"labels",
"for",
"1D",
"plots"
] | def _setLabels1D(axes,
workspace,
indices=None,
normalize_by_bin_width=True,
axis=MantidAxType.SPECTRUM):
'''
helper function to automatically set axes labels for 1D plots
'''
labels = get_axes_labels(workspace, indices, normalize_by_bin_width)
# We assume that previous checking has ensured axis can only be 1 of 2 types
axes.set_xlabel(labels[2 if axis == MantidAxType.BIN else 1])
axes.set_ylabel(labels[0]) | [
"def",
"_setLabels1D",
"(",
"axes",
",",
"workspace",
",",
"indices",
"=",
"None",
",",
"normalize_by_bin_width",
"=",
"True",
",",
"axis",
"=",
"MantidAxType",
".",
"SPECTRUM",
")",
":",
"labels",
"=",
"get_axes_labels",
"(",
"workspace",
",",
"indices",
",... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/plots/axesfunctions.py#L68-L79 | ||
ideawu/icomet | e842345af22b49cc00226ba4378bf1f2e377a597 | deps/libevent-2.0.21-stable/event_rpcgen.py | python | EntryInt.CodeArrayAdd | (self, varname, value) | return [ '%(varname)s = %(value)s;' % { 'varname' : varname,
'value' : value } ] | Returns a new entry of this type. | Returns a new entry of this type. | [
"Returns",
"a",
"new",
"entry",
"of",
"this",
"type",
"."
] | def CodeArrayAdd(self, varname, value):
"""Returns a new entry of this type."""
return [ '%(varname)s = %(value)s;' % { 'varname' : varname,
'value' : value } ] | [
"def",
"CodeArrayAdd",
"(",
"self",
",",
"varname",
",",
"value",
")",
":",
"return",
"[",
"'%(varname)s = %(value)s;'",
"%",
"{",
"'varname'",
":",
"varname",
",",
"'value'",
":",
"value",
"}",
"]"
] | https://github.com/ideawu/icomet/blob/e842345af22b49cc00226ba4378bf1f2e377a597/deps/libevent-2.0.21-stable/event_rpcgen.py#L621-L624 | |
google/clif | cab24d6a105609a65c95a36a1712ae3c20c7b5df | clif/python/slots.py | python | GenSetAttr | (setattr_slots) | Generate slot implementation for __set*__ / __del*__ user functions. | Generate slot implementation for __set*__ / __del*__ user functions. | [
"Generate",
"slot",
"implementation",
"for",
"__set",
"*",
"__",
"/",
"__del",
"*",
"__",
"user",
"functions",
"."
] | def GenSetAttr(setattr_slots):
"""Generate slot implementation for __set*__ / __del*__ user functions."""
assert len(setattr_slots) == 2, 'Need 2-slot input.'
set_attr, del_attr = setattr_slots
assert setattr or delattr, 'Need one or both set/del funcs.'
yield ''
yield 'int slot_seto(PyObject* self, PyObject* name, PyObject* value) {'
yield I+'if (value != nullptr) {'
if set_attr:
yield I+I+'PyObject* args = PyTuple_Pack(2, name, value);'
yield I+I+'if (args == nullptr) return -1;'
yield I+I+'int r = slot::ignore(%s(self, args, nullptr));' % set_attr
yield I+I+'Py_DECREF(args);'
yield I+I+'return r;'
else:
yield I+I+'PyErr_SetNone(PyExc_NotImplementedError);'
yield I+I+'return -1;'
yield I+'} else {'
if del_attr:
yield I+I+'PyObject* args = PyTuple_Pack(1, name);'
yield I+I+'if (args == nullptr) return -1;'
yield I+I+'int r = slot::ignore(%s(self, args, nullptr));' % del_attr
yield I+I+'Py_DECREF(args);'
yield I+I+'return r;'
else:
yield I+I+'PyErr_SetNone(PyExc_NotImplementedError);'
yield I+I+'return -1;'
yield I+'}'
yield '}' | [
"def",
"GenSetAttr",
"(",
"setattr_slots",
")",
":",
"assert",
"len",
"(",
"setattr_slots",
")",
"==",
"2",
",",
"'Need 2-slot input.'",
"set_attr",
",",
"del_attr",
"=",
"setattr_slots",
"assert",
"setattr",
"or",
"delattr",
",",
"'Need one or both set/del funcs.'"... | https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/slots.py#L120-L148 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | PUTXnHandler.WriteServiceUnitTest | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteServiceUnitTest(self, func, file):
"""Overrriden from TypeHandler."""
valid_test = """
TEST_F(%(test_name)s, %(name)sValidArgs) {
EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
SpecializedSetup<cmds::%(name)s, 0>(true);
cmds::%(name)s cmd;
cmd.Init(%(args)s);
EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
EXPECT_EQ(GL_NO_ERROR, GetGLError());
}
"""
args = func.GetOriginalArgs()
local_args = "%s, 1, _" % args[0].GetValidGLArg(func, 0, 0)
self.WriteValidUnitTest(func, file, valid_test, {
'name': func.name,
'count': func.GetInfo('count'),
'local_args': local_args,
})
invalid_test = """
TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
SpecializedSetup<cmds::%(name)s, 0>(false);
cmds::%(name)s cmd;
cmd.Init(%(args)s);
EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
}
"""
self.WriteInvalidUnitTest(func, file, invalid_test, {
'name': func.GetInfo('name'),
'count': func.GetInfo('count'),
}) | [
"def",
"WriteServiceUnitTest",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"valid_test",
"=",
"\"\"\"\nTEST_F(%(test_name)s, %(name)sValidArgs) {\n EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));\n SpecializedSetup<cmds::%(name)s, 0>(true);\n cmds::%(name)s cmd;\n cmd.Init(%(args)s);\... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5264-L5296 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Listbox.selection_set | (self, first, last=None) | Set the selection from FIRST to LAST (included) without
changing the currently selected elements. | Set the selection from FIRST to LAST (included) without
changing the currently selected elements. | [
"Set",
"the",
"selection",
"from",
"FIRST",
"to",
"LAST",
"(",
"included",
")",
"without",
"changing",
"the",
"currently",
"selected",
"elements",
"."
] | def selection_set(self, first, last=None):
"""Set the selection from FIRST to LAST (included) without
changing the currently selected elements."""
self.tk.call(self._w, 'selection', 'set', first, last) | [
"def",
"selection_set",
"(",
"self",
",",
"first",
",",
"last",
"=",
"None",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'selection'",
",",
"'set'",
",",
"first",
",",
"last",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2836-L2839 | ||
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | ctpx/ctp2/ctpmd.py | python | CtpMd.onRspUserLogout | (self, UserLogoutField, RspInfoField, requestId, final) | 登出请求响应 | 登出请求响应 | [
"登出请求响应"
] | def onRspUserLogout(self, UserLogoutField, RspInfoField, requestId, final):
"""登出请求响应"""
if RspInfoField.errorID == 0:
log = u'行情服务器登出成功'
else:
log = u'行情服务登出失败,错误码:[{0}], 错误信息:[{1}]'.format(
RspInfoField.errorID, RspInfoField.errorMsg.decode('gbk'))
logger.info(log) | [
"def",
"onRspUserLogout",
"(",
"self",
",",
"UserLogoutField",
",",
"RspInfoField",
",",
"requestId",
",",
"final",
")",
":",
"if",
"RspInfoField",
".",
"errorID",
"==",
"0",
":",
"log",
"=",
"u'行情服务器登出成功'",
"else",
":",
"log",
"=",
"u'行情服务登出失败,错误码:[{0}], 错误信息... | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp2/ctpmd.py#L59-L66 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/libmintsmolecule.py | python | LibmintsMolecule.create_psi4_string_from_molecule | (self, force_c1=False) | return text | Regenerates a input file molecule specification string from the
current state of the Molecule. Contains geometry info,
fragmentation, charges and multiplicities, and any frame
restriction. | Regenerates a input file molecule specification string from the
current state of the Molecule. Contains geometry info,
fragmentation, charges and multiplicities, and any frame
restriction. | [
"Regenerates",
"a",
"input",
"file",
"molecule",
"specification",
"string",
"from",
"the",
"current",
"state",
"of",
"the",
"Molecule",
".",
"Contains",
"geometry",
"info",
"fragmentation",
"charges",
"and",
"multiplicities",
"and",
"any",
"frame",
"restriction",
... | def create_psi4_string_from_molecule(self, force_c1=False):
"""Regenerates a input file molecule specification string from the
current state of the Molecule. Contains geometry info,
fragmentation, charges and multiplicities, and any frame
restriction.
"""
text = ""
if self.nallatom():
# append units and any other non-default molecule keywords
text += " units %-s\n" % ("Angstrom" if self.units() == 'Angstrom' else "Bohr")
if not self.PYmove_to_com:
text += " no_com\n"
if self.PYfix_orientation:
text += " no_reorient\n"
if force_c1:
text += " symmetry c1\n"
text += " {} {}\n --\n".format(self.molecular_charge(), self.multiplicity())
# append atoms and coordentries and fragment separators with charge and multiplicity
Pfr = 0
for fr in range(self.nfragments()):
if self.fragment_types[fr] == 'Absent' and not self.has_zmatrix():
continue
text += "%s %s%d %d\n" % (
"" if Pfr == 0 else " --\n",
"#" if self.fragment_types[fr] == 'Ghost' or self.fragment_types[fr] == 'Absent' else "",
self.fragment_charges[fr], self.fragment_multiplicities[fr])
Pfr += 1
for at in range(self.fragments[fr][0], self.fragments[fr][1] + 1):
if self.fragment_types[fr] == 'Absent':
text += " %-8s" % ("X")
elif self.fZ(at) or self.fsymbol(at) == "X":
text += " %-8s" % (self.flabel(at))
else:
text += " %-8s" % ("Gh(" + self.flabel(at) + ")")
text += " %s" % (self.full_atoms[at].print_in_input_format())
text += "\n"
# append any coordinate variables
if len(self.geometry_variables):
for vb, val in self.geometry_variables.items():
text += """ %-10s=%16.10f\n""" % (vb, val)
text += "\n"
return text | [
"def",
"create_psi4_string_from_molecule",
"(",
"self",
",",
"force_c1",
"=",
"False",
")",
":",
"text",
"=",
"\"\"",
"if",
"self",
".",
"nallatom",
"(",
")",
":",
"# append units and any other non-default molecule keywords",
"text",
"+=",
"\" units %-s\\n\"",
"%",... | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L945-L990 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/browser/profile_types.py | python | GetProfileTypes | () | return BASE_PROFILE_TYPES + PROFILE_TYPE_MAPPING.keys() | Returns a list of all command line options that can be specified for
profile type. | Returns a list of all command line options that can be specified for
profile type. | [
"Returns",
"a",
"list",
"of",
"all",
"command",
"line",
"options",
"that",
"can",
"be",
"specified",
"for",
"profile",
"type",
"."
] | def GetProfileTypes():
"""Returns a list of all command line options that can be specified for
profile type."""
return BASE_PROFILE_TYPES + PROFILE_TYPE_MAPPING.keys() | [
"def",
"GetProfileTypes",
"(",
")",
":",
"return",
"BASE_PROFILE_TYPES",
"+",
"PROFILE_TYPE_MAPPING",
".",
"keys",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/browser/profile_types.py#L16-L19 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/c_config.py | python | check_cfg | (self, *k, **kw) | return ret | Check for configuration flags using a **-config**-like program (pkg-config, sdl-config, etc).
Encapsulate the calls to :py:func:`waflib.Tools.c_config.validate_cfg` and :py:func:`waflib.Tools.c_config.exec_cfg`
A few examples::
def configure(conf):
conf.load('compiler_c')
conf.check_cfg(package='glib-2.0', args='--libs --cflags')
conf.check_cfg(package='glib-2.0', uselib_store='GLIB', atleast_version='2.10.0',
args='--cflags --libs')
conf.check_cfg(package='pango')
conf.check_cfg(package='pango', uselib_store='MYPANGO', args=['--cflags', '--libs'])
conf.check_cfg(package='pango',
args=['pango >= 0.1.0', 'pango < 9.9.9', '--cflags', '--libs'],
msg="Checking for 'pango 0.1.0'")
conf.check_cfg(path='sdl-config', args='--cflags --libs', package='', uselib_store='SDL')
conf.check_cfg(path='mpicc', args='--showme:compile --showme:link',
package='', uselib_store='OPEN_MPI', mandatory=False) | Check for configuration flags using a **-config**-like program (pkg-config, sdl-config, etc).
Encapsulate the calls to :py:func:`waflib.Tools.c_config.validate_cfg` and :py:func:`waflib.Tools.c_config.exec_cfg` | [
"Check",
"for",
"configuration",
"flags",
"using",
"a",
"**",
"-",
"config",
"**",
"-",
"like",
"program",
"(",
"pkg",
"-",
"config",
"sdl",
"-",
"config",
"etc",
")",
".",
"Encapsulate",
"the",
"calls",
"to",
":",
"py",
":",
"func",
":",
"waflib",
"... | def check_cfg(self, *k, **kw):
"""
Check for configuration flags using a **-config**-like program (pkg-config, sdl-config, etc).
Encapsulate the calls to :py:func:`waflib.Tools.c_config.validate_cfg` and :py:func:`waflib.Tools.c_config.exec_cfg`
A few examples::
def configure(conf):
conf.load('compiler_c')
conf.check_cfg(package='glib-2.0', args='--libs --cflags')
conf.check_cfg(package='glib-2.0', uselib_store='GLIB', atleast_version='2.10.0',
args='--cflags --libs')
conf.check_cfg(package='pango')
conf.check_cfg(package='pango', uselib_store='MYPANGO', args=['--cflags', '--libs'])
conf.check_cfg(package='pango',
args=['pango >= 0.1.0', 'pango < 9.9.9', '--cflags', '--libs'],
msg="Checking for 'pango 0.1.0'")
conf.check_cfg(path='sdl-config', args='--cflags --libs', package='', uselib_store='SDL')
conf.check_cfg(path='mpicc', args='--showme:compile --showme:link',
package='', uselib_store='OPEN_MPI', mandatory=False)
"""
if k:
lst = k[0].split()
kw['package'] = lst[0]
kw['args'] = ' '.join(lst[1:])
self.validate_cfg(kw)
if 'msg' in kw:
self.start_msg(kw['msg'])
ret = None
try:
ret = self.exec_cfg(kw)
except self.errors.WafError:
if 'errmsg' in kw:
self.end_msg(kw['errmsg'], 'YELLOW')
if Logs.verbose > 1:
raise
else:
self.fatal('The configuration failed')
else:
kw['success'] = ret
if 'okmsg' in kw:
self.end_msg(self.ret_msg(kw['okmsg'], kw))
return ret | [
"def",
"check_cfg",
"(",
"self",
",",
"*",
"k",
",",
"*",
"*",
"kw",
")",
":",
"if",
"k",
":",
"lst",
"=",
"k",
"[",
"0",
"]",
".",
"split",
"(",
")",
"kw",
"[",
"'package'",
"]",
"=",
"lst",
"[",
"0",
"]",
"kw",
"[",
"'args'",
"]",
"=",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/c_config.py#L339-L384 | |
greenheartgames/greenworks | 3ea4ab490b56676de3f0a237c74bcfdb17323e60 | deps/cpplint/cpplint.py | python | CheckAltTokens | (filename, clean_lines, linenum, error) | Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check alternative keywords being used in boolean expressions. | [
"Check",
"alternative",
"keywords",
"being",
"used",
"in",
"boolean",
"expressions",
"."
] | def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) | [
"def",
"CheckAltTokens",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Avoid preprocessor lines",
"if",
"Match",
"(",
"r'^\\s*#'",
",",
"line",
")",
":",
"retur... | https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L4181-L4210 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Point2D.GetCrossProduct | (*args, **kwargs) | return _core_.Point2D_GetCrossProduct(*args, **kwargs) | GetCrossProduct(self, Point2D vec) -> double | GetCrossProduct(self, Point2D vec) -> double | [
"GetCrossProduct",
"(",
"self",
"Point2D",
"vec",
")",
"-",
">",
"double"
] | def GetCrossProduct(*args, **kwargs):
"""GetCrossProduct(self, Point2D vec) -> double"""
return _core_.Point2D_GetCrossProduct(*args, **kwargs) | [
"def",
"GetCrossProduct",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Point2D_GetCrossProduct",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1706-L1708 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibar.py | python | AuiToolBar.SetToolLabel | (self, tool_id, label) | Sets the tool label for the tool identified by `tool_id`.
:param integer `tool_id`: the tool identifier;
:param string `label`: the new toolbar item label. | Sets the tool label for the tool identified by `tool_id`. | [
"Sets",
"the",
"tool",
"label",
"for",
"the",
"tool",
"identified",
"by",
"tool_id",
"."
] | def SetToolLabel(self, tool_id, label):
"""
Sets the tool label for the tool identified by `tool_id`.
:param integer `tool_id`: the tool identifier;
:param string `label`: the new toolbar item label.
"""
tool = self.FindTool(tool_id)
if tool:
tool.label = label | [
"def",
"SetToolLabel",
"(",
"self",
",",
"tool_id",
",",
"label",
")",
":",
"tool",
"=",
"self",
".",
"FindTool",
"(",
"tool_id",
")",
"if",
"tool",
":",
"tool",
".",
"label",
"=",
"label"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L2727-L2737 | ||
godlikepanos/anki-3d-engine | e2f65e5045624492571ea8527a4dbf3fad8d2c0a | AnKi/Script/LuaGlueGen.py | python | get_base_fname | (path) | return os.path.splitext(os.path.basename(path))[0] | From path/to/a/file.ext return the "file" | From path/to/a/file.ext return the "file" | [
"From",
"path",
"/",
"to",
"/",
"a",
"/",
"file",
".",
"ext",
"return",
"the",
"file"
] | def get_base_fname(path):
""" From path/to/a/file.ext return the "file" """
return os.path.splitext(os.path.basename(path))[0] | [
"def",
"get_base_fname",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]"
] | https://github.com/godlikepanos/anki-3d-engine/blob/e2f65e5045624492571ea8527a4dbf3fad8d2c0a/AnKi/Script/LuaGlueGen.py#L41-L43 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/locators.py | python | Locator._get_project | (self, name) | For a given project, get a dictionary mapping available versions to Distribution
instances.
This should be implemented in subclasses.
If called from a locate() request, self.matcher will be set to a
matcher for the requirement to satisfy, otherwise it will be None. | For a given project, get a dictionary mapping available versions to Distribution
instances. | [
"For",
"a",
"given",
"project",
"get",
"a",
"dictionary",
"mapping",
"available",
"versions",
"to",
"Distribution",
"instances",
"."
] | def _get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distribution
instances.
This should be implemented in subclasses.
If called from a locate() request, self.matcher will be set to a
matcher for the requirement to satisfy, otherwise it will be None.
"""
raise NotImplementedError('Please implement in the subclass') | [
"def",
"_get_project",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Please implement in the subclass'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/locators.py#L153-L163 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeSynthetic.IsClassCode | (self) | return _lldb.SBTypeSynthetic_IsClassCode(self) | IsClassCode(self) -> bool | IsClassCode(self) -> bool | [
"IsClassCode",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsClassCode(self):
"""IsClassCode(self) -> bool"""
return _lldb.SBTypeSynthetic_IsClassCode(self) | [
"def",
"IsClassCode",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBTypeSynthetic_IsClassCode",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11590-L11592 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/internal/pdbx/reader/PdbxContainers.py | python | DataCategory.__formatPdbx | (self, inp) | Format input data following PDBx quoting rules - | Format input data following PDBx quoting rules - | [
"Format",
"input",
"data",
"following",
"PDBx",
"quoting",
"rules",
"-"
] | def __formatPdbx(self, inp):
""" Format input data following PDBx quoting rules -
"""
try:
if (inp is None):
return ("?",'DT_NULL_VALUE')
# pure numerical values are returned as unquoted strings
if (isinstance(inp,int) or self.__intRe.search(str(inp))):
return ( [str(inp)],'DT_INTEGER')
if (isinstance(inp,float) or self.__floatRe.search(str(inp))):
return ([str(inp)],'DT_FLOAT')
# null value handling -
if (inp == "." or inp == "?"):
return ([inp],'DT_NULL_VALUE')
if (inp == ""):
return (["."],'DT_NULL_VALUE')
# Contains white space or quotes ?
if not self.__wsAndQuotesRe.search(inp):
if inp.startswith("_"):
return (self.__doubleQuotedList(inp),'DT_ITEM_NAME')
else:
return ([str(inp)],'DT_UNQUOTED_STRING')
else:
if self.__nlRe.search(inp):
return (self.__semiColonQuotedList(inp),'DT_MULTI_LINE_STRING')
else:
if (self.__avoidEmbeddedQuoting):
# change priority to choose double quoting where possible.
if not self.__dqRe.search(inp) and not self.__sqWsRe.search(inp):
return (self.__doubleQuotedList(inp),'DT_DOUBLE_QUOTED_STRING')
elif not self.__sqRe.search(inp) and not self.__dqWsRe.search(inp):
return (self.__singleQuotedList(inp),'DT_SINGLE_QUOTED_STRING')
else:
return (self.__semiColonQuotedList(inp),'DT_MULTI_LINE_STRING')
else:
# change priority to choose double quoting where possible.
if not self.__dqRe.search(inp):
return (self.__doubleQuotedList(inp),'DT_DOUBLE_QUOTED_STRING')
elif not self.__sqRe.search(inp):
return (self.__singleQuotedList(inp),'DT_SINGLE_QUOTED_STRING')
else:
return (self.__semiColonQuotedList(inp),'DT_MULTI_LINE_STRING')
except:
traceback.print_exc(file=self.__lfh) | [
"def",
"__formatPdbx",
"(",
"self",
",",
"inp",
")",
":",
"try",
":",
"if",
"(",
"inp",
"is",
"None",
")",
":",
"return",
"(",
"\"?\"",
",",
"'DT_NULL_VALUE'",
")",
"# pure numerical values are returned as unquoted strings",
"if",
"(",
"isinstance",
"(",
"inp"... | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/internal/pdbx/reader/PdbxContainers.py#L606-L657 | ||
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | hasher-matcher-actioner/hmalib/lambdas/api/content.py | python | get_content_api | (
dynamodb_table: Table, image_bucket: str, image_prefix: str
) | return content_api | A Closure that includes all dependencies that MUST be provided by the root
API that this API plugs into. Declare dependencies here, but initialize in
the root API alone. | A Closure that includes all dependencies that MUST be provided by the root
API that this API plugs into. Declare dependencies here, but initialize in
the root API alone. | [
"A",
"Closure",
"that",
"includes",
"all",
"dependencies",
"that",
"MUST",
"be",
"provided",
"by",
"the",
"root",
"API",
"that",
"this",
"API",
"plugs",
"into",
".",
"Declare",
"dependencies",
"here",
"but",
"initialize",
"in",
"the",
"root",
"API",
"alone",... | def get_content_api(
dynamodb_table: Table, image_bucket: str, image_prefix: str
) -> bottle.Bottle:
"""
A Closure that includes all dependencies that MUST be provided by the root
API that this API plugs into. Declare dependencies here, but initialize in
the root API alone.
"""
def get_preview_url(content_id, content_object) -> str:
"""
Given a content_id and a content_object, returns a URL you can use to
preview it.
"""
content_object = t.cast(ContentObject, content_object)
preview_url = ""
if content_object.content_ref_type == ContentRefType.DEFAULT_S3_BUCKET:
source = S3BucketContentSource(image_bucket, image_prefix)
preview_url = create_presigned_url(
image_bucket, source.get_s3_key(content_id), None, 3600, "get_object"
)
elif content_object.content_ref_type == ContentRefType.URL:
preview_url = content_object.content_ref
if not preview_url:
return bottle.abort(400, "preview_url not found.")
return preview_url
# A prefix to all routes must be provided by the api_root app
# The documentation below expects prefix to be '/content/'
content_api = SubApp()
@content_api.get("/", apply=[jsoninator])
def content() -> t.Optional[ContentObject]:
"""
Return content object for given ID.
"""
content_id = bottle.request.query.content_id or None
if content_id:
return ContentObject.get_from_content_id(dynamodb_table, content_id)
return None
@content_api.get("/pipeline-progress/", apply=[jsoninator])
def pipeline_progress() -> ContentPipelineProgress:
"""
WARNING: UNOPTIMIZED. DO NOT CALL FROM AUTOMATED SYSTEMS.
Build a history of the stages that this piece of content has gone
through and what their results were. Do not call this from anything but
a UI. This is not optimized for performance.
"""
content_id = bottle.request.query.content_id or None
if not content_id:
return bottle.abort(400, "content_id must be provided.")
content_id = t.cast(str, content_id)
content_object = ContentObject.get_from_content_id(dynamodb_table, content_id)
if not content_object:
return bottle.abort(400, f"Content with id '{content_id}' not found.")
content_object = t.cast(ContentObject, content_object)
preview_url = get_preview_url(content_id, content_object)
# The result object will be gradually built up as records are retrieved.
result = ContentPipelineProgress(
content_id=content_id,
content_type=content_object.content_type,
content_preview_url=preview_url,
submitted_at=content_object.updated_at,
submission_additional_fields=list(content_object.additional_fields),
)
hash_records = PipelineHashRecord.get_from_content_id(
dynamodb_table, content_id
)
if len(hash_records) != 0:
result.hashed_at = max(hash_records, key=lambda r: r.updated_at).updated_at
for hash_record in hash_records:
# Assume that each signal type has a single hash
if hash_record.signal_type.get_name() in result.hash_results:
return bottle.abort(
500,
f"Content with id '{content_id}' has multiple hash records for signal-type: '{hash_record.signal_type.get_name()}'.",
)
result.hash_results[
hash_record.signal_type.get_name()
] = hash_record.content_hash
match_records = MatchRecord.get_from_content_id(dynamodb_table, content_id)
if len(match_records) != 0:
result.matched_at = max(
match_records, key=lambda r: r.updated_at
).updated_at
# TODO #751 Until we resolve type agnostic storage of signal data,
# we can't populate match details.
# actually populate result.match_results.
# TODO: ActionEvaluation does not yet leave a trail. Either record
# action evaluation or remove the evaluation stage from the
# pipeline-progress indicator.
action_records = ActionEvent.get_from_content_id(dynamodb_table, content_id)
if len(action_records) != 0:
result.action_performed_at = max(
action_records, key=lambda r: r.performed_at
).performed_at
result.action_perform_results = [r.action_label for r in action_records]
return result
@content_api.get("/action-history/", apply=[jsoninator])
def action_history() -> ActionHistoryResponse:
"""
Return list of action event records for a given ID.
"""
if content_id := bottle.request.query.content_id or None:
return ActionHistoryResponse(
ActionEvent.get_from_content_id(dynamodb_table, f"{content_id}")
)
return ActionHistoryResponse()
@content_api.get("/hash/", apply=[jsoninator])
def hashes() -> t.Optional[HashResultResponse]:
"""
Return the hash details for a given ID.
"""
content_id = bottle.request.query.content_id or None
if not content_id:
return None
# FIXME: Presently, hash API can only support one hash per content_id
record = PipelineHashRecord.get_from_content_id(
dynamodb_table, f"{content_id}"
)[0]
if not record:
return None
return HashResultResponse(
content_id=record.content_id,
content_hash=record.content_hash,
updated_at=record.updated_at.isoformat(),
)
@content_api.get("/preview-url/", apply=[jsoninator])
def image():
"""
Return the a URL to submitted media for a given ID.
If URL was submitted is it returned
else creates a signed URL for s3 uploads.
Also works for videos.
"""
content_id = bottle.request.query.content_id or None
if not content_id:
return bottle.abort(400, "content_id must be provided.")
content_object: ContentObject = ContentObject.get_from_content_id(
table=dynamodb_table, content_id=content_id
)
if not content_object:
return bottle.abort(404, "content_id does not exist.")
preview_url = get_preview_url(content_id, content_object)
return ContentPreviewResponse(preview_url)
return content_api | [
"def",
"get_content_api",
"(",
"dynamodb_table",
":",
"Table",
",",
"image_bucket",
":",
"str",
",",
"image_prefix",
":",
"str",
")",
"->",
"bottle",
".",
"Bottle",
":",
"def",
"get_preview_url",
"(",
"content_id",
",",
"content_object",
")",
"->",
"str",
":... | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/lambdas/api/content.py#L111-L281 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/command/egg_info.py | python | manifest_maker.write_manifest | (self) | Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'. | Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'. | [
"Write",
"the",
"file",
"list",
"in",
"self",
".",
"filelist",
"(",
"presumably",
"as",
"filled",
"in",
"by",
"add_defaults",
"()",
"and",
"read_template",
"()",
")",
"to",
"the",
"manifest",
"file",
"named",
"by",
"self",
".",
"manifest",
"."
] | def write_manifest (self):
"""Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'.
"""
# The manifest must be UTF-8 encodable. See #303.
if sys.version_info >= (3,):
files = []
for file in self.filelist.files:
try:
file.encode("utf-8")
except UnicodeEncodeError:
log.warn("'%s' not UTF-8 encodable -- skipping" % file)
else:
files.append(file)
self.filelist.files = files
files = self.filelist.files
if os.sep!='/':
files = [f.replace(os.sep,'/') for f in files]
self.execute(write_file, (self.manifest, files),
"writing manifest file '%s'" % self.manifest) | [
"def",
"write_manifest",
"(",
"self",
")",
":",
"# The manifest must be UTF-8 encodable. See #303.",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
")",
":",
"files",
"=",
"[",
"]",
"for",
"file",
"in",
"self",
".",
"filelist",
".",
"files",
":",
"... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/command/egg_info.py#L335-L356 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/device.py | python | merge_device | (spec) | return _device_function | Returns a device function that merges devices specifications.
This can be used to merge partial specifications of devices. The
innermost setting for a device field takes precedence. For example:
with tf.device(merge_device("/device:GPU:0"))
# Nodes created here have device "/device:GPU:0"
with tf.device(merge_device("/job:worker")):
# Nodes created here have device "/job:worker/device:GPU:0"
with tf.device(merge_device("/device:CPU:0")):
# Nodes created here have device "/job:worker/device:CPU:0"
with tf.device(merge_device("/job:ps")):
# Nodes created here have device "/job:ps/device:CPU:0"
Args:
spec: A `DeviceSpec` or a device spec string (partially) describing the
device that should be used for all nodes created in the scope of
the returned device function's with block.
Returns:
A device function with the above-described behavior.
Raises:
ValueError: if the spec was not valid. | Returns a device function that merges devices specifications. | [
"Returns",
"a",
"device",
"function",
"that",
"merges",
"devices",
"specifications",
"."
] | def merge_device(spec):
"""Returns a device function that merges devices specifications.
This can be used to merge partial specifications of devices. The
innermost setting for a device field takes precedence. For example:
with tf.device(merge_device("/device:GPU:0"))
# Nodes created here have device "/device:GPU:0"
with tf.device(merge_device("/job:worker")):
# Nodes created here have device "/job:worker/device:GPU:0"
with tf.device(merge_device("/device:CPU:0")):
# Nodes created here have device "/job:worker/device:CPU:0"
with tf.device(merge_device("/job:ps")):
# Nodes created here have device "/job:ps/device:CPU:0"
Args:
spec: A `DeviceSpec` or a device spec string (partially) describing the
device that should be used for all nodes created in the scope of
the returned device function's with block.
Returns:
A device function with the above-described behavior.
Raises:
ValueError: if the spec was not valid.
"""
if not isinstance(spec, DeviceSpec):
spec = DeviceSpec.from_string(spec or "")
def _device_function(node_def):
current_device = DeviceSpec.from_string(node_def.device or "")
copy_spec = copy.copy(spec)
copy_spec.merge_from(current_device) # current_device takes precedence.
return copy_spec
return _device_function | [
"def",
"merge_device",
"(",
"spec",
")",
":",
"if",
"not",
"isinstance",
"(",
"spec",
",",
"DeviceSpec",
")",
":",
"spec",
"=",
"DeviceSpec",
".",
"from_string",
"(",
"spec",
"or",
"\"\"",
")",
"def",
"_device_function",
"(",
"node_def",
")",
":",
"curre... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/device.py#L255-L288 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/curses/textpad.py | python | Textbox._end_of_line | (self, y) | return last | Go to the location of the first blank on the given line,
returning the index of the last non-blank character. | Go to the location of the first blank on the given line,
returning the index of the last non-blank character. | [
"Go",
"to",
"the",
"location",
"of",
"the",
"first",
"blank",
"on",
"the",
"given",
"line",
"returning",
"the",
"index",
"of",
"the",
"last",
"non",
"-",
"blank",
"character",
"."
] | def _end_of_line(self, y):
"""Go to the location of the first blank on the given line,
returning the index of the last non-blank character."""
last = self.maxx
while True:
if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
last = min(self.maxx, last+1)
break
elif last == 0:
break
last = last - 1
return last | [
"def",
"_end_of_line",
"(",
"self",
",",
"y",
")",
":",
"last",
"=",
"self",
".",
"maxx",
"while",
"True",
":",
"if",
"curses",
".",
"ascii",
".",
"ascii",
"(",
"self",
".",
"win",
".",
"inch",
"(",
"y",
",",
"last",
")",
")",
"!=",
"curses",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/curses/textpad.py#L53-L64 | |
PyMesh/PyMesh | 384ba882b7558ba6e8653ed263c419226c22bddf | python/pymesh/predicates.py | python | in_sphere | (p1, p2, p3, p4, p5) | return PyMesh.insphere(p1, p2, p3, p4, p5) | Determine if p5 is in the sphere formed by p1, p2, p3, p4.
Args:
p1,p2,p3,p4,p5: 3D points. ``orient_3D(p1, p2, p3, p4)`` must be
positive, otherwise the result will be flipped.
Returns:
positive p5 is inside of the sphere.
negative p5 is outside of the sphere.
0.0 if they are cospherical. | Determine if p5 is in the sphere formed by p1, p2, p3, p4. | [
"Determine",
"if",
"p5",
"is",
"in",
"the",
"sphere",
"formed",
"by",
"p1",
"p2",
"p3",
"p4",
"."
] | def in_sphere(p1, p2, p3, p4, p5):
""" Determine if p5 is in the sphere formed by p1, p2, p3, p4.
Args:
p1,p2,p3,p4,p5: 3D points. ``orient_3D(p1, p2, p3, p4)`` must be
positive, otherwise the result will be flipped.
Returns:
positive p5 is inside of the sphere.
negative p5 is outside of the sphere.
0.0 if they are cospherical.
"""
return PyMesh.insphere(p1, p2, p3, p4, p5) | [
"def",
"in_sphere",
"(",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
",",
"p5",
")",
":",
"return",
"PyMesh",
".",
"insphere",
"(",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
",",
"p5",
")"
] | https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/predicates.py#L50-L62 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosmaster/src/rosmaster/broadcast_handler.py | python | byteify | (input) | Convert unicode to str. | Convert unicode to str. | [
"Convert",
"unicode",
"to",
"str",
"."
] | def byteify(input):
"""
Convert unicode to str.
"""
if isinstance(input, dict):
return {byteify(key): byteify(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input | [
"def",
"byteify",
"(",
"input",
")",
":",
"if",
"isinstance",
"(",
"input",
",",
"dict",
")",
":",
"return",
"{",
"byteify",
"(",
"key",
")",
":",
"byteify",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"input",
".",
"iteritems",
"(",
")",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosmaster/src/rosmaster/broadcast_handler.py#L81-L92 | ||
BlueBrain/Brayns | 0133aae76cc2b7f800fc0bfb064400b64fd9b792 | python/brayns/api/function_builder.py | python | build_function | (
client: AbstractClient,
entrypoint: Entrypoint
) | return context['_function'] | Create a function calling the given entrypoint on the given client.
If the entrypoint params are not a oneOf and have properties, the function
will have these properties as keyword arguments.
The function return type is defined by the content of the field 'result' of
the reply that is returned without any processing.
Example: Entrypoint(
title='do-stuff',
params: [{a: int, b: str}],
returns: {c: float}
)
gives def function(a: int, b: str) -> Any
Optional arguments will be defaulted to None.
:param client: Client connected to the renderer
:type client: AbstractClient
:param entrypoint: Entrypoint to call in the function.
:type entrypoint: Entrypoint
:return: Raw entrypoint return value
:rtype: Callable | Create a function calling the given entrypoint on the given client. | [
"Create",
"a",
"function",
"calling",
"the",
"given",
"entrypoint",
"on",
"the",
"given",
"client",
"."
] | def build_function(
client: AbstractClient,
entrypoint: Entrypoint
) -> Callable:
"""Create a function calling the given entrypoint on the given client.
If the entrypoint params are not a oneOf and have properties, the function
will have these properties as keyword arguments.
The function return type is defined by the content of the field 'result' of
the reply that is returned without any processing.
Example: Entrypoint(
title='do-stuff',
params: [{a: int, b: str}],
returns: {c: float}
)
gives def function(a: int, b: str) -> Any
Optional arguments will be defaulted to None.
:param client: Client connected to the renderer
:type client: AbstractClient
:param entrypoint: Entrypoint to call in the function.
:type entrypoint: Entrypoint
:return: Raw entrypoint return value
:rtype: Callable
"""
code = _get_function_code(entrypoint)
context = {
'_get_result': lambda params: _get_result(client, entrypoint, params)
}
exec(code, context)
return context['_function'] | [
"def",
"build_function",
"(",
"client",
":",
"AbstractClient",
",",
"entrypoint",
":",
"Entrypoint",
")",
"->",
"Callable",
":",
"code",
"=",
"_get_function_code",
"(",
"entrypoint",
")",
"context",
"=",
"{",
"'_get_result'",
":",
"lambda",
"params",
":",
"_ge... | https://github.com/BlueBrain/Brayns/blob/0133aae76cc2b7f800fc0bfb064400b64fd9b792/python/brayns/api/function_builder.py#L30-L63 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/ansic/cparse.py | python | p_shift_expression_3 | (t) | shift_expression : shift_expression RSHIFT additive_expression | shift_expression : shift_expression RSHIFT additive_expression | [
"shift_expression",
":",
"shift_expression",
"RSHIFT",
"additive_expression"
] | def p_shift_expression_3(t):
'shift_expression : shift_expression RSHIFT additive_expression'
pass | [
"def",
"p_shift_expression_3",
"(",
"t",
")",
":",
"pass"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L711-L713 | ||
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/yapf/yapf/yapflib/pytree_visitor.py | python | PyTreeVisitor.Visit | (self, node) | Visit a node. | Visit a node. | [
"Visit",
"a",
"node",
"."
] | def Visit(self, node):
"""Visit a node."""
method = 'Visit_{0}'.format(pytree_utils.NodeName(node))
if hasattr(self, method):
# Found a specific visitor for this node
getattr(self, method)(node)
else:
if isinstance(node, pytree.Leaf):
self.DefaultLeafVisit(node)
else:
self.DefaultNodeVisit(node) | [
"def",
"Visit",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"'Visit_{0}'",
".",
"format",
"(",
"pytree_utils",
".",
"NodeName",
"(",
"node",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"method",
")",
":",
"# Found a specific visitor for this node",
... | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/pytree_visitor.py#L57-L67 | ||
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | projects/humans/c3d/controllers/c3d_viewer/c3d.py | python | Writer._write_frames | (self, handle) | Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. | Write our frame data to the given file handle. | [
"Write",
"our",
"frame",
"data",
"to",
"the",
"given",
"file",
"handle",
"."
] | def _write_frames(self, handle):
'''Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
assert handle.tell() == 512 * (self.header.data_block - 1)
scale = abs(self.point_scale)
is_float = self.point_scale < 0
point_dtype = [np.int16, np.float32][is_float]
# point_scale = [scale, 1][is_float]
point_format = 'if'[is_float]
raw = np.empty((self.point_used, 4), point_dtype)
for points, analog in self._frames:
valid = points[:, 3] > -1
raw[~valid, 3] = -1
raw[valid, :3] = points[valid, :3] / self._point_scale
raw[valid, 3] = (
((points[valid, 4]).astype(np.uint8) << 8) |
(points[valid, 3] / scale).astype(np.uint16)
)
point = array.array(point_format)
point.extend(raw.flatten())
point.tofile(handle)
analog = array.array(point_format)
analog.extend(analog)
analog.tofile(handle)
self._pad_block(handle) | [
"def",
"_write_frames",
"(",
"self",
",",
"handle",
")",
":",
"assert",
"handle",
".",
"tell",
"(",
")",
"==",
"512",
"*",
"(",
"self",
".",
"header",
".",
"data_block",
"-",
"1",
")",
"scale",
"=",
"abs",
"(",
"self",
".",
"point_scale",
")",
"is_... | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/humans/c3d/controllers/c3d_viewer/c3d.py#L986-L1016 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/parallel_for/pfor.py | python | _unflatten_first_dim | (x, first_dim) | return array_ops.reshape(x, new_shape) | Splits first dimension into [first_dim, -1]. | Splits first dimension into [first_dim, -1]. | [
"Splits",
"first",
"dimension",
"into",
"[",
"first_dim",
"-",
"1",
"]",
"."
] | def _unflatten_first_dim(x, first_dim):
"""Splits first dimension into [first_dim, -1]."""
old_shape = array_ops.shape(x)
new_shape = array_ops.concat([first_dim, [-1], old_shape[1:]], axis=0)
return array_ops.reshape(x, new_shape) | [
"def",
"_unflatten_first_dim",
"(",
"x",
",",
"first_dim",
")",
":",
"old_shape",
"=",
"array_ops",
".",
"shape",
"(",
"x",
")",
"new_shape",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"first_dim",
",",
"[",
"-",
"1",
"]",
",",
"old_shape",
"[",
"1",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/parallel_for/pfor.py#L1744-L1748 | |
kiwix/kiwix-xulrunner | 38f4a10ae4b1585c16cb11730bb0dcc4924ae19f | android/gen-custom-android-build.py | python | step_list_output_apk | (jsdata, **options) | ls on the expected APK to check presence and size | ls on the expected APK to check presence and size | [
"ls",
"on",
"the",
"expected",
"APK",
"to",
"check",
"presence",
"and",
"size"
] | def step_list_output_apk(jsdata, **options):
""" ls on the expected APK to check presence and size """
move_to_current_folder()
syscall('ls -lh build/outputs/apk/{}-*'
.format(jsdata.get('package')), shell=True) | [
"def",
"step_list_output_apk",
"(",
"jsdata",
",",
"*",
"*",
"options",
")",
":",
"move_to_current_folder",
"(",
")",
"syscall",
"(",
"'ls -lh build/outputs/apk/{}-*'",
".",
"format",
"(",
"jsdata",
".",
"get",
"(",
"'package'",
")",
")",
",",
"shell",
"=",
... | https://github.com/kiwix/kiwix-xulrunner/blob/38f4a10ae4b1585c16cb11730bb0dcc4924ae19f/android/gen-custom-android-build.py#L557-L563 | ||
espressomd/espresso | 7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a | src/python/espressomd/io/mpiio.py | python | Mpiio.read | (self, prefix=None, positions=False, velocities=False,
types=False, bonds=False) | MPI-IO read.
This function reads data dumped by :meth`write`. See the :meth`write`
documentation for details.
.. note::
The files must be read on the same number of processes that wrote
the data. The data must be read on a machine with the same
architecture (otherwise, this might silently fail). | MPI-IO read. | [
"MPI",
"-",
"IO",
"read",
"."
] | def read(self, prefix=None, positions=False, velocities=False,
types=False, bonds=False):
"""MPI-IO read.
This function reads data dumped by :meth`write`. See the :meth`write`
documentation for details.
.. note::
The files must be read on the same number of processes that wrote
the data. The data must be read on a machine with the same
architecture (otherwise, this might silently fail).
"""
if prefix is None:
raise ValueError(
"Need to supply output prefix via the 'prefix' argument.")
if not positions and not velocities and not types and not bonds:
raise ValueError("No output fields chosen.")
self._instance.call_method(
"read", prefix=prefix, pos=positions, vel=velocities, typ=types, bond=bonds) | [
"def",
"read",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"positions",
"=",
"False",
",",
"velocities",
"=",
"False",
",",
"types",
"=",
"False",
",",
"bonds",
"=",
"False",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"raise",
"ValueError",
"(",
... | https://github.com/espressomd/espresso/blob/7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a/src/python/espressomd/io/mpiio.py#L81-L100 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/dataframe/series.py | python | Series.register_binary_op | (cls, series_method_name) | return register | A decorator that registers `Transform`s as `Series` member functions.
For example:
'''
@series.Series.register_binary_op("__add___")
class Sum(Transform):
...
'''
The registered member function takes `args` and `kwargs`. These values will
be passed to the `__init__` function for the decorated `Transform`.
Args:
series_method_name: the name under which to register the function.
Returns:
Decorator function.
Raises:
ValueError: another `Transform` is already registered under
`series_method_name`. | A decorator that registers `Transform`s as `Series` member functions. | [
"A",
"decorator",
"that",
"registers",
"Transform",
"s",
"as",
"Series",
"member",
"functions",
"."
] | def register_binary_op(cls, series_method_name):
"""A decorator that registers `Transform`s as `Series` member functions.
For example:
'''
@series.Series.register_binary_op("__add___")
class Sum(Transform):
...
'''
The registered member function takes `args` and `kwargs`. These values will
be passed to the `__init__` function for the decorated `Transform`.
Args:
series_method_name: the name under which to register the function.
Returns:
Decorator function.
Raises:
ValueError: another `Transform` is already registered under
`series_method_name`.
"""
def register(transform_cls):
if hasattr(cls, series_method_name):
raise ValueError("Series already has a function registered as %s.",
series_method_name)
def _member_func(slf, b, *args, **kwargs):
return transform_cls(*args, **kwargs)([slf, b])[0]
setattr(cls, series_method_name, _member_func)
return transform_cls
return register | [
"def",
"register_binary_op",
"(",
"cls",
",",
"series_method_name",
")",
":",
"def",
"register",
"(",
"transform_cls",
")",
":",
"if",
"hasattr",
"(",
"cls",
",",
"series_method_name",
")",
":",
"raise",
"ValueError",
"(",
"\"Series already has a function registered... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/dataframe/series.py#L71-L101 | |
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/xcodeproj_file.py | python | XCObject._XCKVPrint | (self, file, tabs, key, value) | Prints a key and value, members of an XCObject's _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by a space insead of a newline. | Prints a key and value, members of an XCObject's _properties dictionary,
to file. | [
"Prints",
"a",
"key",
"and",
"value",
"members",
"of",
"an",
"XCObject",
"s",
"_properties",
"dictionary",
"to",
"file",
"."
] | def _XCKVPrint(self, file, tabs, key, value):
"""Prints a key and value, members of an XCObject's _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by a space insead of a newline.
"""
if self._should_print_single_line:
printable = ''
after_kv = ' '
else:
printable = '\t' * tabs
after_kv = '\n'
# Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy
# objects without comments. Sometimes it prints them with comments, but
# the majority of the time, it doesn't. To avoid unnecessary changes to
# the project file after Xcode opens it, don't write comments for
# remoteGlobalIDString. This is a sucky hack and it would certainly be
# cleaner to extend the schema to indicate whether or not a comment should
# be printed, but since this is the only case where the problem occurs and
# Xcode itself can't seem to make up its mind, the hack will suffice.
#
# Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].
if key == 'remoteGlobalIDString' and isinstance(self,
PBXContainerItemProxy):
value_to_print = value.id
else:
value_to_print = value
# PBXBuildFile's settings property is represented in the output as a dict,
# but a hack here has it represented as a string. Arrange to strip off the
# quotes so that it shows up in the output as expected.
if key == 'settings' and isinstance(self, PBXBuildFile):
strip_value_quotes = True
else:
strip_value_quotes = False
# In another one-off, let's set flatten_list on buildSettings properties
# of XCBuildConfiguration objects, because that's how Xcode treats them.
if key == 'buildSettings' and isinstance(self, XCBuildConfiguration):
flatten_list = True
else:
flatten_list = False
try:
printable_key = self._XCPrintableValue(tabs, key, flatten_list)
printable_value = self._XCPrintableValue(tabs, value_to_print,
flatten_list)
if strip_value_quotes and len(printable_value) > 1 and \
printable_value[0] == '"' and printable_value[-1] == '"':
printable_value = printable_value[1:-1]
printable += printable_key + ' = ' + printable_value + ';' + after_kv
except TypeError, e:
gyp.common.ExceptionAppend(e,
'while printing key "%s"' % key)
raise
self._XCPrint(file, 0, printable) | [
"def",
"_XCKVPrint",
"(",
"self",
",",
"file",
",",
"tabs",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"_should_print_single_line",
":",
"printable",
"=",
"''",
"after_kv",
"=",
"' '",
"else",
":",
"printable",
"=",
"'\\t'",
"*",
"tabs",
"a... | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/xcodeproj_file.py#L639-L699 | ||
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/layer.py | python | MaxPool2d.__init__ | (self, kernel_size, stride=None, padding=0, pad_mode="NOTSET") | Args:
kernel_size (int or tuple): kernel size for two direction of each
axis. For example, (2, 3), the first 2 means will add 2 at the
beginning and also 2 at the end for its axis.and if a int is
accepted, the kernel size will be initiated as (int, int)
stride (int or tuple): stride, the logic is the same as kernel size.
padding (int): tuple, list or None, padding, the logic is the same
as kernel size. However, if you set pad_mode as "SAME_UPPER" or
"SAME_LOWER" mode, you can set padding as None, and the padding
will be computed automatically.
pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where
default value is NOTSET, which means explicit padding is used.
SAME_UPPER or SAME_LOWER mean pad the input so that the output
spatial size match the input. In case of odd number add the extra
padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. | Args:
kernel_size (int or tuple): kernel size for two direction of each
axis. For example, (2, 3), the first 2 means will add 2 at the
beginning and also 2 at the end for its axis.and if a int is
accepted, the kernel size will be initiated as (int, int)
stride (int or tuple): stride, the logic is the same as kernel size.
padding (int): tuple, list or None, padding, the logic is the same
as kernel size. However, if you set pad_mode as "SAME_UPPER" or
"SAME_LOWER" mode, you can set padding as None, and the padding
will be computed automatically.
pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where
default value is NOTSET, which means explicit padding is used.
SAME_UPPER or SAME_LOWER mean pad the input so that the output
spatial size match the input. In case of odd number add the extra
padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. | [
"Args",
":",
"kernel_size",
"(",
"int",
"or",
"tuple",
")",
":",
"kernel",
"size",
"for",
"two",
"direction",
"of",
"each",
"axis",
".",
"For",
"example",
"(",
"2",
"3",
")",
"the",
"first",
"2",
"means",
"will",
"add",
"2",
"at",
"the",
"beginning",... | def __init__(self, kernel_size, stride=None, padding=0, pad_mode="NOTSET"):
"""
Args:
kernel_size (int or tuple): kernel size for two direction of each
axis. For example, (2, 3), the first 2 means will add 2 at the
beginning and also 2 at the end for its axis.and if a int is
accepted, the kernel size will be initiated as (int, int)
stride (int or tuple): stride, the logic is the same as kernel size.
padding (int): tuple, list or None, padding, the logic is the same
as kernel size. However, if you set pad_mode as "SAME_UPPER" or
"SAME_LOWER" mode, you can set padding as None, and the padding
will be computed automatically.
pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where
default value is NOTSET, which means explicit padding is used.
SAME_UPPER or SAME_LOWER mean pad the input so that the output
spatial size match the input. In case of odd number add the extra
padding at the end for SAME_UPPER and at the beginning for SAME_LOWER.
"""
super(MaxPool2d, self).__init__(kernel_size, stride, padding, True,
pad_mode) | [
"def",
"__init__",
"(",
"self",
",",
"kernel_size",
",",
"stride",
"=",
"None",
",",
"padding",
"=",
"0",
",",
"pad_mode",
"=",
"\"NOTSET\"",
")",
":",
"super",
"(",
"MaxPool2d",
",",
"self",
")",
".",
"__init__",
"(",
"kernel_size",
",",
"stride",
","... | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/layer.py#L1011-L1030 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Frontends/VBoxShell/vboxshell.py | python | nicCableSubCmd | (ctx, vm, nicnum, adapter, args) | return nicSwitchOnOff(adapter, 'cableConnected', args) | usage: nic <vm> <nicnum> cable [on|off] | usage: nic <vm> <nicnum> cable [on|off] | [
"usage",
":",
"nic",
"<vm",
">",
"<nicnum",
">",
"cable",
"[",
"on|off",
"]"
] | def nicCableSubCmd(ctx, vm, nicnum, adapter, args):
'''
usage: nic <vm> <nicnum> cable [on|off]
'''
return nicSwitchOnOff(adapter, 'cableConnected', args) | [
"def",
"nicCableSubCmd",
"(",
"ctx",
",",
"vm",
",",
"nicnum",
",",
"adapter",
",",
"args",
")",
":",
"return",
"nicSwitchOnOff",
"(",
"adapter",
",",
"'cableConnected'",
",",
"args",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Frontends/VBoxShell/vboxshell.py#L2959-L2963 | |
microsoft/DirectX-Graphics-Samples | 316de71537a460f9b90a51b145d9fb9d67f5e7b8 | MiniEngine/Tools/Scripts/CreateNewProject.py | python | copy_template_file | (filename, project, guid) | Copies one template file and replaces templated values | Copies one template file and replaces templated values | [
"Copies",
"one",
"template",
"file",
"and",
"replaces",
"templated",
"values"
] | def copy_template_file(filename, project, guid):
'''Copies one template file and replaces templated values'''
template_filename = os.path.join(TEMPLATES_FOLDER, filename)
output_filename = os.path.join(project, filename)
output_filename = output_filename.replace('AppTemplate', project)
output_filename = output_filename.replace('LibTemplate', project)
with open(template_filename, 'r', encoding='utf-8') as infile:
with open(output_filename, 'w', encoding='utf-8') as outfile:
contents = infile.read()
contents = contents.replace('TEMPLATE_NAME', project)
contents = contents.replace('TEMPLATE_GUID', guid)
outfile.write(contents) | [
"def",
"copy_template_file",
"(",
"filename",
",",
"project",
",",
"guid",
")",
":",
"template_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"TEMPLATES_FOLDER",
",",
"filename",
")",
"output_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"proj... | https://github.com/microsoft/DirectX-Graphics-Samples/blob/316de71537a460f9b90a51b145d9fb9d67f5e7b8/MiniEngine/Tools/Scripts/CreateNewProject.py#L22-L33 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/TOFTOFCropWorkspace.py | python | TOFTOFCropWorkspace.PyInit | (self) | return | Declare properties | Declare properties | [
"Declare",
"properties"
] | def PyInit(self):
""" Declare properties
"""
# better would be to use the validator, but it fails if WorkspaceGroup is given as an input
# self.declareProperty(WorkspaceProperty("InputWorkspace", "", direction=Direction.Input,
# validator=WorkspaceUnitValidator('TOF')),
# doc="Input workspace.")
self.declareProperty(WorkspaceProperty("InputWorkspace", "", direction=Direction.Input),
doc="Input workspace.")
self.declareProperty(WorkspaceProperty("OutputWorkspace", "", direction=Direction.Output),
doc="Name of the workspace that will contain the results")
return | [
"def",
"PyInit",
"(",
"self",
")",
":",
"# better would be to use the validator, but it fails if WorkspaceGroup is given as an input",
"# self.declareProperty(WorkspaceProperty(\"InputWorkspace\", \"\", direction=Direction.Input,",
"# validator=WorkspaceUnitVali... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/TOFTOFCropWorkspace.py#L35-L46 | |
QMCPACK/qmcpack | d0948ab455e38364458740cc8e2239600a14c5cd | nexus/lib/grid_functions.py | python | StructuredGrid.unit_metric | (self,upoints=None) | return self.unit_metric_bare(upoints) | (`External API`) Compute the integration metric in the unit coordinate
space for a set of points defined there.
Parameters
----------
upoints : `array_like, float, shape (N,d), optional`
Array of points in the unit coordinate space. `N` is the number
of points and `d` must be equal to `grid_dim`. The unit
representation of the grid points is used if no points are
provided.
Returns
-------
umetric : `ndarray, float, shape (N,)`
Array containing the integration metric in the unit space at the
set of points provided. `N` is the number of points. | (`External API`) Compute the integration metric in the unit coordinate
space for a set of points defined there. | [
"(",
"External",
"API",
")",
"Compute",
"the",
"integration",
"metric",
"in",
"the",
"unit",
"coordinate",
"space",
"for",
"a",
"set",
"of",
"points",
"defined",
"there",
"."
] | def unit_metric(self,upoints=None):
"""
(`External API`) Compute the integration metric in the unit coordinate
space for a set of points defined there.
Parameters
----------
upoints : `array_like, float, shape (N,d), optional`
Array of points in the unit coordinate space. `N` is the number
of points and `d` must be equal to `grid_dim`. The unit
representation of the grid points is used if no points are
provided.
Returns
-------
umetric : `ndarray, float, shape (N,)`
Array containing the integration metric in the unit space at the
set of points provided. `N` is the number of points.
"""
return self.unit_metric_bare(upoints) | [
"def",
"unit_metric",
"(",
"self",
",",
"upoints",
"=",
"None",
")",
":",
"return",
"self",
".",
"unit_metric_bare",
"(",
"upoints",
")"
] | https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/nexus/lib/grid_functions.py#L1551-L1570 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Spinbox.selection_element | (self, element=None) | return self.selection("element", element) | Sets or gets the currently selected element.
If a spinbutton element is specified, it will be
displayed depressed | Sets or gets the currently selected element. | [
"Sets",
"or",
"gets",
"the",
"currently",
"selected",
"element",
"."
] | def selection_element(self, element=None):
"""Sets or gets the currently selected element.
If a spinbutton element is specified, it will be
displayed depressed
"""
return self.selection("element", element) | [
"def",
"selection_element",
"(",
"self",
",",
"element",
"=",
"None",
")",
":",
"return",
"self",
".",
"selection",
"(",
"\"element\"",
",",
"element",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L3519-L3525 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/feature.py | python | implied_feature | (implicit_value) | return __implicit_features[components[0]] | Returns the implicit feature associated with the given implicit value. | Returns the implicit feature associated with the given implicit value. | [
"Returns",
"the",
"implicit",
"feature",
"associated",
"with",
"the",
"given",
"implicit",
"value",
"."
] | def implied_feature (implicit_value):
""" Returns the implicit feature associated with the given implicit value.
"""
assert isinstance(implicit_value, basestring)
components = implicit_value.split('-')
if components[0] not in __implicit_features:
raise InvalidValue ("'%s' is not a value of an implicit feature" % implicit_value)
return __implicit_features[components[0]] | [
"def",
"implied_feature",
"(",
"implicit_value",
")",
":",
"assert",
"isinstance",
"(",
"implicit_value",
",",
"basestring",
")",
"components",
"=",
"implicit_value",
".",
"split",
"(",
"'-'",
")",
"if",
"components",
"[",
"0",
"]",
"not",
"in",
"__implicit_fe... | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/feature.py#L243-L252 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.