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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-students-taking-exam.py | python | bipartiteMatch | (graph) | Find maximum cardinality matching of a bipartite graph (U,V,E).
The input format is a dictionary mapping members of U to a list
of their neighbors in V. The output is a triple (M,A,B) where M is a
dictionary mapping members of V to their matches in U, A is the part
of the maximum independent set in U, and B is the part of the MIS in V.
The same object may occur in both U and V, and is treated as two
distinct vertices if this happens. | Find maximum cardinality matching of a bipartite graph (U,V,E).
The input format is a dictionary mapping members of U to a list
of their neighbors in V. The output is a triple (M,A,B) where M is a
dictionary mapping members of V to their matches in U, A is the part
of the maximum independent set in U, and B is the part of the MIS in V.
The same object may occur in both U and V, and is treated as two
distinct vertices if this happens. | [
"Find",
"maximum",
"cardinality",
"matching",
"of",
"a",
"bipartite",
"graph",
"(",
"U",
"V",
"E",
")",
".",
"The",
"input",
"format",
"is",
"a",
"dictionary",
"mapping",
"members",
"of",
"U",
"to",
"a",
"list",
"of",
"their",
"neighbors",
"in",
"V",
".",
"The",
"output",
"is",
"a",
"triple",
"(",
"M",
"A",
"B",
")",
"where",
"M",
"is",
"a",
"dictionary",
"mapping",
"members",
"of",
"V",
"to",
"their",
"matches",
"in",
"U",
"A",
"is",
"the",
"part",
"of",
"the",
"maximum",
"independent",
"set",
"in",
"U",
"and",
"B",
"is",
"the",
"part",
"of",
"the",
"MIS",
"in",
"V",
".",
"The",
"same",
"object",
"may",
"occur",
"in",
"both",
"U",
"and",
"V",
"and",
"is",
"treated",
"as",
"two",
"distinct",
"vertices",
"if",
"this",
"happens",
"."
] | def bipartiteMatch(graph):
'''Find maximum cardinality matching of a bipartite graph (U,V,E).
The input format is a dictionary mapping members of U to a list
of their neighbors in V. The output is a triple (M,A,B) where M is a
dictionary mapping members of V to their matches in U, A is the part
of the maximum independent set in U, and B is the part of the MIS in V.
The same object may occur in both U and V, and is treated as two
distinct vertices if this happens.'''
# initialize greedy matching (redundant, but faster than full search)
matching = {}
for u in graph:
for v in graph[u]:
if v not in matching:
matching[v] = u
break
while 1:
# structure residual graph into layers
# pred[u] gives the neighbor in the previous layer for u in U
# preds[v] gives a list of neighbors in the previous layer for v in V
# unmatched gives a list of unmatched vertices in final layer of V,
# and is also used as a flag value for pred[u] when u is in the first layer
preds = {}
unmatched = []
pred = dict([(u,unmatched) for u in graph])
for v in matching:
del pred[matching[v]]
layer = list(pred)
# repeatedly extend layering structure by another pair of layers
while layer and not unmatched:
newLayer = {}
for u in layer:
for v in graph[u]:
if v not in preds:
newLayer.setdefault(v,[]).append(u)
layer = []
for v in newLayer:
preds[v] = newLayer[v]
if v in matching:
layer.append(matching[v])
pred[matching[v]] = v
else:
unmatched.append(v)
# did we finish layering without finding any alternating paths?
if not unmatched:
unlayered = {}
for u in graph:
for v in graph[u]:
if v not in preds:
unlayered[v] = None
return (matching,list(pred),list(unlayered))
# recursively search backward through layers to find alternating paths
# recursion returns true if found path, false otherwise
def recurse(v):
if v in preds:
L = preds[v]
del preds[v]
for u in L:
if u in pred:
pu = pred[u]
del pred[u]
if pu is unmatched or recurse(pu):
matching[v] = u
return 1
return 0
def recurse_iter(v):
def divide(v):
if v not in preds:
return
L = preds[v]
del preds[v]
for u in L :
if u in pred and pred[u] is unmatched: # early return
del pred[u]
matching[v] = u
ret[0] = True
return
stk.append(partial(conquer, v, iter(L)))
def conquer(v, it):
for u in it:
if u not in pred:
continue
pu = pred[u]
del pred[u]
stk.append(partial(postprocess, v, u, it))
stk.append(partial(divide, pu))
return
def postprocess(v, u, it):
if not ret[0]:
stk.append(partial(conquer, v, it))
return
matching[v] = u
ret, stk = [False], []
stk.append(partial(divide, v))
while stk:
stk.pop()()
return ret[0]
for v in unmatched: recurse_iter(v) | [
"def",
"bipartiteMatch",
"(",
"graph",
")",
":",
"# initialize greedy matching (redundant, but faster than full search)",
"matching",
"=",
"{",
"}",
"for",
"u",
"in",
"graph",
":",
"for",
"v",
"in",
"graph",
"[",
"u",
"]",
":",
"if",
"v",
"not",
"in",
"matching",
":",
"matching",
"[",
"v",
"]",
"=",
"u",
"break",
"while",
"1",
":",
"# structure residual graph into layers",
"# pred[u] gives the neighbor in the previous layer for u in U",
"# preds[v] gives a list of neighbors in the previous layer for v in V",
"# unmatched gives a list of unmatched vertices in final layer of V,",
"# and is also used as a flag value for pred[u] when u is in the first layer",
"preds",
"=",
"{",
"}",
"unmatched",
"=",
"[",
"]",
"pred",
"=",
"dict",
"(",
"[",
"(",
"u",
",",
"unmatched",
")",
"for",
"u",
"in",
"graph",
"]",
")",
"for",
"v",
"in",
"matching",
":",
"del",
"pred",
"[",
"matching",
"[",
"v",
"]",
"]",
"layer",
"=",
"list",
"(",
"pred",
")",
"# repeatedly extend layering structure by another pair of layers",
"while",
"layer",
"and",
"not",
"unmatched",
":",
"newLayer",
"=",
"{",
"}",
"for",
"u",
"in",
"layer",
":",
"for",
"v",
"in",
"graph",
"[",
"u",
"]",
":",
"if",
"v",
"not",
"in",
"preds",
":",
"newLayer",
".",
"setdefault",
"(",
"v",
",",
"[",
"]",
")",
".",
"append",
"(",
"u",
")",
"layer",
"=",
"[",
"]",
"for",
"v",
"in",
"newLayer",
":",
"preds",
"[",
"v",
"]",
"=",
"newLayer",
"[",
"v",
"]",
"if",
"v",
"in",
"matching",
":",
"layer",
".",
"append",
"(",
"matching",
"[",
"v",
"]",
")",
"pred",
"[",
"matching",
"[",
"v",
"]",
"]",
"=",
"v",
"else",
":",
"unmatched",
".",
"append",
"(",
"v",
")",
"# did we finish layering without finding any alternating paths?",
"if",
"not",
"unmatched",
":",
"unlayered",
"=",
"{",
"}",
"for",
"u",
"in",
"graph",
":",
"for",
"v",
"in",
"graph",
"[",
"u",
"]",
":",
"if",
"v",
"not",
"in",
"preds",
":",
"unlayered",
"[",
"v",
"]",
"=",
"None",
"return",
"(",
"matching",
",",
"list",
"(",
"pred",
")",
",",
"list",
"(",
"unlayered",
")",
")",
"# recursively search backward through layers to find alternating paths",
"# recursion returns true if found path, false otherwise",
"def",
"recurse",
"(",
"v",
")",
":",
"if",
"v",
"in",
"preds",
":",
"L",
"=",
"preds",
"[",
"v",
"]",
"del",
"preds",
"[",
"v",
"]",
"for",
"u",
"in",
"L",
":",
"if",
"u",
"in",
"pred",
":",
"pu",
"=",
"pred",
"[",
"u",
"]",
"del",
"pred",
"[",
"u",
"]",
"if",
"pu",
"is",
"unmatched",
"or",
"recurse",
"(",
"pu",
")",
":",
"matching",
"[",
"v",
"]",
"=",
"u",
"return",
"1",
"return",
"0",
"def",
"recurse_iter",
"(",
"v",
")",
":",
"def",
"divide",
"(",
"v",
")",
":",
"if",
"v",
"not",
"in",
"preds",
":",
"return",
"L",
"=",
"preds",
"[",
"v",
"]",
"del",
"preds",
"[",
"v",
"]",
"for",
"u",
"in",
"L",
":",
"if",
"u",
"in",
"pred",
"and",
"pred",
"[",
"u",
"]",
"is",
"unmatched",
":",
"# early return",
"del",
"pred",
"[",
"u",
"]",
"matching",
"[",
"v",
"]",
"=",
"u",
"ret",
"[",
"0",
"]",
"=",
"True",
"return",
"stk",
".",
"append",
"(",
"partial",
"(",
"conquer",
",",
"v",
",",
"iter",
"(",
"L",
")",
")",
")",
"def",
"conquer",
"(",
"v",
",",
"it",
")",
":",
"for",
"u",
"in",
"it",
":",
"if",
"u",
"not",
"in",
"pred",
":",
"continue",
"pu",
"=",
"pred",
"[",
"u",
"]",
"del",
"pred",
"[",
"u",
"]",
"stk",
".",
"append",
"(",
"partial",
"(",
"postprocess",
",",
"v",
",",
"u",
",",
"it",
")",
")",
"stk",
".",
"append",
"(",
"partial",
"(",
"divide",
",",
"pu",
")",
")",
"return",
"def",
"postprocess",
"(",
"v",
",",
"u",
",",
"it",
")",
":",
"if",
"not",
"ret",
"[",
"0",
"]",
":",
"stk",
".",
"append",
"(",
"partial",
"(",
"conquer",
",",
"v",
",",
"it",
")",
")",
"return",
"matching",
"[",
"v",
"]",
"=",
"u",
"ret",
",",
"stk",
"=",
"[",
"False",
"]",
",",
"[",
"]",
"stk",
".",
"append",
"(",
"partial",
"(",
"divide",
",",
"v",
")",
")",
"while",
"stk",
":",
"stk",
".",
"pop",
"(",
")",
"(",
")",
"return",
"ret",
"[",
"0",
"]",
"for",
"v",
"in",
"unmatched",
":",
"recurse_iter",
"(",
"v",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-students-taking-exam.py#L17-L123 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/pipes.py | python | Template.append | (self, cmd, kind) | t.append(cmd, kind) adds a new step at the end. | t.append(cmd, kind) adds a new step at the end. | [
"t",
".",
"append",
"(",
"cmd",
"kind",
")",
"adds",
"a",
"new",
"step",
"at",
"the",
"end",
"."
] | def append(self, cmd, kind):
"""t.append(cmd, kind) adds a new step at the end."""
if type(cmd) is not type(''):
raise TypeError('Template.append: cmd must be a string')
if kind not in stepkinds:
raise ValueError('Template.append: bad kind %r' % (kind,))
if kind == SOURCE:
raise ValueError('Template.append: SOURCE can only be prepended')
if self.steps and self.steps[-1][1] == SINK:
raise ValueError('Template.append: already ends with SINK')
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
raise ValueError('Template.append: missing $IN in cmd')
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
raise ValueError('Template.append: missing $OUT in cmd')
self.steps.append((cmd, kind)) | [
"def",
"append",
"(",
"self",
",",
"cmd",
",",
"kind",
")",
":",
"if",
"type",
"(",
"cmd",
")",
"is",
"not",
"type",
"(",
"''",
")",
":",
"raise",
"TypeError",
"(",
"'Template.append: cmd must be a string'",
")",
"if",
"kind",
"not",
"in",
"stepkinds",
":",
"raise",
"ValueError",
"(",
"'Template.append: bad kind %r'",
"%",
"(",
"kind",
",",
")",
")",
"if",
"kind",
"==",
"SOURCE",
":",
"raise",
"ValueError",
"(",
"'Template.append: SOURCE can only be prepended'",
")",
"if",
"self",
".",
"steps",
"and",
"self",
".",
"steps",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"==",
"SINK",
":",
"raise",
"ValueError",
"(",
"'Template.append: already ends with SINK'",
")",
"if",
"kind",
"[",
"0",
"]",
"==",
"'f'",
"and",
"not",
"re",
".",
"search",
"(",
"r'\\$IN\\b'",
",",
"cmd",
")",
":",
"raise",
"ValueError",
"(",
"'Template.append: missing $IN in cmd'",
")",
"if",
"kind",
"[",
"1",
"]",
"==",
"'f'",
"and",
"not",
"re",
".",
"search",
"(",
"r'\\$OUT\\b'",
",",
"cmd",
")",
":",
"raise",
"ValueError",
"(",
"'Template.append: missing $OUT in cmd'",
")",
"self",
".",
"steps",
".",
"append",
"(",
"(",
"cmd",
",",
"kind",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pipes.py#L110-L124 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/tensor_util.py | python | make_tensor_proto | (values, dtype=None, shape=None, verify_shape=False) | return tensor_proto | Create a TensorProto.
Args:
values: Values to put in the TensorProto.
dtype: Optional tensor_pb2 DataType value.
shape: List of integers representing the dimensions of tensor.
verify_shape: Boolean that enables verification of a shape of values.
Returns:
A `TensorProto`. Depending on the type, it may contain data in the
"tensor_content" attribute, which is not directly useful to Python programs.
To access the values you should convert the proto back to a numpy ndarray
with `tensor_util.MakeNdarray(proto)`.
If `values` is a `TensorProto`, it is immediately returned; `dtype` and
`shape` are ignored.
Raises:
TypeError: if unsupported types are provided.
ValueError: if arguments have inappropriate values or if verify_shape is
True and shape of values is not equals to a shape from the argument.
make_tensor_proto accepts "values" of a python scalar, a python list, a
numpy ndarray, or a numpy scalar.
If "values" is a python scalar or a python list, make_tensor_proto
first convert it to numpy ndarray. If dtype is None, the
conversion tries its best to infer the right numpy data
type. Otherwise, the resulting numpy array has a compatible data
type with the given dtype.
In either case above, the numpy ndarray (either the caller provided
or the auto converted) must have the compatible type with dtype.
make_tensor_proto then converts the numpy array to a tensor proto.
If "shape" is None, the resulting tensor proto represents the numpy
array precisely.
Otherwise, "shape" specifies the tensor's shape and the numpy array
can not have more elements than what "shape" specifies. | Create a TensorProto. | [
"Create",
"a",
"TensorProto",
"."
] | def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False):
"""Create a TensorProto.
Args:
values: Values to put in the TensorProto.
dtype: Optional tensor_pb2 DataType value.
shape: List of integers representing the dimensions of tensor.
verify_shape: Boolean that enables verification of a shape of values.
Returns:
A `TensorProto`. Depending on the type, it may contain data in the
"tensor_content" attribute, which is not directly useful to Python programs.
To access the values you should convert the proto back to a numpy ndarray
with `tensor_util.MakeNdarray(proto)`.
If `values` is a `TensorProto`, it is immediately returned; `dtype` and
`shape` are ignored.
Raises:
TypeError: if unsupported types are provided.
ValueError: if arguments have inappropriate values or if verify_shape is
True and shape of values is not equals to a shape from the argument.
make_tensor_proto accepts "values" of a python scalar, a python list, a
numpy ndarray, or a numpy scalar.
If "values" is a python scalar or a python list, make_tensor_proto
first convert it to numpy ndarray. If dtype is None, the
conversion tries its best to infer the right numpy data
type. Otherwise, the resulting numpy array has a compatible data
type with the given dtype.
In either case above, the numpy ndarray (either the caller provided
or the auto converted) must have the compatible type with dtype.
make_tensor_proto then converts the numpy array to a tensor proto.
If "shape" is None, the resulting tensor proto represents the numpy
array precisely.
Otherwise, "shape" specifies the tensor's shape and the numpy array
can not have more elements than what "shape" specifies.
"""
if isinstance(values, tensor_pb2.TensorProto):
return values
if dtype:
dtype = dtypes.as_dtype(dtype)
is_quantized = (dtype in [dtypes.qint8, dtypes.quint8, dtypes.qint16,
dtypes.quint16, dtypes.qint32])
# We first convert value to a numpy array or scalar.
if isinstance(values, (np.ndarray, np.generic)):
if dtype:
nparray = values.astype(dtype.as_numpy_dtype)
else:
nparray = values
elif callable(getattr(values, "__array__", None)) or isinstance(
getattr(values, "__array_interface__", None), dict):
# If a class has the __array__ method, or __array_interface__ dict, then it
# is possible to convert to numpy array.
nparray = np.asarray(values, dtype=dtype)
# This is the preferred way to create an array from the object, so replace
# the `values` with the array so that _FlattenToStrings is not run.
values = nparray
else:
if values is None:
raise ValueError("None values not supported.")
# if dtype is provided, forces numpy array to be the type
# provided if possible.
if dtype and dtype.is_numpy_compatible:
np_dt = dtype.as_numpy_dtype
else:
np_dt = None
# If shape is None, numpy.prod returns None when dtype is not set, but raises
# exception when dtype is set to np.int64
if shape is not None and np.prod(shape, dtype=np.int64) == 0:
nparray = np.empty(shape, dtype=np_dt)
else:
_AssertCompatible(values, dtype)
nparray = np.array(values, dtype=np_dt)
# check to them.
# We need to pass in quantized values as tuples, so don't apply the shape
if (list(nparray.shape) != _GetDenseDimensions(values) and
not is_quantized):
raise ValueError("""Argument must be a dense tensor: %s"""
""" - got shape %s, but wanted %s.""" % (
values, list(nparray.shape),
_GetDenseDimensions(values)))
# python/numpy default float type is float64. We prefer float32 instead.
if (nparray.dtype == np.float64) and dtype is None:
nparray = nparray.astype(np.float32)
# python/numpy default int type is int64. We prefer int32 instead.
elif (nparray.dtype == np.int64) and dtype is None:
downcasted_array = nparray.astype(np.int32)
# Do not down cast if it leads to precision loss.
if np.array_equal(downcasted_array, nparray):
nparray = downcasted_array
# if dtype is provided, it must be compatible with what numpy
# conversion says.
numpy_dtype = dtypes.as_dtype(nparray.dtype)
if numpy_dtype is None:
raise TypeError("Unrecognized data type: %s" % nparray.dtype)
# If dtype was specified and is a quantized type, we convert
# numpy_dtype back into the quantized version.
if is_quantized:
numpy_dtype = dtype
if dtype is not None and (not hasattr(dtype, "base_dtype") or
dtype.base_dtype != numpy_dtype.base_dtype):
raise TypeError("Incompatible types: %s vs. %s. Value is %s"
% (dtype, nparray.dtype, values))
# If shape is not given, get the shape from the numpy array.
if shape is None:
shape = nparray.shape
is_same_size = True
shape_size = nparray.size
else:
shape = [int(dim) for dim in shape]
shape_size = np.prod(shape, dtype=np.int64)
is_same_size = shape_size == nparray.size
if verify_shape:
if not nparray.shape == tuple(shape):
raise TypeError("Expected Tensor's shape: %s, got %s." %
(tuple(shape), nparray.shape))
if nparray.size > shape_size:
raise ValueError(
"Too many elements provided. Needed at most %d, but received %d" %
(shape_size, nparray.size))
tensor_proto = tensor_pb2.TensorProto(
dtype=numpy_dtype.as_datatype_enum,
tensor_shape=tensor_shape.as_shape(shape).as_proto())
if is_same_size and numpy_dtype in _TENSOR_CONTENT_TYPES and shape_size > 1:
if nparray.size * nparray.itemsize >= (1 << 31):
raise ValueError(
"Cannot create a tensor proto whose content is larger than 2GB.")
tensor_proto.tensor_content = nparray.tostring()
return tensor_proto
# If we were not given values as a numpy array, compute the proto_values
# from the given values directly, to avoid numpy trimming nulls from the
# strings. Since values could be a list of strings, or a multi-dimensional
# list of lists that might or might not correspond to the given shape,
# we flatten it conservatively.
if numpy_dtype == dtypes.string and not isinstance(values, np.ndarray):
proto_values = _FlattenToStrings(values)
# At this point, values may be a list of objects that we could not
# identify a common type for (hence it was inferred as
# np.object/dtypes.string). If we are unable to convert it to a
# string, we raise a more helpful error message.
#
# Ideally, we'd be able to convert the elements of the list to a
# common type, but this type inference requires some thinking and
# so we defer it for now.
try:
str_values = [compat.as_bytes(x) for x in proto_values]
except TypeError:
raise TypeError("Failed to convert object of type %s to Tensor. "
"Contents: %s. Consider casting elements to a "
"supported type." % (type(values), values))
tensor_proto.string_val.extend(str_values)
return tensor_proto
# TensorFlow expects C order (a.k.a., eigen row major).
proto_values = nparray.ravel()
append_fn = GetNumpyAppendFn(proto_values.dtype)
if append_fn is None:
raise TypeError("Element type not supported in TensorProto: %s" %
numpy_dtype.name)
append_fn(tensor_proto, proto_values)
return tensor_proto | [
"def",
"make_tensor_proto",
"(",
"values",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"verify_shape",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"tensor_pb2",
".",
"TensorProto",
")",
":",
"return",
"values",
"if",
"dtype",
":",
"dtype",
"=",
"dtypes",
".",
"as_dtype",
"(",
"dtype",
")",
"is_quantized",
"=",
"(",
"dtype",
"in",
"[",
"dtypes",
".",
"qint8",
",",
"dtypes",
".",
"quint8",
",",
"dtypes",
".",
"qint16",
",",
"dtypes",
".",
"quint16",
",",
"dtypes",
".",
"qint32",
"]",
")",
"# We first convert value to a numpy array or scalar.",
"if",
"isinstance",
"(",
"values",
",",
"(",
"np",
".",
"ndarray",
",",
"np",
".",
"generic",
")",
")",
":",
"if",
"dtype",
":",
"nparray",
"=",
"values",
".",
"astype",
"(",
"dtype",
".",
"as_numpy_dtype",
")",
"else",
":",
"nparray",
"=",
"values",
"elif",
"callable",
"(",
"getattr",
"(",
"values",
",",
"\"__array__\"",
",",
"None",
")",
")",
"or",
"isinstance",
"(",
"getattr",
"(",
"values",
",",
"\"__array_interface__\"",
",",
"None",
")",
",",
"dict",
")",
":",
"# If a class has the __array__ method, or __array_interface__ dict, then it",
"# is possible to convert to numpy array.",
"nparray",
"=",
"np",
".",
"asarray",
"(",
"values",
",",
"dtype",
"=",
"dtype",
")",
"# This is the preferred way to create an array from the object, so replace",
"# the `values` with the array so that _FlattenToStrings is not run.",
"values",
"=",
"nparray",
"else",
":",
"if",
"values",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"None values not supported.\"",
")",
"# if dtype is provided, forces numpy array to be the type",
"# provided if possible.",
"if",
"dtype",
"and",
"dtype",
".",
"is_numpy_compatible",
":",
"np_dt",
"=",
"dtype",
".",
"as_numpy_dtype",
"else",
":",
"np_dt",
"=",
"None",
"# If shape is None, numpy.prod returns None when dtype is not set, but raises",
"# exception when dtype is set to np.int64",
"if",
"shape",
"is",
"not",
"None",
"and",
"np",
".",
"prod",
"(",
"shape",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"==",
"0",
":",
"nparray",
"=",
"np",
".",
"empty",
"(",
"shape",
",",
"dtype",
"=",
"np_dt",
")",
"else",
":",
"_AssertCompatible",
"(",
"values",
",",
"dtype",
")",
"nparray",
"=",
"np",
".",
"array",
"(",
"values",
",",
"dtype",
"=",
"np_dt",
")",
"# check to them.",
"# We need to pass in quantized values as tuples, so don't apply the shape",
"if",
"(",
"list",
"(",
"nparray",
".",
"shape",
")",
"!=",
"_GetDenseDimensions",
"(",
"values",
")",
"and",
"not",
"is_quantized",
")",
":",
"raise",
"ValueError",
"(",
"\"\"\"Argument must be a dense tensor: %s\"\"\"",
"\"\"\" - got shape %s, but wanted %s.\"\"\"",
"%",
"(",
"values",
",",
"list",
"(",
"nparray",
".",
"shape",
")",
",",
"_GetDenseDimensions",
"(",
"values",
")",
")",
")",
"# python/numpy default float type is float64. We prefer float32 instead.",
"if",
"(",
"nparray",
".",
"dtype",
"==",
"np",
".",
"float64",
")",
"and",
"dtype",
"is",
"None",
":",
"nparray",
"=",
"nparray",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"# python/numpy default int type is int64. We prefer int32 instead.",
"elif",
"(",
"nparray",
".",
"dtype",
"==",
"np",
".",
"int64",
")",
"and",
"dtype",
"is",
"None",
":",
"downcasted_array",
"=",
"nparray",
".",
"astype",
"(",
"np",
".",
"int32",
")",
"# Do not down cast if it leads to precision loss.",
"if",
"np",
".",
"array_equal",
"(",
"downcasted_array",
",",
"nparray",
")",
":",
"nparray",
"=",
"downcasted_array",
"# if dtype is provided, it must be compatible with what numpy",
"# conversion says.",
"numpy_dtype",
"=",
"dtypes",
".",
"as_dtype",
"(",
"nparray",
".",
"dtype",
")",
"if",
"numpy_dtype",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Unrecognized data type: %s\"",
"%",
"nparray",
".",
"dtype",
")",
"# If dtype was specified and is a quantized type, we convert",
"# numpy_dtype back into the quantized version.",
"if",
"is_quantized",
":",
"numpy_dtype",
"=",
"dtype",
"if",
"dtype",
"is",
"not",
"None",
"and",
"(",
"not",
"hasattr",
"(",
"dtype",
",",
"\"base_dtype\"",
")",
"or",
"dtype",
".",
"base_dtype",
"!=",
"numpy_dtype",
".",
"base_dtype",
")",
":",
"raise",
"TypeError",
"(",
"\"Incompatible types: %s vs. %s. Value is %s\"",
"%",
"(",
"dtype",
",",
"nparray",
".",
"dtype",
",",
"values",
")",
")",
"# If shape is not given, get the shape from the numpy array.",
"if",
"shape",
"is",
"None",
":",
"shape",
"=",
"nparray",
".",
"shape",
"is_same_size",
"=",
"True",
"shape_size",
"=",
"nparray",
".",
"size",
"else",
":",
"shape",
"=",
"[",
"int",
"(",
"dim",
")",
"for",
"dim",
"in",
"shape",
"]",
"shape_size",
"=",
"np",
".",
"prod",
"(",
"shape",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"is_same_size",
"=",
"shape_size",
"==",
"nparray",
".",
"size",
"if",
"verify_shape",
":",
"if",
"not",
"nparray",
".",
"shape",
"==",
"tuple",
"(",
"shape",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected Tensor's shape: %s, got %s.\"",
"%",
"(",
"tuple",
"(",
"shape",
")",
",",
"nparray",
".",
"shape",
")",
")",
"if",
"nparray",
".",
"size",
">",
"shape_size",
":",
"raise",
"ValueError",
"(",
"\"Too many elements provided. Needed at most %d, but received %d\"",
"%",
"(",
"shape_size",
",",
"nparray",
".",
"size",
")",
")",
"tensor_proto",
"=",
"tensor_pb2",
".",
"TensorProto",
"(",
"dtype",
"=",
"numpy_dtype",
".",
"as_datatype_enum",
",",
"tensor_shape",
"=",
"tensor_shape",
".",
"as_shape",
"(",
"shape",
")",
".",
"as_proto",
"(",
")",
")",
"if",
"is_same_size",
"and",
"numpy_dtype",
"in",
"_TENSOR_CONTENT_TYPES",
"and",
"shape_size",
">",
"1",
":",
"if",
"nparray",
".",
"size",
"*",
"nparray",
".",
"itemsize",
">=",
"(",
"1",
"<<",
"31",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot create a tensor proto whose content is larger than 2GB.\"",
")",
"tensor_proto",
".",
"tensor_content",
"=",
"nparray",
".",
"tostring",
"(",
")",
"return",
"tensor_proto",
"# If we were not given values as a numpy array, compute the proto_values",
"# from the given values directly, to avoid numpy trimming nulls from the",
"# strings. Since values could be a list of strings, or a multi-dimensional",
"# list of lists that might or might not correspond to the given shape,",
"# we flatten it conservatively.",
"if",
"numpy_dtype",
"==",
"dtypes",
".",
"string",
"and",
"not",
"isinstance",
"(",
"values",
",",
"np",
".",
"ndarray",
")",
":",
"proto_values",
"=",
"_FlattenToStrings",
"(",
"values",
")",
"# At this point, values may be a list of objects that we could not",
"# identify a common type for (hence it was inferred as",
"# np.object/dtypes.string). If we are unable to convert it to a",
"# string, we raise a more helpful error message.",
"#",
"# Ideally, we'd be able to convert the elements of the list to a",
"# common type, but this type inference requires some thinking and",
"# so we defer it for now.",
"try",
":",
"str_values",
"=",
"[",
"compat",
".",
"as_bytes",
"(",
"x",
")",
"for",
"x",
"in",
"proto_values",
"]",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"Failed to convert object of type %s to Tensor. \"",
"\"Contents: %s. Consider casting elements to a \"",
"\"supported type.\"",
"%",
"(",
"type",
"(",
"values",
")",
",",
"values",
")",
")",
"tensor_proto",
".",
"string_val",
".",
"extend",
"(",
"str_values",
")",
"return",
"tensor_proto",
"# TensorFlow expects C order (a.k.a., eigen row major).",
"proto_values",
"=",
"nparray",
".",
"ravel",
"(",
")",
"append_fn",
"=",
"GetNumpyAppendFn",
"(",
"proto_values",
".",
"dtype",
")",
"if",
"append_fn",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Element type not supported in TensorProto: %s\"",
"%",
"numpy_dtype",
".",
"name",
")",
"append_fn",
"(",
"tensor_proto",
",",
"proto_values",
")",
"return",
"tensor_proto"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/tensor_util.py#L317-L501 | |
v8mips/v8mips | f0c9cc0bbfd461c7f516799d9a58e9a7395f737e | tools/stats-viewer.py | python | CounterCollection.Counter | (self, index) | return Counter(self.data, 16 + index * self.CounterSize()) | Return the index'th counter. | Return the index'th counter. | [
"Return",
"the",
"index",
"th",
"counter",
"."
] | def Counter(self, index):
"""Return the index'th counter."""
return Counter(self.data, 16 + index * self.CounterSize()) | [
"def",
"Counter",
"(",
"self",
",",
"index",
")",
":",
"return",
"Counter",
"(",
"self",
".",
"data",
",",
"16",
"+",
"index",
"*",
"self",
".",
"CounterSize",
"(",
")",
")"
] | https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/tools/stats-viewer.py#L374-L376 | |
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/rocksdb-master/linters/cpp_linter/cpplint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",
")",
"include_state",
"=",
"_IncludeState",
"(",
")",
"function_state",
"=",
"_FunctionState",
"(",
")",
"nesting_state",
"=",
"_NestingState",
"(",
")",
"ResetNolintSuppressions",
"(",
")",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"CheckForHeaderGuard",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"clean_lines",
"=",
"CleansedLines",
"(",
"lines",
")",
"for",
"line",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
")",
"nesting_state",
".",
"CheckCompletedBlocks",
"(",
"filename",
",",
"error",
")",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
")",
"# We check here rather than inside ProcessLine so that we see raw",
"# lines rather than \"cleaned\" lines.",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/rocksdb-master/linters/cpp_linter/cpplint.py#L4543-L4586 | ||
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/build/lib.linux-x86_64-2.7/mxnet/executor.py | python | Executor.forward | (self, is_train=False, **kwargs) | Calculate the outputs specified by the bound symbol.
Parameters
----------
is_train: bool, optional
whether this forward is for evaluation purpose.
**kwargs
Additional specification of input arguments.
Examples
--------
>>> # doing forward by specifying data
>>> texec.forward(is_train=True, data=mydata)
>>> # doing forward by not specifying things, but copy to the executor before hand
>>> mydata.copyto(texec.arg_dict['data'])
>>> texec.forward(is_train=True) | Calculate the outputs specified by the bound symbol. | [
"Calculate",
"the",
"outputs",
"specified",
"by",
"the",
"bound",
"symbol",
"."
] | def forward(self, is_train=False, **kwargs):
"""Calculate the outputs specified by the bound symbol.
Parameters
----------
is_train: bool, optional
whether this forward is for evaluation purpose.
**kwargs
Additional specification of input arguments.
Examples
--------
>>> # doing forward by specifying data
>>> texec.forward(is_train=True, data=mydata)
>>> # doing forward by not specifying things, but copy to the executor before hand
>>> mydata.copyto(texec.arg_dict['data'])
>>> texec.forward(is_train=True)
"""
if len(kwargs) != 0:
arg_dict = self.arg_dict
for name, array in kwargs.items():
if not isinstance(array, NDArray):
raise ValueError('only accept keyword argument of NDArrays')
if name not in arg_dict:
raise TypeError('Unknown argument %s' % name)
array.copyto(arg_dict[name])
check_call(_LIB.MXExecutorForward(
self.handle,
ctypes.c_int(int(is_train)))) | [
"def",
"forward",
"(",
"self",
",",
"is_train",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"0",
":",
"arg_dict",
"=",
"self",
".",
"arg_dict",
"for",
"name",
",",
"array",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"array",
",",
"NDArray",
")",
":",
"raise",
"ValueError",
"(",
"'only accept keyword argument of NDArrays'",
")",
"if",
"name",
"not",
"in",
"arg_dict",
":",
"raise",
"TypeError",
"(",
"'Unknown argument %s'",
"%",
"name",
")",
"array",
".",
"copyto",
"(",
"arg_dict",
"[",
"name",
"]",
")",
"check_call",
"(",
"_LIB",
".",
"MXExecutorForward",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"c_int",
"(",
"int",
"(",
"is_train",
")",
")",
")",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/executor.py#L83-L113 | ||
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.AdjustLibraries | (self, libraries) | return [lib + '.lib' if not lib.endswith('.lib') else lib for lib in libs] | Strip -l from library if it's specified with that. | Strip -l from library if it's specified with that. | [
"Strip",
"-",
"l",
"from",
"library",
"if",
"it",
"s",
"specified",
"with",
"that",
"."
] | def AdjustLibraries(self, libraries):
"""Strip -l from library if it's specified with that."""
libs = [lib[2:] if lib.startswith('-l') else lib for lib in libraries]
return [lib + '.lib' if not lib.endswith('.lib') else lib for lib in libs] | [
"def",
"AdjustLibraries",
"(",
"self",
",",
"libraries",
")",
":",
"libs",
"=",
"[",
"lib",
"[",
"2",
":",
"]",
"if",
"lib",
".",
"startswith",
"(",
"'-l'",
")",
"else",
"lib",
"for",
"lib",
"in",
"libraries",
"]",
"return",
"[",
"lib",
"+",
"'.lib'",
"if",
"not",
"lib",
".",
"endswith",
"(",
"'.lib'",
")",
"else",
"lib",
"for",
"lib",
"in",
"libs",
"]"
] | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/msvs_emulation.py#L269-L272 | |
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | scripts/kat/spectra.py | python | smooth | (x, window_len=3) | return y | Smooths the histogram using a moving average
:param x: Histogram to smooth
:param window_len: Window length, larger value is smoother. min (and default) is 3
:return: A smoothed version of x | Smooths the histogram using a moving average
:param x: Histogram to smooth
:param window_len: Window length, larger value is smoother. min (and default) is 3
:return: A smoothed version of x | [
"Smooths",
"the",
"histogram",
"using",
"a",
"moving",
"average",
":",
"param",
"x",
":",
"Histogram",
"to",
"smooth",
":",
"param",
"window_len",
":",
"Window",
"length",
"larger",
"value",
"is",
"smoother",
".",
"min",
"(",
"and",
"default",
")",
"is",
"3",
":",
"return",
":",
"A",
"smoothed",
"version",
"of",
"x"
] | def smooth(x, window_len=3):
"""
Smooths the histogram using a moving average
:param x: Histogram to smooth
:param window_len: Window length, larger value is smoother. min (and default) is 3
:return: A smoothed version of x
"""
if x.ndim != 1:
raise ValueError("Smooth only accepts 1 dimension arrays.")
if x.size < window_len or window_len < 3:
return x
s = np.r_[x[window_len - 1:0:-1], x, x[-2:-window_len - 1:-1]]
w = np.ones(window_len, 'd')
y = np.convolve(w / w.sum(), s, mode='valid')
return y | [
"def",
"smooth",
"(",
"x",
",",
"window_len",
"=",
"3",
")",
":",
"if",
"x",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Smooth only accepts 1 dimension arrays.\"",
")",
"if",
"x",
".",
"size",
"<",
"window_len",
"or",
"window_len",
"<",
"3",
":",
"return",
"x",
"s",
"=",
"np",
".",
"r_",
"[",
"x",
"[",
"window_len",
"-",
"1",
":",
"0",
":",
"-",
"1",
"]",
",",
"x",
",",
"x",
"[",
"-",
"2",
":",
"-",
"window_len",
"-",
"1",
":",
"-",
"1",
"]",
"]",
"w",
"=",
"np",
".",
"ones",
"(",
"window_len",
",",
"'d'",
")",
"y",
"=",
"np",
".",
"convolve",
"(",
"w",
"/",
"w",
".",
"sum",
"(",
")",
",",
"s",
",",
"mode",
"=",
"'valid'",
")",
"return",
"y"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/scripts/kat/spectra.py#L16-L32 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | MaildirMessage.set_subdir | (self, subdir) | Set subdir to 'new' or 'cur'. | Set subdir to 'new' or 'cur'. | [
"Set",
"subdir",
"to",
"new",
"or",
"cur",
"."
] | def set_subdir(self, subdir):
"""Set subdir to 'new' or 'cur'."""
if subdir == 'new' or subdir == 'cur':
self._subdir = subdir
else:
raise ValueError("subdir must be 'new' or 'cur': %s" % subdir) | [
"def",
"set_subdir",
"(",
"self",
",",
"subdir",
")",
":",
"if",
"subdir",
"==",
"'new'",
"or",
"subdir",
"==",
"'cur'",
":",
"self",
".",
"_subdir",
"=",
"subdir",
"else",
":",
"raise",
"ValueError",
"(",
"\"subdir must be 'new' or 'cur': %s\"",
"%",
"subdir",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L1485-L1490 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/mstats_basic.py | python | trimr | (a, limits=None, inclusive=(True, True), axis=None) | Trims an array by masking some proportion of the data on each end.
Returns a masked version of the input array.
Parameters
----------
a : sequence
Input array.
limits : {None, tuple}, optional
Tuple of the percentages to cut on each side of the array, with respect
to the number of unmasked data, as floats between 0. and 1.
Noting n the number of unmasked data before trimming, the
(n*limits[0])th smallest data and the (n*limits[1])th largest data are
masked, and the total number of unmasked data after trimming is
n*(1.-sum(limits)). The value of one limit can be set to None to
indicate an open interval.
inclusive : {(True,True) tuple}, optional
Tuple of flags indicating whether the number of data being masked on
the left (right) end should be truncated (True) or rounded (False) to
integers.
axis : {None,int}, optional
Axis along which to trim. If None, the whole array is trimmed, but its
shape is maintained. | Trims an array by masking some proportion of the data on each end.
Returns a masked version of the input array. | [
"Trims",
"an",
"array",
"by",
"masking",
"some",
"proportion",
"of",
"the",
"data",
"on",
"each",
"end",
".",
"Returns",
"a",
"masked",
"version",
"of",
"the",
"input",
"array",
"."
] | def trimr(a, limits=None, inclusive=(True, True), axis=None):
"""
Trims an array by masking some proportion of the data on each end.
Returns a masked version of the input array.
Parameters
----------
a : sequence
Input array.
limits : {None, tuple}, optional
Tuple of the percentages to cut on each side of the array, with respect
to the number of unmasked data, as floats between 0. and 1.
Noting n the number of unmasked data before trimming, the
(n*limits[0])th smallest data and the (n*limits[1])th largest data are
masked, and the total number of unmasked data after trimming is
n*(1.-sum(limits)). The value of one limit can be set to None to
indicate an open interval.
inclusive : {(True,True) tuple}, optional
Tuple of flags indicating whether the number of data being masked on
the left (right) end should be truncated (True) or rounded (False) to
integers.
axis : {None,int}, optional
Axis along which to trim. If None, the whole array is trimmed, but its
shape is maintained.
"""
def _trimr1D(a, low_limit, up_limit, low_inclusive, up_inclusive):
n = a.count()
idx = a.argsort()
if low_limit:
if low_inclusive:
lowidx = int(low_limit*n)
else:
lowidx = np.round(low_limit*n)
a[idx[:lowidx]] = masked
if up_limit is not None:
if up_inclusive:
upidx = n - int(n*up_limit)
else:
upidx = n - np.round(n*up_limit)
a[idx[upidx:]] = masked
return a
a = ma.asarray(a)
a.unshare_mask()
if limits is None:
return a
# Check the limits
(lolim, uplim) = limits
errmsg = "The proportion to cut from the %s should be between 0. and 1."
if lolim is not None:
if lolim > 1. or lolim < 0:
raise ValueError(errmsg % 'beginning' + "(got %s)" % lolim)
if uplim is not None:
if uplim > 1. or uplim < 0:
raise ValueError(errmsg % 'end' + "(got %s)" % uplim)
(loinc, upinc) = inclusive
if axis is None:
shp = a.shape
return _trimr1D(a.ravel(),lolim,uplim,loinc,upinc).reshape(shp)
else:
return ma.apply_along_axis(_trimr1D, axis, a, lolim,uplim,loinc,upinc) | [
"def",
"trimr",
"(",
"a",
",",
"limits",
"=",
"None",
",",
"inclusive",
"=",
"(",
"True",
",",
"True",
")",
",",
"axis",
"=",
"None",
")",
":",
"def",
"_trimr1D",
"(",
"a",
",",
"low_limit",
",",
"up_limit",
",",
"low_inclusive",
",",
"up_inclusive",
")",
":",
"n",
"=",
"a",
".",
"count",
"(",
")",
"idx",
"=",
"a",
".",
"argsort",
"(",
")",
"if",
"low_limit",
":",
"if",
"low_inclusive",
":",
"lowidx",
"=",
"int",
"(",
"low_limit",
"*",
"n",
")",
"else",
":",
"lowidx",
"=",
"np",
".",
"round",
"(",
"low_limit",
"*",
"n",
")",
"a",
"[",
"idx",
"[",
":",
"lowidx",
"]",
"]",
"=",
"masked",
"if",
"up_limit",
"is",
"not",
"None",
":",
"if",
"up_inclusive",
":",
"upidx",
"=",
"n",
"-",
"int",
"(",
"n",
"*",
"up_limit",
")",
"else",
":",
"upidx",
"=",
"n",
"-",
"np",
".",
"round",
"(",
"n",
"*",
"up_limit",
")",
"a",
"[",
"idx",
"[",
"upidx",
":",
"]",
"]",
"=",
"masked",
"return",
"a",
"a",
"=",
"ma",
".",
"asarray",
"(",
"a",
")",
"a",
".",
"unshare_mask",
"(",
")",
"if",
"limits",
"is",
"None",
":",
"return",
"a",
"# Check the limits",
"(",
"lolim",
",",
"uplim",
")",
"=",
"limits",
"errmsg",
"=",
"\"The proportion to cut from the %s should be between 0. and 1.\"",
"if",
"lolim",
"is",
"not",
"None",
":",
"if",
"lolim",
">",
"1.",
"or",
"lolim",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"errmsg",
"%",
"'beginning'",
"+",
"\"(got %s)\"",
"%",
"lolim",
")",
"if",
"uplim",
"is",
"not",
"None",
":",
"if",
"uplim",
">",
"1.",
"or",
"uplim",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"errmsg",
"%",
"'end'",
"+",
"\"(got %s)\"",
"%",
"uplim",
")",
"(",
"loinc",
",",
"upinc",
")",
"=",
"inclusive",
"if",
"axis",
"is",
"None",
":",
"shp",
"=",
"a",
".",
"shape",
"return",
"_trimr1D",
"(",
"a",
".",
"ravel",
"(",
")",
",",
"lolim",
",",
"uplim",
",",
"loinc",
",",
"upinc",
")",
".",
"reshape",
"(",
"shp",
")",
"else",
":",
"return",
"ma",
".",
"apply_along_axis",
"(",
"_trimr1D",
",",
"axis",
",",
"a",
",",
"lolim",
",",
"uplim",
",",
"loinc",
",",
"upinc",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/mstats_basic.py#L1344-L1408 | ||
google/nucleus | 68d3947fafba1337f294c0668a6e1c7f3f1273e3 | nucleus/util/ranges.py | python | RangeSet.from_bed | (cls, source, contigs=None) | return cls(bed_parser(source), contigs) | Creates a RangeSet containing the intervals from source.
Args:
source: A path to a BED (or equivalent) file of intervals.
contigs: An optional list of ContigInfo proto, used by RangeSet
constructor.
Returns:
A RangeSet. | Creates a RangeSet containing the intervals from source. | [
"Creates",
"a",
"RangeSet",
"containing",
"the",
"intervals",
"from",
"source",
"."
] | def from_bed(cls, source, contigs=None):
"""Creates a RangeSet containing the intervals from source.
Args:
source: A path to a BED (or equivalent) file of intervals.
contigs: An optional list of ContigInfo proto, used by RangeSet
constructor.
Returns:
A RangeSet.
"""
return cls(bed_parser(source), contigs) | [
"def",
"from_bed",
"(",
"cls",
",",
"source",
",",
"contigs",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"bed_parser",
"(",
"source",
")",
",",
"contigs",
")"
] | https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/util/ranges.py#L156-L167 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Taskmaster.py | python | Task.executed_with_callbacks | (self) | Called when the task has been successfully executed and
the Taskmaster instance wants to call the Node's callback
methods.
This may have been a do-nothing operation (to preserve build
order), so we must check the node's state before deciding whether
it was "built", in which case we call the appropriate Node method.
In any event, we always call "visited()", which will handle any
post-visit actions that must take place regardless of whether
or not the target was an actual built target or a source Node. | Called when the task has been successfully executed and
the Taskmaster instance wants to call the Node's callback
methods. | [
"Called",
"when",
"the",
"task",
"has",
"been",
"successfully",
"executed",
"and",
"the",
"Taskmaster",
"instance",
"wants",
"to",
"call",
"the",
"Node",
"s",
"callback",
"methods",
"."
] | def executed_with_callbacks(self):
"""
Called when the task has been successfully executed and
the Taskmaster instance wants to call the Node's callback
methods.
This may have been a do-nothing operation (to preserve build
order), so we must check the node's state before deciding whether
it was "built", in which case we call the appropriate Node method.
In any event, we always call "visited()", which will handle any
post-visit actions that must take place regardless of whether
or not the target was an actual built target or a source Node.
"""
global print_prepare
T = self.tm.trace
if T: T.write(self.trace_message('Task.executed_with_callbacks()',
self.node))
for t in self.targets:
if t.get_state() == NODE_EXECUTING:
for side_effect in t.side_effects:
side_effect.set_state(NODE_NO_STATE)
t.set_state(NODE_EXECUTED)
if not t.cached:
t.push_to_cache()
t.built()
t.visited()
if (not print_prepare and
(not hasattr(self, 'options') or not self.options.debug_includes)):
t.release_target_info()
else:
t.visited() | [
"def",
"executed_with_callbacks",
"(",
"self",
")",
":",
"global",
"print_prepare",
"T",
"=",
"self",
".",
"tm",
".",
"trace",
"if",
"T",
":",
"T",
".",
"write",
"(",
"self",
".",
"trace_message",
"(",
"'Task.executed_with_callbacks()'",
",",
"self",
".",
"node",
")",
")",
"for",
"t",
"in",
"self",
".",
"targets",
":",
"if",
"t",
".",
"get_state",
"(",
")",
"==",
"NODE_EXECUTING",
":",
"for",
"side_effect",
"in",
"t",
".",
"side_effects",
":",
"side_effect",
".",
"set_state",
"(",
"NODE_NO_STATE",
")",
"t",
".",
"set_state",
"(",
"NODE_EXECUTED",
")",
"if",
"not",
"t",
".",
"cached",
":",
"t",
".",
"push_to_cache",
"(",
")",
"t",
".",
"built",
"(",
")",
"t",
".",
"visited",
"(",
")",
"if",
"(",
"not",
"print_prepare",
"and",
"(",
"not",
"hasattr",
"(",
"self",
",",
"'options'",
")",
"or",
"not",
"self",
".",
"options",
".",
"debug_includes",
")",
")",
":",
"t",
".",
"release_target_info",
"(",
")",
"else",
":",
"t",
".",
"visited",
"(",
")"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Taskmaster.py#L268-L299 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetProductName | (self) | return self.spec.get("product_name", self.spec["target_name"]) | Returns PRODUCT_NAME. | Returns PRODUCT_NAME. | [
"Returns",
"PRODUCT_NAME",
"."
] | def GetProductName(self):
"""Returns PRODUCT_NAME."""
return self.spec.get("product_name", self.spec["target_name"]) | [
"def",
"GetProductName",
"(",
"self",
")",
":",
"return",
"self",
".",
"spec",
".",
"get",
"(",
"\"product_name\"",
",",
"self",
".",
"spec",
"[",
"\"target_name\"",
"]",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L286-L288 | |
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | scripts/cpp_lint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"rest",
")"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L930-L942 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/offline_debug/dbg_services.py | python | WatchpointHit.name | (self) | return self.instance.get_name() | Function to receive WatchpointHit name.
Returns:
name of WatchpointHit instance (str).
Examples:
>>> from mindspore.ccsrc.debug.debugger.offline_debug import dbg_services
>>> watchpoint_hit = dbg_services.WatchpointHit(name="hit1",
... slot=1,
... condition=2,
... watchpoint_id=3,
... parameters=[param1, param2],
... error_code=0,
... rank_id=1,
... root_graph_id=1)
>>> name = watchpoint_hit.name | Function to receive WatchpointHit name. | [
"Function",
"to",
"receive",
"WatchpointHit",
"name",
"."
] | def name(self):
"""
Function to receive WatchpointHit name.
Returns:
name of WatchpointHit instance (str).
Examples:
>>> from mindspore.ccsrc.debug.debugger.offline_debug import dbg_services
>>> watchpoint_hit = dbg_services.WatchpointHit(name="hit1",
... slot=1,
... condition=2,
... watchpoint_id=3,
... parameters=[param1, param2],
... error_code=0,
... rank_id=1,
... root_graph_id=1)
>>> name = watchpoint_hit.name
"""
return self.instance.get_name() | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"instance",
".",
"get_name",
"(",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/offline_debug/dbg_services.py#L1068-L1087 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBFunction.GetName | (self) | return _lldb.SBFunction_GetName(self) | GetName(self) -> str | GetName(self) -> str | [
"GetName",
"(",
"self",
")",
"-",
">",
"str"
] | def GetName(self):
"""GetName(self) -> str"""
return _lldb.SBFunction_GetName(self) | [
"def",
"GetName",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBFunction_GetName",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L4932-L4934 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | PyApp.GetComCtl32Version | (*args, **kwargs) | return _core_.PyApp_GetComCtl32Version(*args, **kwargs) | GetComCtl32Version() -> int
Returns 400, 470, 471, etc. for comctl32.dll 4.00, 4.70, 4.71 or 0 if
it wasn't found at all. Raises an exception on non-Windows platforms. | GetComCtl32Version() -> int | [
"GetComCtl32Version",
"()",
"-",
">",
"int"
] | def GetComCtl32Version(*args, **kwargs):
"""
GetComCtl32Version() -> int
Returns 400, 470, 471, etc. for comctl32.dll 4.00, 4.70, 4.71 or 0 if
it wasn't found at all. Raises an exception on non-Windows platforms.
"""
return _core_.PyApp_GetComCtl32Version(*args, **kwargs) | [
"def",
"GetComCtl32Version",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"PyApp_GetComCtl32Version",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L8198-L8205 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/build/linux/rewrite_dirs.py | python | RewritePath | (path, opts) | Rewrites a path by stripping the prefix and prepending the sysroot. | Rewrites a path by stripping the prefix and prepending the sysroot. | [
"Rewrites",
"a",
"path",
"by",
"stripping",
"the",
"prefix",
"and",
"prepending",
"the",
"sysroot",
"."
] | def RewritePath(path, opts):
"""Rewrites a path by stripping the prefix and prepending the sysroot."""
sysroot = opts.sysroot
prefix = opts.strip_prefix
if os.path.isabs(path) and not path.startswith(sysroot):
if path.startswith(prefix):
path = path[len(prefix):]
path = path.lstrip('/')
return os.path.join(sysroot, path)
else:
return path | [
"def",
"RewritePath",
"(",
"path",
",",
"opts",
")",
":",
"sysroot",
"=",
"opts",
".",
"sysroot",
"prefix",
"=",
"opts",
".",
"strip_prefix",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
"and",
"not",
"path",
".",
"startswith",
"(",
"sysroot",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"prefix",
")",
":",
"path",
"=",
"path",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"path",
"=",
"path",
".",
"lstrip",
"(",
"'/'",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"sysroot",
",",
"path",
")",
"else",
":",
"return",
"path"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/linux/rewrite_dirs.py#L22-L32 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/bundlebuilder.py | python | pathjoin | (*args) | return os.path.join(*args) | Safe wrapper for os.path.join: asserts that all but the first
argument are relative paths. | Safe wrapper for os.path.join: asserts that all but the first
argument are relative paths. | [
"Safe",
"wrapper",
"for",
"os",
".",
"path",
".",
"join",
":",
"asserts",
"that",
"all",
"but",
"the",
"first",
"argument",
"are",
"relative",
"paths",
"."
] | def pathjoin(*args):
"""Safe wrapper for os.path.join: asserts that all but the first
argument are relative paths."""
for seg in args[1:]:
assert seg[0] != "/"
return os.path.join(*args) | [
"def",
"pathjoin",
"(",
"*",
"args",
")",
":",
"for",
"seg",
"in",
"args",
"[",
"1",
":",
"]",
":",
"assert",
"seg",
"[",
"0",
"]",
"!=",
"\"/\"",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"args",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/bundlebuilder.py#L789-L794 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/decent_q/python/input_fn.py | python | check_images | (image_dir, image_list, iterations, batch_size) | Check images validation | Check images validation | [
"Check",
"images",
"validation"
] | def check_images(image_dir, image_list, iterations, batch_size):
"""Check images validation"""
if not gfile.Exists(image_list):
raise ValueError("Cannot find image_list file {}.".format(image_list))
text = open(image_list).readlines()
print(
"Total images for calibration: {}\ncalib_iter: {}\nbatch_size: {}".format(
len(text), iterations, batch_size))
if (len(text) < iterations * batch_size):
raise RuntimeError(
"calib_iter * batch_size > number of images, please decrease calib_iter or batch_size"
) | [
"def",
"check_images",
"(",
"image_dir",
",",
"image_list",
",",
"iterations",
",",
"batch_size",
")",
":",
"if",
"not",
"gfile",
".",
"Exists",
"(",
"image_list",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot find image_list file {}.\"",
".",
"format",
"(",
"image_list",
")",
")",
"text",
"=",
"open",
"(",
"image_list",
")",
".",
"readlines",
"(",
")",
"print",
"(",
"\"Total images for calibration: {}\\ncalib_iter: {}\\nbatch_size: {}\"",
".",
"format",
"(",
"len",
"(",
"text",
")",
",",
"iterations",
",",
"batch_size",
")",
")",
"if",
"(",
"len",
"(",
"text",
")",
"<",
"iterations",
"*",
"batch_size",
")",
":",
"raise",
"RuntimeError",
"(",
"\"calib_iter * batch_size > number of images, please decrease calib_iter or batch_size\"",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/decent_q/python/input_fn.py#L25-L36 | ||
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | resources/osm_importer/elevation.py | python | Elevation.interpolate_height | (self, Y, X) | Interpolate the height at a given position. | Interpolate the height at a given position. | [
"Interpolate",
"the",
"height",
"at",
"a",
"given",
"position",
"."
] | def interpolate_height(self, Y, X):
"""Interpolate the height at a given position."""
xMinus = -float('inf')
yMinus = -float('inf')
xPlus = float('inf')
yPlus = float('inf')
heights = [0, 0, 0, 0]
Y = -Y
# get the 'boundary' box:
# yMinus
# 0---1
# xMinus | c | xPlus
# 3---2
# yPlus
for elevation in self.elevationArray:
currentX = elevation['x']
currentY = elevation['y']
if currentX < X:
if currentX > xMinus:
xMinus = currentX
else:
if currentX < xPlus:
xPlus = currentX
if currentY < Y:
if currentY > yMinus:
yMinus = currentY
else:
if currentY < yPlus:
yPlus = currentY
for elevation in self.elevationArray:
if elevation['x'] == xMinus and elevation['y'] == yMinus:
heights[0] = elevation['height']
elif elevation['x'] == xMinus and elevation['y'] == yPlus:
heights[3] = elevation['height']
elif elevation['x'] == xPlus and elevation['y'] == yMinus:
heights[1] = elevation['height']
elif elevation['x'] == xPlus and elevation['y'] == yPlus:
heights[2] = elevation['height']
# compute the ration to determine in which of the two triangle of the box the point lies
ratio1 = (yPlus - yMinus) / (xPlus - xMinus)
ratio2 = (Y - yMinus) / (X - xMinus)
# use a barycentric coordinate system in order to interpolate the value in the triangle
# http://en.wikipedia.org/wiki/Barycentric_coordinate_system
x1 = xMinus
y1 = yMinus
if ratio2 < ratio1: # use triangle 0-1-2
x2 = xPlus
x3 = xPlus
y2 = yMinus
y3 = yPlus
else: # use triangle 0-2-3
x2 = xPlus
x3 = xMinus
y2 = yPlus
y3 = yPlus
denominator = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3)
lambda1 = ((y2 - y3) * (X - x3) + (x3 - x2) * (Y - y3)) / denominator
lambda2 = ((y3 - y1) * (X - x3) + (x1 - x3) * (Y - y3)) / denominator
lambda3 = 1 - lambda1 - lambda2
if ratio2 < ratio1:
height = lambda1 * heights[0] + lambda2 * heights[1] + lambda3 * heights[2]
else:
height = lambda1 * heights[0] + lambda2 * heights[2] + lambda3 * heights[3]
if math.isnan(height) or height == float('inf') or height == -float('inf'):
return 0
else:
return height | [
"def",
"interpolate_height",
"(",
"self",
",",
"Y",
",",
"X",
")",
":",
"xMinus",
"=",
"-",
"float",
"(",
"'inf'",
")",
"yMinus",
"=",
"-",
"float",
"(",
"'inf'",
")",
"xPlus",
"=",
"float",
"(",
"'inf'",
")",
"yPlus",
"=",
"float",
"(",
"'inf'",
")",
"heights",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"Y",
"=",
"-",
"Y",
"# get the 'boundary' box:",
"# yMinus",
"# 0---1",
"# xMinus | c | xPlus",
"# 3---2",
"# yPlus",
"for",
"elevation",
"in",
"self",
".",
"elevationArray",
":",
"currentX",
"=",
"elevation",
"[",
"'x'",
"]",
"currentY",
"=",
"elevation",
"[",
"'y'",
"]",
"if",
"currentX",
"<",
"X",
":",
"if",
"currentX",
">",
"xMinus",
":",
"xMinus",
"=",
"currentX",
"else",
":",
"if",
"currentX",
"<",
"xPlus",
":",
"xPlus",
"=",
"currentX",
"if",
"currentY",
"<",
"Y",
":",
"if",
"currentY",
">",
"yMinus",
":",
"yMinus",
"=",
"currentY",
"else",
":",
"if",
"currentY",
"<",
"yPlus",
":",
"yPlus",
"=",
"currentY",
"for",
"elevation",
"in",
"self",
".",
"elevationArray",
":",
"if",
"elevation",
"[",
"'x'",
"]",
"==",
"xMinus",
"and",
"elevation",
"[",
"'y'",
"]",
"==",
"yMinus",
":",
"heights",
"[",
"0",
"]",
"=",
"elevation",
"[",
"'height'",
"]",
"elif",
"elevation",
"[",
"'x'",
"]",
"==",
"xMinus",
"and",
"elevation",
"[",
"'y'",
"]",
"==",
"yPlus",
":",
"heights",
"[",
"3",
"]",
"=",
"elevation",
"[",
"'height'",
"]",
"elif",
"elevation",
"[",
"'x'",
"]",
"==",
"xPlus",
"and",
"elevation",
"[",
"'y'",
"]",
"==",
"yMinus",
":",
"heights",
"[",
"1",
"]",
"=",
"elevation",
"[",
"'height'",
"]",
"elif",
"elevation",
"[",
"'x'",
"]",
"==",
"xPlus",
"and",
"elevation",
"[",
"'y'",
"]",
"==",
"yPlus",
":",
"heights",
"[",
"2",
"]",
"=",
"elevation",
"[",
"'height'",
"]",
"# compute the ration to determine in which of the two triangle of the box the point lies",
"ratio1",
"=",
"(",
"yPlus",
"-",
"yMinus",
")",
"/",
"(",
"xPlus",
"-",
"xMinus",
")",
"ratio2",
"=",
"(",
"Y",
"-",
"yMinus",
")",
"/",
"(",
"X",
"-",
"xMinus",
")",
"# use a barycentric coordinate system in order to interpolate the value in the triangle",
"# http://en.wikipedia.org/wiki/Barycentric_coordinate_system",
"x1",
"=",
"xMinus",
"y1",
"=",
"yMinus",
"if",
"ratio2",
"<",
"ratio1",
":",
"# use triangle 0-1-2",
"x2",
"=",
"xPlus",
"x3",
"=",
"xPlus",
"y2",
"=",
"yMinus",
"y3",
"=",
"yPlus",
"else",
":",
"# use triangle 0-2-3",
"x2",
"=",
"xPlus",
"x3",
"=",
"xMinus",
"y2",
"=",
"yPlus",
"y3",
"=",
"yPlus",
"denominator",
"=",
"(",
"y2",
"-",
"y3",
")",
"*",
"(",
"x1",
"-",
"x3",
")",
"+",
"(",
"x3",
"-",
"x2",
")",
"*",
"(",
"y1",
"-",
"y3",
")",
"lambda1",
"=",
"(",
"(",
"y2",
"-",
"y3",
")",
"*",
"(",
"X",
"-",
"x3",
")",
"+",
"(",
"x3",
"-",
"x2",
")",
"*",
"(",
"Y",
"-",
"y3",
")",
")",
"/",
"denominator",
"lambda2",
"=",
"(",
"(",
"y3",
"-",
"y1",
")",
"*",
"(",
"X",
"-",
"x3",
")",
"+",
"(",
"x1",
"-",
"x3",
")",
"*",
"(",
"Y",
"-",
"y3",
")",
")",
"/",
"denominator",
"lambda3",
"=",
"1",
"-",
"lambda1",
"-",
"lambda2",
"if",
"ratio2",
"<",
"ratio1",
":",
"height",
"=",
"lambda1",
"*",
"heights",
"[",
"0",
"]",
"+",
"lambda2",
"*",
"heights",
"[",
"1",
"]",
"+",
"lambda3",
"*",
"heights",
"[",
"2",
"]",
"else",
":",
"height",
"=",
"lambda1",
"*",
"heights",
"[",
"0",
"]",
"+",
"lambda2",
"*",
"heights",
"[",
"2",
"]",
"+",
"lambda3",
"*",
"heights",
"[",
"3",
"]",
"if",
"math",
".",
"isnan",
"(",
"height",
")",
"or",
"height",
"==",
"float",
"(",
"'inf'",
")",
"or",
"height",
"==",
"-",
"float",
"(",
"'inf'",
")",
":",
"return",
"0",
"else",
":",
"return",
"height"
] | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/osm_importer/elevation.py#L192-L261 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/debug/debug_data.py | python | DebugDumpDir.node_inputs | (self, node_name, is_control=False) | Get the inputs of given node according to partition graphs.
Args:
node_name: Name of the node.
is_control: Whether control inputs, rather than non-control inputs, are
to be returned.
Returns:
All non-control inputs to the node, as a list of node names.
Raises:
RuntimeError: If node inputs and control inputs have not been loaded
from partition graphs yet.
ValueError: If the node does not exist in partition graphs. | Get the inputs of given node according to partition graphs. | [
"Get",
"the",
"inputs",
"of",
"given",
"node",
"according",
"to",
"partition",
"graphs",
"."
] | def node_inputs(self, node_name, is_control=False):
"""Get the inputs of given node according to partition graphs.
Args:
node_name: Name of the node.
is_control: Whether control inputs, rather than non-control inputs, are
to be returned.
Returns:
All non-control inputs to the node, as a list of node names.
Raises:
RuntimeError: If node inputs and control inputs have not been loaded
from partition graphs yet.
ValueError: If the node does not exist in partition graphs.
"""
if self._node_inputs is None or self._node_ctrl_inputs is None:
raise RuntimeError(
"Node inputs are not loaded from partition graphs yet.")
if node_name not in self._node_inputs:
raise ValueError("Node '%s' does not exist in partition graphs." %
node_name)
if is_control:
return self._node_ctrl_inputs[node_name]
else:
return self._node_inputs[node_name] | [
"def",
"node_inputs",
"(",
"self",
",",
"node_name",
",",
"is_control",
"=",
"False",
")",
":",
"if",
"self",
".",
"_node_inputs",
"is",
"None",
"or",
"self",
".",
"_node_ctrl_inputs",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Node inputs are not loaded from partition graphs yet.\"",
")",
"if",
"node_name",
"not",
"in",
"self",
".",
"_node_inputs",
":",
"raise",
"ValueError",
"(",
"\"Node '%s' does not exist in partition graphs.\"",
"%",
"node_name",
")",
"if",
"is_control",
":",
"return",
"self",
".",
"_node_ctrl_inputs",
"[",
"node_name",
"]",
"else",
":",
"return",
"self",
".",
"_node_inputs",
"[",
"node_name",
"]"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/debug_data.py#L688-L716 | ||
googlearchive/tango-examples-c | b57d8c173664de569a7fec703091ff82684a2db5 | third_party/libfreetype/src/tools/docmaker/tohtml.py | python | HtmlFormatter.make_html_words | ( self, words ) | return line | convert a series of simple words into some HTML text | convert a series of simple words into some HTML text | [
"convert",
"a",
"series",
"of",
"simple",
"words",
"into",
"some",
"HTML",
"text"
] | def make_html_words( self, words ):
""" convert a series of simple words into some HTML text """
line = ""
if words:
line = html_quote( words[0] )
for w in words[1:]:
line = line + " " + html_quote( w )
return line | [
"def",
"make_html_words",
"(",
"self",
",",
"words",
")",
":",
"line",
"=",
"\"\"",
"if",
"words",
":",
"line",
"=",
"html_quote",
"(",
"words",
"[",
"0",
"]",
")",
"for",
"w",
"in",
"words",
"[",
"1",
":",
"]",
":",
"line",
"=",
"line",
"+",
"\" \"",
"+",
"html_quote",
"(",
"w",
")",
"return",
"line"
] | https://github.com/googlearchive/tango-examples-c/blob/b57d8c173664de569a7fec703091ff82684a2db5/third_party/libfreetype/src/tools/docmaker/tohtml.py#L245-L253 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/subtree-of-another-tree.py | python | Solution.isSubtree | (self, s, t) | return preOrderTraverse(s, t) | :type s: TreeNode
:type t: TreeNode
:rtype: bool | :type s: TreeNode
:type t: TreeNode
:rtype: bool | [
":",
"type",
"s",
":",
"TreeNode",
":",
"type",
"t",
":",
"TreeNode",
":",
"rtype",
":",
"bool"
] | def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def isSame(x, y):
if not x and not y:
return True
if not x or not y:
return False
return x.val == y.val and \
isSame(x.left, y.left) and \
isSame(x.right, y.right)
def preOrderTraverse(s, t):
return s != None and \
(isSame(s, t) or \
preOrderTraverse(s.left, t) or \
preOrderTraverse(s.right, t))
return preOrderTraverse(s, t) | [
"def",
"isSubtree",
"(",
"self",
",",
"s",
",",
"t",
")",
":",
"def",
"isSame",
"(",
"x",
",",
"y",
")",
":",
"if",
"not",
"x",
"and",
"not",
"y",
":",
"return",
"True",
"if",
"not",
"x",
"or",
"not",
"y",
":",
"return",
"False",
"return",
"x",
".",
"val",
"==",
"y",
".",
"val",
"and",
"isSame",
"(",
"x",
".",
"left",
",",
"y",
".",
"left",
")",
"and",
"isSame",
"(",
"x",
".",
"right",
",",
"y",
".",
"right",
")",
"def",
"preOrderTraverse",
"(",
"s",
",",
"t",
")",
":",
"return",
"s",
"!=",
"None",
"and",
"(",
"isSame",
"(",
"s",
",",
"t",
")",
"or",
"preOrderTraverse",
"(",
"s",
".",
"left",
",",
"t",
")",
"or",
"preOrderTraverse",
"(",
"s",
".",
"right",
",",
"t",
")",
")",
"return",
"preOrderTraverse",
"(",
"s",
",",
"t",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/subtree-of-another-tree.py#L5-L26 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/multiprocessing/connection.py | python | Listener.close | (self) | Close the bound socket or named pipe of `self`. | Close the bound socket or named pipe of `self`. | [
"Close",
"the",
"bound",
"socket",
"or",
"named",
"pipe",
"of",
"self",
"."
] | def close(self):
'''
Close the bound socket or named pipe of `self`.
'''
listener = self._listener
if listener is not None:
self._listener = None
listener.close() | [
"def",
"close",
"(",
"self",
")",
":",
"listener",
"=",
"self",
".",
"_listener",
"if",
"listener",
"is",
"not",
"None",
":",
"self",
".",
"_listener",
"=",
"None",
"listener",
".",
"close",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/connection.py#L474-L481 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py | python | register_namespace_handler | (importer_type, namespace_handler) | Register `namespace_handler` to declare namespace packages
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `namespace_handler` is a callable like this::
def namespace_handler(importer,path_entry,moduleName,module):
# return a path_entry to use for child packages
Namespace handlers are only called if the importer object has already
agreed that it can handle the relevant path item, and they should only
return a subpath if the module __path__ does not already contain an
equivalent subpath. For an example namespace handler, see
``pkg_resources.file_ns_handler``. | Register `namespace_handler` to declare namespace packages | [
"Register",
"namespace_handler",
"to",
"declare",
"namespace",
"packages"
] | def register_namespace_handler(importer_type, namespace_handler):
"""Register `namespace_handler` to declare namespace packages
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `namespace_handler` is a callable like this::
def namespace_handler(importer,path_entry,moduleName,module):
# return a path_entry to use for child packages
Namespace handlers are only called if the importer object has already
agreed that it can handle the relevant path item, and they should only
return a subpath if the module __path__ does not already contain an
equivalent subpath. For an example namespace handler, see
``pkg_resources.file_ns_handler``.
"""
_namespace_handlers[importer_type] = namespace_handler | [
"def",
"register_namespace_handler",
"(",
"importer_type",
",",
"namespace_handler",
")",
":",
"_namespace_handlers",
"[",
"importer_type",
"]",
"=",
"namespace_handler"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py#L1877-L1892 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/math_ops.py | python | _div_python2 | (x, y, name=None) | Divide two values using Python 2 semantics. Used for Tensor.__div__.
Args:
x: `Tensor` numerator of real numeric type.
y: `Tensor` denominator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` returns the quotient of x and y. | Divide two values using Python 2 semantics. Used for Tensor.__div__. | [
"Divide",
"two",
"values",
"using",
"Python",
"2",
"semantics",
".",
"Used",
"for",
"Tensor",
".",
"__div__",
"."
] | def _div_python2(x, y, name=None):
"""Divide two values using Python 2 semantics. Used for Tensor.__div__.
Args:
x: `Tensor` numerator of real numeric type.
y: `Tensor` denominator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` returns the quotient of x and y.
"""
with ops.name_scope(name, "div", [x, y]) as name:
x = ops.convert_to_tensor(x, name="x")
y = ops.convert_to_tensor(y, name="y", dtype=x.dtype.base_dtype)
x_dtype = x.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if x_dtype != y_dtype:
raise TypeError("x and y must have the same dtype, got %r != %r" %
(x_dtype, y_dtype))
if x_dtype.is_floating or x_dtype.is_complex:
return gen_math_ops._real_div(x, y, name=name)
else:
return gen_math_ops._floor_div(x, y, name=name) | [
"def",
"_div_python2",
"(",
"x",
",",
"y",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"div\"",
",",
"[",
"x",
",",
"y",
"]",
")",
"as",
"name",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
",",
"name",
"=",
"\"x\"",
")",
"y",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"y",
",",
"name",
"=",
"\"y\"",
",",
"dtype",
"=",
"x",
".",
"dtype",
".",
"base_dtype",
")",
"x_dtype",
"=",
"x",
".",
"dtype",
".",
"base_dtype",
"y_dtype",
"=",
"y",
".",
"dtype",
".",
"base_dtype",
"if",
"x_dtype",
"!=",
"y_dtype",
":",
"raise",
"TypeError",
"(",
"\"x and y must have the same dtype, got %r != %r\"",
"%",
"(",
"x_dtype",
",",
"y_dtype",
")",
")",
"if",
"x_dtype",
".",
"is_floating",
"or",
"x_dtype",
".",
"is_complex",
":",
"return",
"gen_math_ops",
".",
"_real_div",
"(",
"x",
",",
"y",
",",
"name",
"=",
"name",
")",
"else",
":",
"return",
"gen_math_ops",
".",
"_floor_div",
"(",
"x",
",",
"y",
",",
"name",
"=",
"name",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/math_ops.py#L963-L985 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | makepanda/makepandacore.py | python | PkgConfigGetLibs | (pkgname, tool = "pkg-config") | return libs | Returns a list of libs for the package, prefixed by -l. | Returns a list of libs for the package, prefixed by -l. | [
"Returns",
"a",
"list",
"of",
"libs",
"for",
"the",
"package",
"prefixed",
"by",
"-",
"l",
"."
] | def PkgConfigGetLibs(pkgname, tool = "pkg-config"):
"""Returns a list of libs for the package, prefixed by -l."""
if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
return []
if (tool == "pkg-config"):
handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-l " + pkgname)
elif (tool == "fltk-config"):
handle = os.popen(LocateBinary("fltk-config") + " --ldstaticflags")
else:
handle = os.popen(LocateBinary(tool) + " --libs")
result = handle.read().strip()
handle.close()
libs = []
# Walk through the result arguments carefully. Look for -lname as
# well as -framework name.
r = result.split(' ')
ri = 0
while ri < len(r):
l = r[ri]
if l.startswith("-l") or l.startswith("/"):
libs.append(l)
elif l == '-framework':
libs.append(l)
ri += 1
libs.append(r[ri])
ri += 1
return libs | [
"def",
"PkgConfigGetLibs",
"(",
"pkgname",
",",
"tool",
"=",
"\"pkg-config\"",
")",
":",
"if",
"(",
"sys",
".",
"platform",
"==",
"\"win32\"",
"or",
"CrossCompiling",
"(",
")",
"or",
"not",
"LocateBinary",
"(",
"tool",
")",
")",
":",
"return",
"[",
"]",
"if",
"(",
"tool",
"==",
"\"pkg-config\"",
")",
":",
"handle",
"=",
"os",
".",
"popen",
"(",
"LocateBinary",
"(",
"\"pkg-config\"",
")",
"+",
"\" --silence-errors --libs-only-l \"",
"+",
"pkgname",
")",
"elif",
"(",
"tool",
"==",
"\"fltk-config\"",
")",
":",
"handle",
"=",
"os",
".",
"popen",
"(",
"LocateBinary",
"(",
"\"fltk-config\"",
")",
"+",
"\" --ldstaticflags\"",
")",
"else",
":",
"handle",
"=",
"os",
".",
"popen",
"(",
"LocateBinary",
"(",
"tool",
")",
"+",
"\" --libs\"",
")",
"result",
"=",
"handle",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"handle",
".",
"close",
"(",
")",
"libs",
"=",
"[",
"]",
"# Walk through the result arguments carefully. Look for -lname as",
"# well as -framework name.",
"r",
"=",
"result",
".",
"split",
"(",
"' '",
")",
"ri",
"=",
"0",
"while",
"ri",
"<",
"len",
"(",
"r",
")",
":",
"l",
"=",
"r",
"[",
"ri",
"]",
"if",
"l",
".",
"startswith",
"(",
"\"-l\"",
")",
"or",
"l",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"libs",
".",
"append",
"(",
"l",
")",
"elif",
"l",
"==",
"'-framework'",
":",
"libs",
".",
"append",
"(",
"l",
")",
"ri",
"+=",
"1",
"libs",
".",
"append",
"(",
"r",
"[",
"ri",
"]",
")",
"ri",
"+=",
"1",
"return",
"libs"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/makepanda/makepandacore.py#L1525-L1554 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/style/checker.py | python | _create_log_handlers | (stream) | return [error_handler, non_error_handler] | Create and return a default list of logging.Handler instances.
Format WARNING messages and above to display the logging level, and
messages strictly below WARNING not to display it.
Args:
stream: See the configure_logging() docstring. | Create and return a default list of logging.Handler instances. | [
"Create",
"and",
"return",
"a",
"default",
"list",
"of",
"logging",
".",
"Handler",
"instances",
"."
] | def _create_log_handlers(stream):
"""Create and return a default list of logging.Handler instances.
Format WARNING messages and above to display the logging level, and
messages strictly below WARNING not to display it.
Args:
stream: See the configure_logging() docstring.
"""
# Handles logging.WARNING and above.
error_handler = logging.StreamHandler(stream)
error_handler.setLevel(logging.WARNING)
formatter = logging.Formatter("%(levelname)s: %(message)s")
error_handler.setFormatter(formatter)
# Create a logging.Filter instance that only accepts messages
# below WARNING (i.e. filters out anything WARNING or above).
non_error_filter = logging.Filter()
# The filter method accepts a logging.LogRecord instance.
non_error_filter.filter = lambda record: record.levelno < logging.WARNING
non_error_handler = logging.StreamHandler(stream)
non_error_handler.addFilter(non_error_filter)
formatter = logging.Formatter("%(message)s")
non_error_handler.setFormatter(formatter)
return [error_handler, non_error_handler] | [
"def",
"_create_log_handlers",
"(",
"stream",
")",
":",
"# Handles logging.WARNING and above.",
"error_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
")",
"error_handler",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"\"%(levelname)s: %(message)s\"",
")",
"error_handler",
".",
"setFormatter",
"(",
"formatter",
")",
"# Create a logging.Filter instance that only accepts messages",
"# below WARNING (i.e. filters out anything WARNING or above).",
"non_error_filter",
"=",
"logging",
".",
"Filter",
"(",
")",
"# The filter method accepts a logging.LogRecord instance.",
"non_error_filter",
".",
"filter",
"=",
"lambda",
"record",
":",
"record",
".",
"levelno",
"<",
"logging",
".",
"WARNING",
"non_error_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
")",
"non_error_handler",
".",
"addFilter",
"(",
"non_error_filter",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"\"%(message)s\"",
")",
"non_error_handler",
".",
"setFormatter",
"(",
"formatter",
")",
"return",
"[",
"error_handler",
",",
"non_error_handler",
"]"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/style/checker.py#L291-L318 | |
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/message.py | python | Message.__setstate__ | (self, state) | Support the pickle protocol. | Support the pickle protocol. | [
"Support",
"the",
"pickle",
"protocol",
"."
] | def __setstate__(self, state):
"""Support the pickle protocol."""
self.__init__()
self.ParseFromString(state['serialized']) | [
"def",
"__setstate__",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"__init__",
"(",
")",
"self",
".",
"ParseFromString",
"(",
"state",
"[",
"'serialized'",
"]",
")"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/message.py#L277-L280 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/random.py | python | negative_binomial | (k=1, p=1, shape=_Null, dtype=_Null, ctx=None,
out=None, **kwargs) | return _random_helper(_internal._random_negative_binomial,
_internal._sample_negative_binomial,
[k, p], shape, dtype, ctx, out, kwargs) | Draw random samples from a negative binomial distribution.
Samples are distributed according to a negative binomial distribution
parametrized by *k* (limit of unsuccessful experiments) and *p* (failure
probability in each experiment). Samples will always be returned as a
floating point data type.
Parameters
----------
k : float or NDArray, optional
Limit of unsuccessful experiments, > 0.
p : float or NDArray, optional
Failure probability in each experiment, >= 0 and <=1.
shape : int or tuple of ints, optional
The number of samples to draw. If shape is, e.g., `(m, n)` and `k` and
`p` are scalars, output shape will be `(m, n)`. If `k` and `p`
are NDArrays with shape, e.g., `(x, y)`, then output will have shape
`(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair.
dtype : {'float16', 'float32', 'float64'}, optional
Data type of output samples. Default is 'float32'
ctx : Context, optional
Device context of output. Default is current context. Overridden by
`k.context` when `k` is an NDArray.
out : NDArray, optional
Store output to an existing NDArray.
Returns
-------
NDArray
If input `shape` has shape, e.g., `(m, n)` and `k` and `p` are scalars, output shape
will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then
output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair.
Examples
--------
>>> mx.nd.random.negative_binomial(10, 0.5)
[ 4.]
<NDArray 1 @cpu(0)>
>>> mx.nd.random.negative_binomial(10, 0.5, shape=(2,))
[ 3. 4.]
<NDArray 2 @cpu(0)>
>>> k = mx.nd.array([1,2,3])
>>> p = mx.nd.array([0.2,0.4,0.6])
>>> mx.nd.random.negative_binomial(k, p, shape=2)
[[ 3. 2.]
[ 4. 4.]
[ 0. 5.]]
<NDArray 3x2 @cpu(0)> | Draw random samples from a negative binomial distribution. | [
"Draw",
"random",
"samples",
"from",
"a",
"negative",
"binomial",
"distribution",
"."
] | def negative_binomial(k=1, p=1, shape=_Null, dtype=_Null, ctx=None,
out=None, **kwargs):
"""Draw random samples from a negative binomial distribution.
Samples are distributed according to a negative binomial distribution
parametrized by *k* (limit of unsuccessful experiments) and *p* (failure
probability in each experiment). Samples will always be returned as a
floating point data type.
Parameters
----------
k : float or NDArray, optional
Limit of unsuccessful experiments, > 0.
p : float or NDArray, optional
Failure probability in each experiment, >= 0 and <=1.
shape : int or tuple of ints, optional
The number of samples to draw. If shape is, e.g., `(m, n)` and `k` and
`p` are scalars, output shape will be `(m, n)`. If `k` and `p`
are NDArrays with shape, e.g., `(x, y)`, then output will have shape
`(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair.
dtype : {'float16', 'float32', 'float64'}, optional
Data type of output samples. Default is 'float32'
ctx : Context, optional
Device context of output. Default is current context. Overridden by
`k.context` when `k` is an NDArray.
out : NDArray, optional
Store output to an existing NDArray.
Returns
-------
NDArray
If input `shape` has shape, e.g., `(m, n)` and `k` and `p` are scalars, output shape
will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then
output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair.
Examples
--------
>>> mx.nd.random.negative_binomial(10, 0.5)
[ 4.]
<NDArray 1 @cpu(0)>
>>> mx.nd.random.negative_binomial(10, 0.5, shape=(2,))
[ 3. 4.]
<NDArray 2 @cpu(0)>
>>> k = mx.nd.array([1,2,3])
>>> p = mx.nd.array([0.2,0.4,0.6])
>>> mx.nd.random.negative_binomial(k, p, shape=2)
[[ 3. 2.]
[ 4. 4.]
[ 0. 5.]]
<NDArray 3x2 @cpu(0)>
"""
return _random_helper(_internal._random_negative_binomial,
_internal._sample_negative_binomial,
[k, p], shape, dtype, ctx, out, kwargs) | [
"def",
"negative_binomial",
"(",
"k",
"=",
"1",
",",
"p",
"=",
"1",
",",
"shape",
"=",
"_Null",
",",
"dtype",
"=",
"_Null",
",",
"ctx",
"=",
"None",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_random_helper",
"(",
"_internal",
".",
"_random_negative_binomial",
",",
"_internal",
".",
"_sample_negative_binomial",
",",
"[",
"k",
",",
"p",
"]",
",",
"shape",
",",
"dtype",
",",
"ctx",
",",
"out",
",",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/random.py#L439-L492 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/internals/managers.py | python | BlockManager.operate_blockwise | (self, other: BlockManager, array_op) | return operate_blockwise(self, other, array_op) | Apply array_op blockwise with another (aligned) BlockManager. | Apply array_op blockwise with another (aligned) BlockManager. | [
"Apply",
"array_op",
"blockwise",
"with",
"another",
"(",
"aligned",
")",
"BlockManager",
"."
] | def operate_blockwise(self, other: BlockManager, array_op) -> BlockManager:
"""
Apply array_op blockwise with another (aligned) BlockManager.
"""
return operate_blockwise(self, other, array_op) | [
"def",
"operate_blockwise",
"(",
"self",
",",
"other",
":",
"BlockManager",
",",
"array_op",
")",
"->",
"BlockManager",
":",
"return",
"operate_blockwise",
"(",
"self",
",",
"other",
",",
"array_op",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/managers.py#L1299-L1303 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_upaxes_upaxes_upax | (p) | upaxes : upaxes upax | upaxes : upaxes upax | [
"upaxes",
":",
"upaxes",
"upax"
] | def p_upaxes_upaxes_upax(p):
'upaxes : upaxes upax'
p[0] = p[1]
p[0].append(p[2]) | [
"def",
"p_upaxes_upaxes_upax",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"p",
"[",
"0",
"]",
".",
"append",
"(",
"p",
"[",
"2",
"]",
")"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1463-L1466 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py | python | _check_multiple_of | (value, multiple_of) | Checks that value `value` is a non-zero multiple of `multiple_of`.
Args:
value: an int32 scalar Tensor.
multiple_of: an int or int32 scalar Tensor.
Returns:
new_value: an int32 scalar Tensor matching `value`, but which includes an
assertion that `value` is a multiple of `multiple_of`. | Checks that value `value` is a non-zero multiple of `multiple_of`. | [
"Checks",
"that",
"value",
"value",
"is",
"a",
"non",
"-",
"zero",
"multiple",
"of",
"multiple_of",
"."
] | def _check_multiple_of(value, multiple_of):
"""Checks that value `value` is a non-zero multiple of `multiple_of`.
Args:
value: an int32 scalar Tensor.
multiple_of: an int or int32 scalar Tensor.
Returns:
new_value: an int32 scalar Tensor matching `value`, but which includes an
assertion that `value` is a multiple of `multiple_of`.
"""
assert isinstance(value, ops.Tensor)
with ops.control_dependencies([
control_flow_ops.Assert(
math_ops.logical_and(
math_ops.equal(math_ops.mod(value, multiple_of), 0),
math_ops.not_equal(value, 0)), [
string_ops.string_join([
"Tensor %s should be a multiple of: " % value.name,
string_ops.as_string(multiple_of), ", but saw value: ",
string_ops.as_string(value),
". Consider setting pad=True."
])
])
]):
new_value = array_ops.identity(value, name="multiple_of_checked")
return new_value | [
"def",
"_check_multiple_of",
"(",
"value",
",",
"multiple_of",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"ops",
".",
"Tensor",
")",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"control_flow_ops",
".",
"Assert",
"(",
"math_ops",
".",
"logical_and",
"(",
"math_ops",
".",
"equal",
"(",
"math_ops",
".",
"mod",
"(",
"value",
",",
"multiple_of",
")",
",",
"0",
")",
",",
"math_ops",
".",
"not_equal",
"(",
"value",
",",
"0",
")",
")",
",",
"[",
"string_ops",
".",
"string_join",
"(",
"[",
"\"Tensor %s should be a multiple of: \"",
"%",
"value",
".",
"name",
",",
"string_ops",
".",
"as_string",
"(",
"multiple_of",
")",
",",
"\", but saw value: \"",
",",
"string_ops",
".",
"as_string",
"(",
"value",
")",
",",
"\". Consider setting pad=True.\"",
"]",
")",
"]",
")",
"]",
")",
":",
"new_value",
"=",
"array_ops",
".",
"identity",
"(",
"value",
",",
"name",
"=",
"\"multiple_of_checked\"",
")",
"return",
"new_value"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L110-L136 | ||
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | misc/copyright.py | python | make_notice | (comment_style: CommentStyle, ctime_year: str) | return lines | Returns the notice message as list of strings.
NOTE Each line should end with a newline character. | Returns the notice message as list of strings.
NOTE Each line should end with a newline character. | [
"Returns",
"the",
"notice",
"message",
"as",
"list",
"of",
"strings",
".",
"NOTE",
"Each",
"line",
"should",
"end",
"with",
"a",
"newline",
"character",
"."
] | def make_notice(comment_style: CommentStyle, ctime_year: str) -> List[str]:
"""
Returns the notice message as list of strings.
NOTE Each line should end with a newline character.
"""
lines = []
if comment_style == CommentStyle.C_STYLE:
lines.append("/*" + "*" * 78 + "\n")
line_start = " "
elif comment_style == CommentStyle.CPP_STYLE:
line_start = "//"
elif comment_style == CommentStyle.PY_STYLE:
line_start = "#"
lines.append(
"{0} Copyright (c) {1} The Taichi Authors. All rights reserved.\n".
format(line_start, ctime_year))
lines.append(
"{0} Use of this software is governed by the LICENSE file.\n".format(
line_start))
if comment_style == CommentStyle.C_STYLE:
lines.append("*" * 78 + "*/\n")
lines.append("\n")
return lines | [
"def",
"make_notice",
"(",
"comment_style",
":",
"CommentStyle",
",",
"ctime_year",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"lines",
"=",
"[",
"]",
"if",
"comment_style",
"==",
"CommentStyle",
".",
"C_STYLE",
":",
"lines",
".",
"append",
"(",
"\"/*\"",
"+",
"\"*\"",
"*",
"78",
"+",
"\"\\n\"",
")",
"line_start",
"=",
"\" \"",
"elif",
"comment_style",
"==",
"CommentStyle",
".",
"CPP_STYLE",
":",
"line_start",
"=",
"\"//\"",
"elif",
"comment_style",
"==",
"CommentStyle",
".",
"PY_STYLE",
":",
"line_start",
"=",
"\"#\"",
"lines",
".",
"append",
"(",
"\"{0} Copyright (c) {1} The Taichi Authors. All rights reserved.\\n\"",
".",
"format",
"(",
"line_start",
",",
"ctime_year",
")",
")",
"lines",
".",
"append",
"(",
"\"{0} Use of this software is governed by the LICENSE file.\\n\"",
".",
"format",
"(",
"line_start",
")",
")",
"if",
"comment_style",
"==",
"CommentStyle",
".",
"C_STYLE",
":",
"lines",
".",
"append",
"(",
"\"*\"",
"*",
"78",
"+",
"\"*/\\n\"",
")",
"lines",
".",
"append",
"(",
"\"\\n\"",
")",
"return",
"lines"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/misc/copyright.py#L99-L121 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/statetracker.py | python | StateTracker.IsFunctionClose | (self) | return (self._functions and
self._functions[-1].block_depth == self._block_depth) | Returns true if the current token is a function block close.
Returns:
True if the current token is a function block close. | Returns true if the current token is a function block close. | [
"Returns",
"true",
"if",
"the",
"current",
"token",
"is",
"a",
"function",
"block",
"close",
"."
] | def IsFunctionClose(self):
"""Returns true if the current token is a function block close.
Returns:
True if the current token is a function block close.
"""
return (self._functions and
self._functions[-1].block_depth == self._block_depth) | [
"def",
"IsFunctionClose",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_functions",
"and",
"self",
".",
"_functions",
"[",
"-",
"1",
"]",
".",
"block_depth",
"==",
"self",
".",
"_block_depth",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/statetracker.py#L652-L659 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.LineScrollDown | (*args, **kwargs) | return _stc.StyledTextCtrl_LineScrollDown(*args, **kwargs) | LineScrollDown(self)
Scroll the document down, keeping the caret visible. | LineScrollDown(self) | [
"LineScrollDown",
"(",
"self",
")"
] | def LineScrollDown(*args, **kwargs):
"""
LineScrollDown(self)
Scroll the document down, keeping the caret visible.
"""
return _stc.StyledTextCtrl_LineScrollDown(*args, **kwargs) | [
"def",
"LineScrollDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_LineScrollDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4684-L4690 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py | python | CategoricalBlock.array_dtype | (self) | return np.object_ | the dtype to return if I want to construct this block as an
array | the dtype to return if I want to construct this block as an
array | [
"the",
"dtype",
"to",
"return",
"if",
"I",
"want",
"to",
"construct",
"this",
"block",
"as",
"an",
"array"
] | def array_dtype(self):
""" the dtype to return if I want to construct this block as an
array
"""
return np.object_ | [
"def",
"array_dtype",
"(",
"self",
")",
":",
"return",
"np",
".",
"object_"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L2905-L2909 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/vqs/mc/mc_state/state.py | python | MCState.model | (self) | return self._model | Returns the model definition of this variational state.
This field is optional, and is set to `None` if the variational state has
been initialized using a custom function. | Returns the model definition of this variational state. | [
"Returns",
"the",
"model",
"definition",
"of",
"this",
"variational",
"state",
"."
] | def model(self) -> Optional[Any]:
"""Returns the model definition of this variational state.
This field is optional, and is set to `None` if the variational state has
been initialized using a custom function.
"""
return self._model | [
"def",
"model",
"(",
"self",
")",
"->",
"Optional",
"[",
"Any",
"]",
":",
"return",
"self",
".",
"_model"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/vqs/mc/mc_state/state.py#L287-L293 | |
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/message.py | python | Message.IsInitialized | (self) | Checks if the message is initialized.
Returns:
The method returns True if the message is initialized (i.e. all of its
required fields are set). | Checks if the message is initialized. | [
"Checks",
"if",
"the",
"message",
"is",
"initialized",
"."
] | def IsInitialized(self):
"""Checks if the message is initialized.
Returns:
The method returns True if the message is initialized (i.e. all of its
required fields are set).
"""
raise NotImplementedError | [
"def",
"IsInitialized",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/message.py#L131-L138 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/_collections.py | python | HTTPHeaderDict.add | (self, key, val) | Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz' | Adds a (name, value) pair, doesn't overwrite the value if it already
exists. | [
"Adds",
"a",
"(",
"name",
"value",
")",
"pair",
"doesn",
"t",
"overwrite",
"the",
"value",
"if",
"it",
"already",
"exists",
"."
] | def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = [key, val]
# Keep the common case aka no item present as fast as possible
vals = self._container.setdefault(key_lower, new_vals)
if new_vals is not vals:
vals.append(val) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"key_lower",
"=",
"key",
".",
"lower",
"(",
")",
"new_vals",
"=",
"[",
"key",
",",
"val",
"]",
"# Keep the common case aka no item present as fast as possible",
"vals",
"=",
"self",
".",
"_container",
".",
"setdefault",
"(",
"key_lower",
",",
"new_vals",
")",
"if",
"new_vals",
"is",
"not",
"vals",
":",
"vals",
".",
"append",
"(",
"val",
")"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/_collections.py#L209-L223 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/core/defchararray.py | python | islower | (a) | return _vec_string(a, bool_, 'islower') | Returns true for each element if all cased characters in the
string are lowercase and there is at least one cased character,
false otherwise.
Calls `str.islower` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See also
--------
str.islower | Returns true for each element if all cased characters in the
string are lowercase and there is at least one cased character,
false otherwise. | [
"Returns",
"true",
"for",
"each",
"element",
"if",
"all",
"cased",
"characters",
"in",
"the",
"string",
"are",
"lowercase",
"and",
"there",
"is",
"at",
"least",
"one",
"cased",
"character",
"false",
"otherwise",
"."
] | def islower(a):
"""
Returns true for each element if all cased characters in the
string are lowercase and there is at least one cased character,
false otherwise.
Calls `str.islower` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See also
--------
str.islower
"""
return _vec_string(a, bool_, 'islower') | [
"def",
"islower",
"(",
"a",
")",
":",
"return",
"_vec_string",
"(",
"a",
",",
"bool_",
",",
"'islower'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/defchararray.py#L836-L859 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pytree.py | python | Leaf.__init__ | (self, type, value,
context=None,
prefix=None,
fixers_applied=[]) | Initializer.
Takes a type constant (a token number < 256), a string value, and an
optional context keyword argument. | Initializer. | [
"Initializer",
"."
] | def __init__(self, type, value,
context=None,
prefix=None,
fixers_applied=[]):
"""
Initializer.
Takes a type constant (a token number < 256), a string value, and an
optional context keyword argument.
"""
assert 0 <= type < 256, type
if context is not None:
self._prefix, (self.lineno, self.column) = context
self.type = type
self.value = value
if prefix is not None:
self._prefix = prefix
self.fixers_applied = fixers_applied[:] | [
"def",
"__init__",
"(",
"self",
",",
"type",
",",
"value",
",",
"context",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"fixers_applied",
"=",
"[",
"]",
")",
":",
"assert",
"0",
"<=",
"type",
"<",
"256",
",",
"type",
"if",
"context",
"is",
"not",
"None",
":",
"self",
".",
"_prefix",
",",
"(",
"self",
".",
"lineno",
",",
"self",
".",
"column",
")",
"=",
"context",
"self",
".",
"type",
"=",
"type",
"self",
".",
"value",
"=",
"value",
"if",
"prefix",
"is",
"not",
"None",
":",
"self",
".",
"_prefix",
"=",
"prefix",
"self",
".",
"fixers_applied",
"=",
"fixers_applied",
"[",
":",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pytree.py#L326-L343 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | catboost/python-package/catboost/core.py | python | Pool._check_weight_shape | (self, weight, samples_count) | Check weight length. | Check weight length. | [
"Check",
"weight",
"length",
"."
] | def _check_weight_shape(self, weight, samples_count):
"""
Check weight length.
"""
if len(weight) != samples_count:
raise CatBoostError("Length of weight={} and length of data={} are different.".format(len(weight), samples_count))
if not isinstance(weight[0], (INTEGER_TYPES, FLOAT_TYPES)):
raise CatBoostError("Invalid weight value type={}: must be 1 dimensional data with int, float or long types.".format(type(weight[0]))) | [
"def",
"_check_weight_shape",
"(",
"self",
",",
"weight",
",",
"samples_count",
")",
":",
"if",
"len",
"(",
"weight",
")",
"!=",
"samples_count",
":",
"raise",
"CatBoostError",
"(",
"\"Length of weight={} and length of data={} are different.\"",
".",
"format",
"(",
"len",
"(",
"weight",
")",
",",
"samples_count",
")",
")",
"if",
"not",
"isinstance",
"(",
"weight",
"[",
"0",
"]",
",",
"(",
"INTEGER_TYPES",
",",
"FLOAT_TYPES",
")",
")",
":",
"raise",
"CatBoostError",
"(",
"\"Invalid weight value type={}: must be 1 dimensional data with int, float or long types.\"",
".",
"format",
"(",
"type",
"(",
"weight",
"[",
"0",
"]",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/core.py#L894-L901 | ||
apache/thrift | 0b29261a4f3c6882ef3b09aae47914f0012b0472 | lib/py/src/server/TNonblockingServer.py | python | Connection.write | (self) | Writes data from socket and switch state. | Writes data from socket and switch state. | [
"Writes",
"data",
"from",
"socket",
"and",
"switch",
"state",
"."
] | def write(self):
"""Writes data from socket and switch state."""
assert self.status == SEND_ANSWER
sent = self.socket.send(self._wbuf)
if sent == len(self._wbuf):
self.status = WAIT_LEN
self._wbuf = b''
self.len = 0
else:
self._wbuf = self._wbuf[sent:] | [
"def",
"write",
"(",
"self",
")",
":",
"assert",
"self",
".",
"status",
"==",
"SEND_ANSWER",
"sent",
"=",
"self",
".",
"socket",
".",
"send",
"(",
"self",
".",
"_wbuf",
")",
"if",
"sent",
"==",
"len",
"(",
"self",
".",
"_wbuf",
")",
":",
"self",
".",
"status",
"=",
"WAIT_LEN",
"self",
".",
"_wbuf",
"=",
"b''",
"self",
".",
"len",
"=",
"0",
"else",
":",
"self",
".",
"_wbuf",
"=",
"self",
".",
"_wbuf",
"[",
"sent",
":",
"]"
] | https://github.com/apache/thrift/blob/0b29261a4f3c6882ef3b09aae47914f0012b0472/lib/py/src/server/TNonblockingServer.py#L168-L177 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/generator/msvs.py | python | _MapFileToMsBuildSourceType | (source, rule_dependencies,
extension_to_rule_name, platforms) | return (group, element) | Returns the group and element type of the source file.
Arguments:
source: The source file name.
extension_to_rule_name: A dictionary mapping file extensions to rules.
Returns:
A pair of (group this file should be part of, the label of element) | Returns the group and element type of the source file. | [
"Returns",
"the",
"group",
"and",
"element",
"type",
"of",
"the",
"source",
"file",
"."
] | def _MapFileToMsBuildSourceType(source, rule_dependencies,
extension_to_rule_name, platforms):
"""Returns the group and element type of the source file.
Arguments:
source: The source file name.
extension_to_rule_name: A dictionary mapping file extensions to rules.
Returns:
A pair of (group this file should be part of, the label of element)
"""
_, ext = os.path.splitext(source)
ext = ext.lower()
if ext in extension_to_rule_name:
group = 'rule'
element = extension_to_rule_name[ext]
elif ext in ['.cc', '.cpp', '.c', '.cxx', '.mm']:
group = 'compile'
element = 'ClCompile'
elif ext in ['.h', '.hxx']:
group = 'include'
element = 'ClInclude'
elif ext == '.rc':
group = 'resource'
element = 'ResourceCompile'
elif ext in ['.s', '.asm']:
group = 'masm'
element = 'MASM'
for platform in platforms:
if platform.lower() in ['arm', 'arm64']:
element = 'MARMASM'
elif ext == '.idl':
group = 'midl'
element = 'Midl'
elif source in rule_dependencies:
group = 'rule_dependency'
element = 'CustomBuild'
else:
group = 'none'
element = 'None'
return (group, element) | [
"def",
"_MapFileToMsBuildSourceType",
"(",
"source",
",",
"rule_dependencies",
",",
"extension_to_rule_name",
",",
"platforms",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"source",
")",
"ext",
"=",
"ext",
".",
"lower",
"(",
")",
"if",
"ext",
"in",
"extension_to_rule_name",
":",
"group",
"=",
"'rule'",
"element",
"=",
"extension_to_rule_name",
"[",
"ext",
"]",
"elif",
"ext",
"in",
"[",
"'.cc'",
",",
"'.cpp'",
",",
"'.c'",
",",
"'.cxx'",
",",
"'.mm'",
"]",
":",
"group",
"=",
"'compile'",
"element",
"=",
"'ClCompile'",
"elif",
"ext",
"in",
"[",
"'.h'",
",",
"'.hxx'",
"]",
":",
"group",
"=",
"'include'",
"element",
"=",
"'ClInclude'",
"elif",
"ext",
"==",
"'.rc'",
":",
"group",
"=",
"'resource'",
"element",
"=",
"'ResourceCompile'",
"elif",
"ext",
"in",
"[",
"'.s'",
",",
"'.asm'",
"]",
":",
"group",
"=",
"'masm'",
"element",
"=",
"'MASM'",
"for",
"platform",
"in",
"platforms",
":",
"if",
"platform",
".",
"lower",
"(",
")",
"in",
"[",
"'arm'",
",",
"'arm64'",
"]",
":",
"element",
"=",
"'MARMASM'",
"elif",
"ext",
"==",
"'.idl'",
":",
"group",
"=",
"'midl'",
"element",
"=",
"'Midl'",
"elif",
"source",
"in",
"rule_dependencies",
":",
"group",
"=",
"'rule_dependency'",
"element",
"=",
"'CustomBuild'",
"else",
":",
"group",
"=",
"'none'",
"element",
"=",
"'None'",
"return",
"(",
"group",
",",
"element",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/msvs.py#L2174-L2214 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/bijector/invert.py | python | Invert.inverse_log_jacobian | (self, y) | return self.bijector("forward_log_jacobian", y) | Logarithm of the derivative of the inverse transformation of the inverse bijector,
namely logarithm of the derivative of the forward transformation of the underlying bijector.
Args:
y (Tensor): the value of the transformed random variable.
Output:
Tensor, logarithm of the derivative of the inverse transformation of the inverse bijector. | Logarithm of the derivative of the inverse transformation of the inverse bijector,
namely logarithm of the derivative of the forward transformation of the underlying bijector. | [
"Logarithm",
"of",
"the",
"derivative",
"of",
"the",
"inverse",
"transformation",
"of",
"the",
"inverse",
"bijector",
"namely",
"logarithm",
"of",
"the",
"derivative",
"of",
"the",
"forward",
"transformation",
"of",
"the",
"underlying",
"bijector",
"."
] | def inverse_log_jacobian(self, y):
"""
Logarithm of the derivative of the inverse transformation of the inverse bijector,
namely logarithm of the derivative of the forward transformation of the underlying bijector.
Args:
y (Tensor): the value of the transformed random variable.
Output:
Tensor, logarithm of the derivative of the inverse transformation of the inverse bijector.
"""
return self.bijector("forward_log_jacobian", y) | [
"def",
"inverse_log_jacobian",
"(",
"self",
",",
"y",
")",
":",
"return",
"self",
".",
"bijector",
"(",
"\"forward_log_jacobian\"",
",",
"y",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/bijector/invert.py#L112-L123 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/locale.py | python | atof | (string, func=float) | return func(string) | Parses a string as a float according to the locale settings. | Parses a string as a float according to the locale settings. | [
"Parses",
"a",
"string",
"as",
"a",
"float",
"according",
"to",
"the",
"locale",
"settings",
"."
] | def atof(string, func=float):
"Parses a string as a float according to the locale settings."
#First, get rid of the grouping
ts = localeconv()['thousands_sep']
if ts:
string = string.replace(ts, '')
#next, replace the decimal point with a dot
dd = localeconv()['decimal_point']
if dd:
string = string.replace(dd, '.')
#finally, parse the string
return func(string) | [
"def",
"atof",
"(",
"string",
",",
"func",
"=",
"float",
")",
":",
"#First, get rid of the grouping",
"ts",
"=",
"localeconv",
"(",
")",
"[",
"'thousands_sep'",
"]",
"if",
"ts",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"ts",
",",
"''",
")",
"#next, replace the decimal point with a dot",
"dd",
"=",
"localeconv",
"(",
")",
"[",
"'decimal_point'",
"]",
"if",
"dd",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"dd",
",",
"'.'",
")",
"#finally, parse the string",
"return",
"func",
"(",
"string",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/locale.py#L305-L316 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/backend.py | python | dot | (x, y) | return out | Multiplies 2 tensors (and/or variables) and returns a *tensor*.
When attempting to multiply a nD tensor
with a nD tensor, it reproduces the Theano behavior.
(e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)
Arguments:
x: Tensor or variable.
y: Tensor or variable.
Returns:
A tensor, dot product of `x` and `y`.
Examples:
```python
# dot product between tensors
>>> x = K.placeholder(shape=(2, 3))
>>> y = K.placeholder(shape=(3, 4))
>>> xy = K.dot(x, y)
>>> xy
<tf.Tensor 'MatMul_9:0' shape=(2, 4) dtype=float32>
```
```python
# dot product between tensors
>>> x = K.placeholder(shape=(32, 28, 3))
>>> y = K.placeholder(shape=(3, 4))
>>> xy = K.dot(x, y)
>>> xy
<tf.Tensor 'MatMul_9:0' shape=(32, 28, 4) dtype=float32>
```
```python
# Theano-like behavior example
>>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)
>>> y = K.ones((4, 3, 5))
>>> xy = K.dot(x, y)
>>> K.int_shape(xy)
(2, 4, 5)
``` | Multiplies 2 tensors (and/or variables) and returns a *tensor*. | [
"Multiplies",
"2",
"tensors",
"(",
"and",
"/",
"or",
"variables",
")",
"and",
"returns",
"a",
"*",
"tensor",
"*",
"."
] | def dot(x, y):
"""Multiplies 2 tensors (and/or variables) and returns a *tensor*.
When attempting to multiply a nD tensor
with a nD tensor, it reproduces the Theano behavior.
(e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)
Arguments:
x: Tensor or variable.
y: Tensor or variable.
Returns:
A tensor, dot product of `x` and `y`.
Examples:
```python
# dot product between tensors
>>> x = K.placeholder(shape=(2, 3))
>>> y = K.placeholder(shape=(3, 4))
>>> xy = K.dot(x, y)
>>> xy
<tf.Tensor 'MatMul_9:0' shape=(2, 4) dtype=float32>
```
```python
# dot product between tensors
>>> x = K.placeholder(shape=(32, 28, 3))
>>> y = K.placeholder(shape=(3, 4))
>>> xy = K.dot(x, y)
>>> xy
<tf.Tensor 'MatMul_9:0' shape=(32, 28, 4) dtype=float32>
```
```python
# Theano-like behavior example
>>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)
>>> y = K.ones((4, 3, 5))
>>> xy = K.dot(x, y)
>>> K.int_shape(xy)
(2, 4, 5)
```
"""
if ndim(x) is not None and (ndim(x) > 2 or ndim(y) > 2):
x_shape = []
for i, s in zip(int_shape(x), array_ops.unstack(array_ops.shape(x))):
if i is not None:
x_shape.append(i)
else:
x_shape.append(s)
x_shape = tuple(x_shape)
y_shape = []
for i, s in zip(int_shape(y), array_ops.unstack(array_ops.shape(y))):
if i is not None:
y_shape.append(i)
else:
y_shape.append(s)
y_shape = tuple(y_shape)
y_permute_dim = list(range(ndim(y)))
y_permute_dim = [y_permute_dim.pop(-2)] + y_permute_dim
xt = array_ops.reshape(x, [-1, x_shape[-1]])
yt = array_ops.reshape(
array_ops.transpose(y, perm=y_permute_dim), [y_shape[-2], -1])
return array_ops.reshape(
math_ops.matmul(xt, yt), x_shape[:-1] + y_shape[:-2] + y_shape[-1:])
if is_sparse(x):
out = sparse_ops.sparse_tensor_dense_matmul(x, y)
else:
out = math_ops.matmul(x, y)
return out | [
"def",
"dot",
"(",
"x",
",",
"y",
")",
":",
"if",
"ndim",
"(",
"x",
")",
"is",
"not",
"None",
"and",
"(",
"ndim",
"(",
"x",
")",
">",
"2",
"or",
"ndim",
"(",
"y",
")",
">",
"2",
")",
":",
"x_shape",
"=",
"[",
"]",
"for",
"i",
",",
"s",
"in",
"zip",
"(",
"int_shape",
"(",
"x",
")",
",",
"array_ops",
".",
"unstack",
"(",
"array_ops",
".",
"shape",
"(",
"x",
")",
")",
")",
":",
"if",
"i",
"is",
"not",
"None",
":",
"x_shape",
".",
"append",
"(",
"i",
")",
"else",
":",
"x_shape",
".",
"append",
"(",
"s",
")",
"x_shape",
"=",
"tuple",
"(",
"x_shape",
")",
"y_shape",
"=",
"[",
"]",
"for",
"i",
",",
"s",
"in",
"zip",
"(",
"int_shape",
"(",
"y",
")",
",",
"array_ops",
".",
"unstack",
"(",
"array_ops",
".",
"shape",
"(",
"y",
")",
")",
")",
":",
"if",
"i",
"is",
"not",
"None",
":",
"y_shape",
".",
"append",
"(",
"i",
")",
"else",
":",
"y_shape",
".",
"append",
"(",
"s",
")",
"y_shape",
"=",
"tuple",
"(",
"y_shape",
")",
"y_permute_dim",
"=",
"list",
"(",
"range",
"(",
"ndim",
"(",
"y",
")",
")",
")",
"y_permute_dim",
"=",
"[",
"y_permute_dim",
".",
"pop",
"(",
"-",
"2",
")",
"]",
"+",
"y_permute_dim",
"xt",
"=",
"array_ops",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
",",
"x_shape",
"[",
"-",
"1",
"]",
"]",
")",
"yt",
"=",
"array_ops",
".",
"reshape",
"(",
"array_ops",
".",
"transpose",
"(",
"y",
",",
"perm",
"=",
"y_permute_dim",
")",
",",
"[",
"y_shape",
"[",
"-",
"2",
"]",
",",
"-",
"1",
"]",
")",
"return",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"matmul",
"(",
"xt",
",",
"yt",
")",
",",
"x_shape",
"[",
":",
"-",
"1",
"]",
"+",
"y_shape",
"[",
":",
"-",
"2",
"]",
"+",
"y_shape",
"[",
"-",
"1",
":",
"]",
")",
"if",
"is_sparse",
"(",
"x",
")",
":",
"out",
"=",
"sparse_ops",
".",
"sparse_tensor_dense_matmul",
"(",
"x",
",",
"y",
")",
"else",
":",
"out",
"=",
"math_ops",
".",
"matmul",
"(",
"x",
",",
"y",
")",
"return",
"out"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L1143-L1211 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/png/png.py | python | Reader.asRGBA | (self) | return width,height,convert(),meta | Return image as RGBA pixels. Greyscales are expanded into
RGB triplets; an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``, and
``metadata['alpha']`` will be ``True``. | Return image as RGBA pixels. Greyscales are expanded into
RGB triplets; an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``, and
``metadata['alpha']`` will be ``True``. | [
"Return",
"image",
"as",
"RGBA",
"pixels",
".",
"Greyscales",
"are",
"expanded",
"into",
"RGB",
"triplets",
";",
"an",
"alpha",
"channel",
"is",
"synthesized",
"if",
"necessary",
".",
"The",
"return",
"values",
"are",
"as",
"for",
"the",
":",
"meth",
":",
"read",
"method",
"except",
"that",
"the",
"*",
"metadata",
"*",
"reflect",
"the",
"returned",
"pixels",
"not",
"the",
"source",
"image",
".",
"In",
"particular",
"for",
"this",
"method",
"metadata",
"[",
"greyscale",
"]",
"will",
"be",
"False",
"and",
"metadata",
"[",
"alpha",
"]",
"will",
"be",
"True",
"."
] | def asRGBA(self):
"""Return image as RGBA pixels. Greyscales are expanded into
RGB triplets; an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source image. In particular, for this method
``metadata['greyscale']`` will be ``False``, and
``metadata['alpha']`` will be ``True``.
"""
width,height,pixels,meta = self.asDirect()
if meta['alpha'] and not meta['greyscale']:
return width,height,pixels,meta
typecode = 'BH'[meta['bitdepth'] > 8]
maxval = 2**meta['bitdepth'] - 1
maxbuffer = struct.pack('=' + typecode, maxval) * 4 * width
def newarray():
return array(typecode, maxbuffer)
if meta['alpha'] and meta['greyscale']:
# LA to RGBA
def convert():
for row in pixels:
# Create a fresh target row, then copy L channel
# into first three target channels, and A channel
# into fourth channel.
a = newarray()
pngfilters.convert_la_to_rgba(row, a)
yield a
elif meta['greyscale']:
# L to RGBA
def convert():
for row in pixels:
a = newarray()
pngfilters.convert_l_to_rgba(row, a)
yield a
else:
assert not meta['alpha'] and not meta['greyscale']
# RGB to RGBA
def convert():
for row in pixels:
a = newarray()
pngfilters.convert_rgb_to_rgba(row, a)
yield a
meta['alpha'] = True
meta['greyscale'] = False
return width,height,convert(),meta | [
"def",
"asRGBA",
"(",
"self",
")",
":",
"width",
",",
"height",
",",
"pixels",
",",
"meta",
"=",
"self",
".",
"asDirect",
"(",
")",
"if",
"meta",
"[",
"'alpha'",
"]",
"and",
"not",
"meta",
"[",
"'greyscale'",
"]",
":",
"return",
"width",
",",
"height",
",",
"pixels",
",",
"meta",
"typecode",
"=",
"'BH'",
"[",
"meta",
"[",
"'bitdepth'",
"]",
">",
"8",
"]",
"maxval",
"=",
"2",
"**",
"meta",
"[",
"'bitdepth'",
"]",
"-",
"1",
"maxbuffer",
"=",
"struct",
".",
"pack",
"(",
"'='",
"+",
"typecode",
",",
"maxval",
")",
"*",
"4",
"*",
"width",
"def",
"newarray",
"(",
")",
":",
"return",
"array",
"(",
"typecode",
",",
"maxbuffer",
")",
"if",
"meta",
"[",
"'alpha'",
"]",
"and",
"meta",
"[",
"'greyscale'",
"]",
":",
"# LA to RGBA",
"def",
"convert",
"(",
")",
":",
"for",
"row",
"in",
"pixels",
":",
"# Create a fresh target row, then copy L channel",
"# into first three target channels, and A channel",
"# into fourth channel.",
"a",
"=",
"newarray",
"(",
")",
"pngfilters",
".",
"convert_la_to_rgba",
"(",
"row",
",",
"a",
")",
"yield",
"a",
"elif",
"meta",
"[",
"'greyscale'",
"]",
":",
"# L to RGBA",
"def",
"convert",
"(",
")",
":",
"for",
"row",
"in",
"pixels",
":",
"a",
"=",
"newarray",
"(",
")",
"pngfilters",
".",
"convert_l_to_rgba",
"(",
"row",
",",
"a",
")",
"yield",
"a",
"else",
":",
"assert",
"not",
"meta",
"[",
"'alpha'",
"]",
"and",
"not",
"meta",
"[",
"'greyscale'",
"]",
"# RGB to RGBA",
"def",
"convert",
"(",
")",
":",
"for",
"row",
"in",
"pixels",
":",
"a",
"=",
"newarray",
"(",
")",
"pngfilters",
".",
"convert_rgb_to_rgba",
"(",
"row",
",",
"a",
")",
"yield",
"a",
"meta",
"[",
"'alpha'",
"]",
"=",
"True",
"meta",
"[",
"'greyscale'",
"]",
"=",
"False",
"return",
"width",
",",
"height",
",",
"convert",
"(",
")",
",",
"meta"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/png/png.py#L2175-L2221 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | components/policy/tools/make_policy_zip.py | python | add_files_to_zip | (zip_file, base_dir, file_list) | return 0 | Pack a list of files into a zip archive, that is already
opened for writing.
Args:
zip_file: An object representing the zip archive.
base_dir: Base path of all the files in the real file system.
files: List of file paths to add, all relative to base_dir.
The zip entries will only contain this componenet of the path. | Pack a list of files into a zip archive, that is already
opened for writing. | [
"Pack",
"a",
"list",
"of",
"files",
"into",
"a",
"zip",
"archive",
"that",
"is",
"already",
"opened",
"for",
"writing",
"."
] | def add_files_to_zip(zip_file, base_dir, file_list):
"""Pack a list of files into a zip archive, that is already
opened for writing.
Args:
zip_file: An object representing the zip archive.
base_dir: Base path of all the files in the real file system.
files: List of file paths to add, all relative to base_dir.
The zip entries will only contain this componenet of the path.
"""
for file_path in file_list:
zip_file.write(base_dir + file_path, file_path)
return 0 | [
"def",
"add_files_to_zip",
"(",
"zip_file",
",",
"base_dir",
",",
"file_list",
")",
":",
"for",
"file_path",
"in",
"file_list",
":",
"zip_file",
".",
"write",
"(",
"base_dir",
"+",
"file_path",
",",
"file_path",
")",
"return",
"0"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/components/policy/tools/make_policy_zip.py#L17-L29 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/NinjaWriter.py | python | NinjaWriter._WriteLink | (self, spec, config_name, config, link_deps, compile_deps) | Write out a link step. Fills out target.binary. | Write out a link step. Fills out target.binary. | [
"Write",
"out",
"a",
"link",
"step",
".",
"Fills",
"out",
"target",
".",
"binary",
"."
] | def _WriteLink(self, spec, config_name, config, link_deps, compile_deps):
"""Write out a link step. Fills out target.binary. """
if self.flavor != 'mac' or len(self.archs) == 1:
return self._WriteLinkForArch(self.ninja, spec, config_name, config, link_deps, compile_deps)
else:
output = self._ComputeOutput(spec)
inputs = [self._WriteLinkForArch(self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], compile_deps, arch=arch) for arch in self.archs]
extra_bindings = []
build_output = output
if not self.is_mac_bundle:
self._AppendPostbuildVariable(extra_bindings, spec, output, output)
# TODO(yyanagisawa): more work needed to fix:
# https://code.google.com/p/gyp/issues/detail?id=411
if spec['type'] in ('shared_library', 'loadable_module') and not self.is_mac_bundle:
extra_bindings.append(('lib', output))
self.ninja.build([output, output + '.TOC'], 'solipo', inputs, variables=extra_bindings)
else:
self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings)
return output | [
"def",
"_WriteLink",
"(",
"self",
",",
"spec",
",",
"config_name",
",",
"config",
",",
"link_deps",
",",
"compile_deps",
")",
":",
"if",
"self",
".",
"flavor",
"!=",
"'mac'",
"or",
"len",
"(",
"self",
".",
"archs",
")",
"==",
"1",
":",
"return",
"self",
".",
"_WriteLinkForArch",
"(",
"self",
".",
"ninja",
",",
"spec",
",",
"config_name",
",",
"config",
",",
"link_deps",
",",
"compile_deps",
")",
"else",
":",
"output",
"=",
"self",
".",
"_ComputeOutput",
"(",
"spec",
")",
"inputs",
"=",
"[",
"self",
".",
"_WriteLinkForArch",
"(",
"self",
".",
"arch_subninjas",
"[",
"arch",
"]",
",",
"spec",
",",
"config_name",
",",
"config",
",",
"link_deps",
"[",
"arch",
"]",
",",
"compile_deps",
",",
"arch",
"=",
"arch",
")",
"for",
"arch",
"in",
"self",
".",
"archs",
"]",
"extra_bindings",
"=",
"[",
"]",
"build_output",
"=",
"output",
"if",
"not",
"self",
".",
"is_mac_bundle",
":",
"self",
".",
"_AppendPostbuildVariable",
"(",
"extra_bindings",
",",
"spec",
",",
"output",
",",
"output",
")",
"# TODO(yyanagisawa): more work needed to fix:",
"# https://code.google.com/p/gyp/issues/detail?id=411",
"if",
"spec",
"[",
"'type'",
"]",
"in",
"(",
"'shared_library'",
",",
"'loadable_module'",
")",
"and",
"not",
"self",
".",
"is_mac_bundle",
":",
"extra_bindings",
".",
"append",
"(",
"(",
"'lib'",
",",
"output",
")",
")",
"self",
".",
"ninja",
".",
"build",
"(",
"[",
"output",
",",
"output",
"+",
"'.TOC'",
"]",
",",
"'solipo'",
",",
"inputs",
",",
"variables",
"=",
"extra_bindings",
")",
"else",
":",
"self",
".",
"ninja",
".",
"build",
"(",
"build_output",
",",
"'lipo'",
",",
"inputs",
",",
"variables",
"=",
"extra_bindings",
")",
"return",
"output"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/NinjaWriter.py#L779-L798 | ||
ElementsProject/elements | 7d83cc0089345a0646834986c56e58543fd5ee07 | contrib/devtools/security-check.py | python | check_ELF_PIE | (executable) | return ok | Check for position independent executable (PIE), allowing for address space randomization. | Check for position independent executable (PIE), allowing for address space randomization. | [
"Check",
"for",
"position",
"independent",
"executable",
"(",
"PIE",
")",
"allowing",
"for",
"address",
"space",
"randomization",
"."
] | def check_ELF_PIE(executable) -> bool:
'''
Check for position independent executable (PIE), allowing for address space randomization.
'''
stdout = run_command([READELF_CMD, '-h', '-W', executable])
ok = False
for line in stdout.splitlines():
tokens = line.split()
if len(line)>=2 and tokens[0] == 'Type:' and tokens[1] == 'DYN':
ok = True
return ok | [
"def",
"check_ELF_PIE",
"(",
"executable",
")",
"->",
"bool",
":",
"stdout",
"=",
"run_command",
"(",
"[",
"READELF_CMD",
",",
"'-h'",
",",
"'-W'",
",",
"executable",
"]",
")",
"ok",
"=",
"False",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"line",
")",
">=",
"2",
"and",
"tokens",
"[",
"0",
"]",
"==",
"'Type:'",
"and",
"tokens",
"[",
"1",
"]",
"==",
"'DYN'",
":",
"ok",
"=",
"True",
"return",
"ok"
] | https://github.com/ElementsProject/elements/blob/7d83cc0089345a0646834986c56e58543fd5ee07/contrib/devtools/security-check.py#L25-L36 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/random_ops.py | python | normal | (shape, mean, stddev, seed=None) | return value | Generates random numbers according to the Normal (or Gaussian) random number distribution.
Args:
shape (tuple): The shape of random tensor to be generated.
The format is :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
mean (Tensor): The mean μ distribution parameter, which specifies the location of the peak,
with data type in [int8, int16, int32, int64, float16, float32].
stddev (Tensor): The deviation σ distribution parameter. It should be greater than 0,
with data type in [int8, int16, int32, int64, float16, float32].
seed (int): Seed is used as entropy source for the Random number engines to generate pseudo-random numbers.
The value must be non-negative. Default: None, which will be treated as 0.
Returns:
Tensor. The shape should be equal to the broadcasted shape between the input `shape` and shapes
of `mean` and `stddev`.
The dtype is float32.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor, ops
>>> import mindspore
>>> shape = (3, 1, 2)
>>> mean = Tensor(np.array([[3, 4], [5, 6]]), mindspore.float32)
>>> stddev = Tensor(1.0, mindspore.float32)
>>> output = ops.normal(shape, mean, stddev, seed=5)
>>> result = output.shape
>>> print(result)
(3, 2, 2)
>>> shape = (3, 1, 3)
>>> mean = Tensor(np.array([[3, 4, 3], [3, 5, 6]]), mindspore.float32)
>>> stddev = Tensor(1.0, mindspore.float32)
>>> output = ops.normal(shape, mean, stddev, seed=5)
>>> result = output.shape
>>> print(result)
(3, 2, 3)
>>> shape = (3, 1, 3)
>>> mean = Tensor(np.array([[1, 2, 3], [3, 4, 3], [3, 5, 6]]), mindspore.float32)
>>> stddev = Tensor(1.0, mindspore.float32)
>>> output = ops.normal(shape, mean, stddev, seed=5)
>>> result = output.shape
>>> print(result)
(3, 3, 3) | Generates random numbers according to the Normal (or Gaussian) random number distribution. | [
"Generates",
"random",
"numbers",
"according",
"to",
"the",
"Normal",
"(",
"or",
"Gaussian",
")",
"random",
"number",
"distribution",
"."
] | def normal(shape, mean, stddev, seed=None):
"""
Generates random numbers according to the Normal (or Gaussian) random number distribution.
Args:
shape (tuple): The shape of random tensor to be generated.
The format is :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
mean (Tensor): The mean μ distribution parameter, which specifies the location of the peak,
with data type in [int8, int16, int32, int64, float16, float32].
stddev (Tensor): The deviation σ distribution parameter. It should be greater than 0,
with data type in [int8, int16, int32, int64, float16, float32].
seed (int): Seed is used as entropy source for the Random number engines to generate pseudo-random numbers.
The value must be non-negative. Default: None, which will be treated as 0.
Returns:
Tensor. The shape should be equal to the broadcasted shape between the input `shape` and shapes
of `mean` and `stddev`.
The dtype is float32.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor, ops
>>> import mindspore
>>> shape = (3, 1, 2)
>>> mean = Tensor(np.array([[3, 4], [5, 6]]), mindspore.float32)
>>> stddev = Tensor(1.0, mindspore.float32)
>>> output = ops.normal(shape, mean, stddev, seed=5)
>>> result = output.shape
>>> print(result)
(3, 2, 2)
>>> shape = (3, 1, 3)
>>> mean = Tensor(np.array([[3, 4, 3], [3, 5, 6]]), mindspore.float32)
>>> stddev = Tensor(1.0, mindspore.float32)
>>> output = ops.normal(shape, mean, stddev, seed=5)
>>> result = output.shape
>>> print(result)
(3, 2, 3)
>>> shape = (3, 1, 3)
>>> mean = Tensor(np.array([[1, 2, 3], [3, 4, 3], [3, 5, 6]]), mindspore.float32)
>>> stddev = Tensor(1.0, mindspore.float32)
>>> output = ops.normal(shape, mean, stddev, seed=5)
>>> result = output.shape
>>> print(result)
(3, 3, 3)
"""
mean_dtype = F.dtype(mean)
stddev_dtype = F.dtype(stddev)
const_utils.check_type_valid(mean_dtype, mstype.int_type + (mstype.float16, mstype.float32), 'normal')
const_utils.check_type_valid(stddev_dtype, mstype.int_type + (mstype.float16, mstype.float32), 'normal')
seed1, seed2 = _get_seed(seed, "normal")
stdnormal = P.StandardNormal(seed1, seed2)
random_normal = stdnormal(shape)
value = random_normal * stddev + mean
return value | [
"def",
"normal",
"(",
"shape",
",",
"mean",
",",
"stddev",
",",
"seed",
"=",
"None",
")",
":",
"mean_dtype",
"=",
"F",
".",
"dtype",
"(",
"mean",
")",
"stddev_dtype",
"=",
"F",
".",
"dtype",
"(",
"stddev",
")",
"const_utils",
".",
"check_type_valid",
"(",
"mean_dtype",
",",
"mstype",
".",
"int_type",
"+",
"(",
"mstype",
".",
"float16",
",",
"mstype",
".",
"float32",
")",
",",
"'normal'",
")",
"const_utils",
".",
"check_type_valid",
"(",
"stddev_dtype",
",",
"mstype",
".",
"int_type",
"+",
"(",
"mstype",
".",
"float16",
",",
"mstype",
".",
"float32",
")",
",",
"'normal'",
")",
"seed1",
",",
"seed2",
"=",
"_get_seed",
"(",
"seed",
",",
"\"normal\"",
")",
"stdnormal",
"=",
"P",
".",
"StandardNormal",
"(",
"seed1",
",",
"seed2",
")",
"random_normal",
"=",
"stdnormal",
"(",
"shape",
")",
"value",
"=",
"random_normal",
"*",
"stddev",
"+",
"mean",
"return",
"value"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/random_ops.py#L30-L85 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | TreeCtrl.SetSpacing | (*args, **kwargs) | return _controls_.TreeCtrl_SetSpacing(*args, **kwargs) | SetSpacing(self, unsigned int spacing) | SetSpacing(self, unsigned int spacing) | [
"SetSpacing",
"(",
"self",
"unsigned",
"int",
"spacing",
")"
] | def SetSpacing(*args, **kwargs):
"""SetSpacing(self, unsigned int spacing)"""
return _controls_.TreeCtrl_SetSpacing(*args, **kwargs) | [
"def",
"SetSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_SetSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5232-L5234 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/metric_spec.py | python | MetricSpec.create_metric_ops | (self, inputs, labels, predictions) | Connect our `metric_fn` to the specified members of the given dicts.
This function will call the `metric_fn` given in our constructor as follows:
```
metric_fn(predictions[self.prediction_key],
labels[self.label_key],
weights=weights[self.weight_key])
```
And returns the result. The `weights` argument is only passed if
`self.weight_key` is not `None`.
`predictions` and `labels` may be single tensors as well as dicts. If
`predictions` is a single tensor, `self.prediction_key` must be `None`. If
`predictions` is a single element dict, `self.prediction_key` is allowed to
be `None`. Conversely, if `labels` is a single tensor, `self.label_key` must
be `None`. If `labels` is a single element dict, `self.label_key` is allowed
to be `None`.
Args:
inputs: A dict of inputs produced by the `input_fn`
labels: A dict of labels or a single label tensor produced by the
`input_fn`.
predictions: A dict of predictions or a single tensor produced by the
`model_fn`.
Returns:
The result of calling `metric_fn`.
Raises:
ValueError: If `predictions` or `labels` is a single `Tensor` and
`self.prediction_key` or `self.label_key` is not `None`; or if
`self.label_key` is `None` but `labels` is a dict with more than one
element, or if `self.prediction_key` is `None` but `predictions` is a
dict with more than one element. | Connect our `metric_fn` to the specified members of the given dicts. | [
"Connect",
"our",
"metric_fn",
"to",
"the",
"specified",
"members",
"of",
"the",
"given",
"dicts",
"."
] | def create_metric_ops(self, inputs, labels, predictions):
"""Connect our `metric_fn` to the specified members of the given dicts.
This function will call the `metric_fn` given in our constructor as follows:
```
metric_fn(predictions[self.prediction_key],
labels[self.label_key],
weights=weights[self.weight_key])
```
And returns the result. The `weights` argument is only passed if
`self.weight_key` is not `None`.
`predictions` and `labels` may be single tensors as well as dicts. If
`predictions` is a single tensor, `self.prediction_key` must be `None`. If
`predictions` is a single element dict, `self.prediction_key` is allowed to
be `None`. Conversely, if `labels` is a single tensor, `self.label_key` must
be `None`. If `labels` is a single element dict, `self.label_key` is allowed
to be `None`.
Args:
inputs: A dict of inputs produced by the `input_fn`
labels: A dict of labels or a single label tensor produced by the
`input_fn`.
predictions: A dict of predictions or a single tensor produced by the
`model_fn`.
Returns:
The result of calling `metric_fn`.
Raises:
ValueError: If `predictions` or `labels` is a single `Tensor` and
`self.prediction_key` or `self.label_key` is not `None`; or if
`self.label_key` is `None` but `labels` is a dict with more than one
element, or if `self.prediction_key` is `None` but `predictions` is a
dict with more than one element.
"""
def _get_dict(name, dict_or_tensor, key):
"""Get a single tensor or an element of a dict or raise ValueError."""
if key:
if not isinstance(dict_or_tensor, dict):
raise ValueError('MetricSpec with ' + name + '_key specified'
' requires ' +
name + 's dict, got %s.\n' % dict_or_tensor +
'You must not provide a %s_key if you ' % name +
'only have a single Tensor as %ss.' % name)
if key not in dict_or_tensor:
raise KeyError(
'Key \'%s\' missing from %s.' % (key, dict_or_tensor.keys()))
return dict_or_tensor[key]
else:
if isinstance(dict_or_tensor, dict):
if len(dict_or_tensor) != 1:
raise ValueError('MetricSpec without specified ' + name + '_key'
' requires ' + name + 's tensor or single element'
' dict, got %s' % dict_or_tensor)
return six.next(six.itervalues(dict_or_tensor))
return dict_or_tensor
# Get the predictions.
prediction = _get_dict('prediction', predictions, self.prediction_key)
# Get the labels.
label = _get_dict('label', labels, self.label_key)
try:
return self.metric_fn(
labels=label,
predictions=prediction,
weights=inputs[self.weight_key] if self.weight_key else None)
except Exception as ex:
logging.error('Could not create metric ops for %s, %s.' % (self, ex))
raise | [
"def",
"create_metric_ops",
"(",
"self",
",",
"inputs",
",",
"labels",
",",
"predictions",
")",
":",
"def",
"_get_dict",
"(",
"name",
",",
"dict_or_tensor",
",",
"key",
")",
":",
"\"\"\"Get a single tensor or an element of a dict or raise ValueError.\"\"\"",
"if",
"key",
":",
"if",
"not",
"isinstance",
"(",
"dict_or_tensor",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'MetricSpec with '",
"+",
"name",
"+",
"'_key specified'",
"' requires '",
"+",
"name",
"+",
"'s dict, got %s.\\n'",
"%",
"dict_or_tensor",
"+",
"'You must not provide a %s_key if you '",
"%",
"name",
"+",
"'only have a single Tensor as %ss.'",
"%",
"name",
")",
"if",
"key",
"not",
"in",
"dict_or_tensor",
":",
"raise",
"KeyError",
"(",
"'Key \\'%s\\' missing from %s.'",
"%",
"(",
"key",
",",
"dict_or_tensor",
".",
"keys",
"(",
")",
")",
")",
"return",
"dict_or_tensor",
"[",
"key",
"]",
"else",
":",
"if",
"isinstance",
"(",
"dict_or_tensor",
",",
"dict",
")",
":",
"if",
"len",
"(",
"dict_or_tensor",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'MetricSpec without specified '",
"+",
"name",
"+",
"'_key'",
"' requires '",
"+",
"name",
"+",
"'s tensor or single element'",
"' dict, got %s'",
"%",
"dict_or_tensor",
")",
"return",
"six",
".",
"next",
"(",
"six",
".",
"itervalues",
"(",
"dict_or_tensor",
")",
")",
"return",
"dict_or_tensor",
"# Get the predictions.",
"prediction",
"=",
"_get_dict",
"(",
"'prediction'",
",",
"predictions",
",",
"self",
".",
"prediction_key",
")",
"# Get the labels.",
"label",
"=",
"_get_dict",
"(",
"'label'",
",",
"labels",
",",
"self",
".",
"label_key",
")",
"try",
":",
"return",
"self",
".",
"metric_fn",
"(",
"labels",
"=",
"label",
",",
"predictions",
"=",
"prediction",
",",
"weights",
"=",
"inputs",
"[",
"self",
".",
"weight_key",
"]",
"if",
"self",
".",
"weight_key",
"else",
"None",
")",
"except",
"Exception",
"as",
"ex",
":",
"logging",
".",
"error",
"(",
"'Could not create metric ops for %s, %s.'",
"%",
"(",
"self",
",",
"ex",
")",
")",
"raise"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/metric_spec.py#L360-L433 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode_support.py | python | _Py_ISCARRIAGERETURN | (ch) | return _Py_ctype_islinebreak[_Py_CHARMASK(ch)] & _PY_CTF_LB.CARRIAGE_RETURN | Check if character is carriage return `\r` | Check if character is carriage return `\r` | [
"Check",
"if",
"character",
"is",
"carriage",
"return",
"\\",
"r"
] | def _Py_ISCARRIAGERETURN(ch):
"""Check if character is carriage return `\r`"""
return _Py_ctype_islinebreak[_Py_CHARMASK(ch)] & _PY_CTF_LB.CARRIAGE_RETURN | [
"def",
"_Py_ISCARRIAGERETURN",
"(",
"ch",
")",
":",
"return",
"_Py_ctype_islinebreak",
"[",
"_Py_CHARMASK",
"(",
"ch",
")",
"]",
"&",
"_PY_CTF_LB",
".",
"CARRIAGE_RETURN"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode_support.py#L755-L757 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/core/defchararray.py | python | isnumeric | (a) | return _vec_string(a, bool_, 'isnumeric') | For each element, return True if there are only numeric
characters in the element.
Calls `unicode.isnumeric` element-wise.
Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. ``U+2155,
VULGAR FRACTION ONE FIFTH``.
Parameters
----------
a : array_like, unicode
Input array.
Returns
-------
out : ndarray, bool
Array of booleans of same shape as `a`.
See Also
--------
unicode.isnumeric | For each element, return True if there are only numeric
characters in the element. | [
"For",
"each",
"element",
"return",
"True",
"if",
"there",
"are",
"only",
"numeric",
"characters",
"in",
"the",
"element",
"."
] | def isnumeric(a):
"""
For each element, return True if there are only numeric
characters in the element.
Calls `unicode.isnumeric` element-wise.
Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. ``U+2155,
VULGAR FRACTION ONE FIFTH``.
Parameters
----------
a : array_like, unicode
Input array.
Returns
-------
out : ndarray, bool
Array of booleans of same shape as `a`.
See Also
--------
unicode.isnumeric
"""
if _use_unicode(a) != unicode_:
raise TypeError("isnumeric is only available for Unicode strings and arrays")
return _vec_string(a, bool_, 'isnumeric') | [
"def",
"isnumeric",
"(",
"a",
")",
":",
"if",
"_use_unicode",
"(",
"a",
")",
"!=",
"unicode_",
":",
"raise",
"TypeError",
"(",
"\"isnumeric is only available for Unicode strings and arrays\"",
")",
"return",
"_vec_string",
"(",
"a",
",",
"bool_",
",",
"'isnumeric'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/defchararray.py#L1742-L1770 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | tools/clang_format.py | python | main | () | Main entry point | Main entry point | [
"Main",
"entry",
"point"
] | def main():
"""Main entry point
"""
args = parse_args()
if hasattr(args, "func"):
args.func(args) | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"if",
"hasattr",
"(",
"args",
",",
"\"func\"",
")",
":",
"args",
".",
"func",
"(",
"args",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/tools/clang_format.py#L817-L822 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/format/policy_templates/writers/xml_formatted_writer.py | python | XMLFormattedWriter.AddText | (self, parent, text) | Adds text to a parent node. | Adds text to a parent node. | [
"Adds",
"text",
"to",
"a",
"parent",
"node",
"."
] | def AddText(self, parent, text):
'''Adds text to a parent node.
'''
doc = parent.ownerDocument
parent.appendChild(doc.createTextNode(text)) | [
"def",
"AddText",
"(",
"self",
",",
"parent",
",",
"text",
")",
":",
"doc",
"=",
"parent",
".",
"ownerDocument",
"parent",
".",
"appendChild",
"(",
"doc",
".",
"createTextNode",
"(",
"text",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/policy_templates/writers/xml_formatted_writer.py#L41-L45 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/dist.py | python | write_pkg_info | (self, base_dir) | Write the PKG-INFO file into the release tree. | Write the PKG-INFO file into the release tree. | [
"Write",
"the",
"PKG",
"-",
"INFO",
"file",
"into",
"the",
"release",
"tree",
"."
] | def write_pkg_info(self, base_dir):
"""Write the PKG-INFO file into the release tree.
"""
with open(os.path.join(base_dir, 'PKG-INFO'), 'w',
encoding='UTF-8') as pkg_info:
self.write_pkg_file(pkg_info) | [
"def",
"write_pkg_info",
"(",
"self",
",",
"base_dir",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"'PKG-INFO'",
")",
",",
"'w'",
",",
"encoding",
"=",
"'UTF-8'",
")",
"as",
"pkg_info",
":",
"self",
".",
"write_pkg_file",
"(",
"pkg_info",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/dist.py#L88-L93 | ||
1989Ryan/Semantic_SLAM | 0284b3f832ca431c494f9c134fe46c40ec86ee38 | Third_Part/PSPNet_Keras_tensorflow/caffe-tensorflow/examples/imagenet/models/helper.py | python | std_spec | (batch_size, isotropic=True) | return DataSpec(batch_size=batch_size, scale_size=256, crop_size=224, isotropic=isotropic) | Parameters commonly used by "post-AlexNet" architectures. | Parameters commonly used by "post-AlexNet" architectures. | [
"Parameters",
"commonly",
"used",
"by",
"post",
"-",
"AlexNet",
"architectures",
"."
] | def std_spec(batch_size, isotropic=True):
'''Parameters commonly used by "post-AlexNet" architectures.'''
return DataSpec(batch_size=batch_size, scale_size=256, crop_size=224, isotropic=isotropic) | [
"def",
"std_spec",
"(",
"batch_size",
",",
"isotropic",
"=",
"True",
")",
":",
"return",
"DataSpec",
"(",
"batch_size",
"=",
"batch_size",
",",
"scale_size",
"=",
"256",
",",
"crop_size",
"=",
"224",
",",
"isotropic",
"=",
"isotropic",
")"
] | https://github.com/1989Ryan/Semantic_SLAM/blob/0284b3f832ca431c494f9c134fe46c40ec86ee38/Third_Part/PSPNet_Keras_tensorflow/caffe-tensorflow/examples/imagenet/models/helper.py#L51-L53 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/PathList.py | python | _PathList.__init__ | (self, pathlist) | Initializes a PathList object, canonicalizing the input and
pre-processing it for quicker substitution later.
The stored representation of the PathList is a list of tuples
containing (type, value), where the "type" is one of the TYPE_*
variables defined above. We distinguish between:
strings that contain no '$' and therefore need no
delayed-evaluation string substitution (we expect that there
will be many of these and that we therefore get a pretty
big win from avoiding string substitution)
strings that contain '$' and therefore need substitution
(the hard case is things like '${TARGET.dir}/include',
which require re-evaluation for every target + source)
other objects (which may be something like an EntryProxy
that needs a method called to return a Node)
Pre-identifying the type of each element in the PathList up-front
and storing the type in the list of tuples is intended to reduce
the amount of calculation when we actually do the substitution
over and over for each target. | Initializes a PathList object, canonicalizing the input and
pre-processing it for quicker substitution later. | [
"Initializes",
"a",
"PathList",
"object",
"canonicalizing",
"the",
"input",
"and",
"pre",
"-",
"processing",
"it",
"for",
"quicker",
"substitution",
"later",
"."
] | def __init__(self, pathlist):
"""
Initializes a PathList object, canonicalizing the input and
pre-processing it for quicker substitution later.
The stored representation of the PathList is a list of tuples
containing (type, value), where the "type" is one of the TYPE_*
variables defined above. We distinguish between:
strings that contain no '$' and therefore need no
delayed-evaluation string substitution (we expect that there
will be many of these and that we therefore get a pretty
big win from avoiding string substitution)
strings that contain '$' and therefore need substitution
(the hard case is things like '${TARGET.dir}/include',
which require re-evaluation for every target + source)
other objects (which may be something like an EntryProxy
that needs a method called to return a Node)
Pre-identifying the type of each element in the PathList up-front
and storing the type in the list of tuples is intended to reduce
the amount of calculation when we actually do the substitution
over and over for each target.
"""
if SCons.Util.is_String(pathlist):
pathlist = pathlist.split(os.pathsep)
elif not SCons.Util.is_Sequence(pathlist):
pathlist = [pathlist]
pl = []
for p in pathlist:
try:
found = '$' in p
except (AttributeError, TypeError):
type = TYPE_OBJECT
else:
if not found:
type = TYPE_STRING_NO_SUBST
else:
type = TYPE_STRING_SUBST
pl.append((type, p))
self.pathlist = tuple(pl) | [
"def",
"__init__",
"(",
"self",
",",
"pathlist",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_String",
"(",
"pathlist",
")",
":",
"pathlist",
"=",
"pathlist",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"elif",
"not",
"SCons",
".",
"Util",
".",
"is_Sequence",
"(",
"pathlist",
")",
":",
"pathlist",
"=",
"[",
"pathlist",
"]",
"pl",
"=",
"[",
"]",
"for",
"p",
"in",
"pathlist",
":",
"try",
":",
"found",
"=",
"'$'",
"in",
"p",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"type",
"=",
"TYPE_OBJECT",
"else",
":",
"if",
"not",
"found",
":",
"type",
"=",
"TYPE_STRING_NO_SUBST",
"else",
":",
"type",
"=",
"TYPE_STRING_SUBST",
"pl",
".",
"append",
"(",
"(",
"type",
",",
"p",
")",
")",
"self",
".",
"pathlist",
"=",
"tuple",
"(",
"pl",
")"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/PathList.py#L70-L114 | ||
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | python/caffe/io.py | python | blobproto_to_array | (blob, return_diff=False) | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | [
"Convert",
"a",
"blob",
"proto",
"to",
"an",
"array",
".",
"In",
"default",
"we",
"will",
"just",
"return",
"the",
"data",
"unless",
"return_diff",
"is",
"True",
"in",
"which",
"case",
"we",
"will",
"return",
"the",
"diff",
"."
] | def blobproto_to_array(blob, return_diff=False):
"""
Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff.
"""
# Read the data into an array
if return_diff:
data = np.array(blob.diff)
else:
data = np.array(blob.data)
# Reshape the array
if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'):
# Use legacy 4D shape
return data.reshape(blob.num, blob.channels, blob.height, blob.width)
else:
return data.reshape(blob.shape.dim) | [
"def",
"blobproto_to_array",
"(",
"blob",
",",
"return_diff",
"=",
"False",
")",
":",
"# Read the data into an array",
"if",
"return_diff",
":",
"data",
"=",
"np",
".",
"array",
"(",
"blob",
".",
"diff",
")",
"else",
":",
"data",
"=",
"np",
".",
"array",
"(",
"blob",
".",
"data",
")",
"# Reshape the array",
"if",
"blob",
".",
"HasField",
"(",
"'num'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'channels'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'height'",
")",
"or",
"blob",
".",
"HasField",
"(",
"'width'",
")",
":",
"# Use legacy 4D shape",
"return",
"data",
".",
"reshape",
"(",
"blob",
".",
"num",
",",
"blob",
".",
"channels",
",",
"blob",
".",
"height",
",",
"blob",
".",
"width",
")",
"else",
":",
"return",
"data",
".",
"reshape",
"(",
"blob",
".",
"shape",
".",
"dim",
")"
] | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/io.py#L18-L34 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/summaries.py | python | tf_parameter_iter | (x) | Iterate over the left branches of a graph and yield sizes.
Args:
x: root of the subgraph (Tensor, Operation)
Yields:
A triple of name, number of params, and shape. | Iterate over the left branches of a graph and yield sizes. | [
"Iterate",
"over",
"the",
"left",
"branches",
"of",
"a",
"graph",
"and",
"yield",
"sizes",
"."
] | def tf_parameter_iter(x):
"""Iterate over the left branches of a graph and yield sizes.
Args:
x: root of the subgraph (Tensor, Operation)
Yields:
A triple of name, number of params, and shape.
"""
while 1:
if isinstance(x, ops.Tensor):
shape = x.get_shape().as_list()
x = x.op
else:
shape = ""
left, right = tf_left_split(x)
totals = [tf_num_params(y) for y in right]
total = sum(totals)
yield x.name, total, shape
if left is None:
break
x = left | [
"def",
"tf_parameter_iter",
"(",
"x",
")",
":",
"while",
"1",
":",
"if",
"isinstance",
"(",
"x",
",",
"ops",
".",
"Tensor",
")",
":",
"shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"x",
"=",
"x",
".",
"op",
"else",
":",
"shape",
"=",
"\"\"",
"left",
",",
"right",
"=",
"tf_left_split",
"(",
"x",
")",
"totals",
"=",
"[",
"tf_num_params",
"(",
"y",
")",
"for",
"y",
"in",
"right",
"]",
"total",
"=",
"sum",
"(",
"totals",
")",
"yield",
"x",
".",
"name",
",",
"total",
",",
"shape",
"if",
"left",
"is",
"None",
":",
"break",
"x",
"=",
"left"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/summaries.py#L185-L207 | ||
cmu-sei/pharos | af54b6ada58d50c046fa899452addce80e9ce8da | tools/ooanalyzer/ida/OOAnalyzer.py | python | PyOOAnalyzer.__parse_methods | (self, cls, methods) | return | Parse the methods defined in the JSON file | Parse the methods defined in the JSON file | [
"Parse",
"the",
"methods",
"defined",
"in",
"the",
"JSON",
"file"
] | def __parse_methods(self, cls, methods):
'''
Parse the methods defined in the JSON file
'''
print("Parsing %d methods for class %s ..." %
(len(methods), cls.ida_name))
for m in methods.values ():
meth = PyClassMethod()
meth.cls = cls
meth.is_virtual = False # no traditional methods are virtual
meth.is_ctor = False
meth.is_dtor = False
if m['type'] == "ctor":
meth.is_ctor = True
elif m['type'] == "dtor" or m['type'] == "deldtor":
meth.is_dtor = True
# this method is imported
meth.is_import = False
if m['import']:
meth.is_import = True
meth.start_ea = int(m['ea'], 16)
meth.method_name = m['name']
meth.demangled_name = m['demangled_name'] if m['demangled_name'] != "" else None
meth.userdef_name = False
flags = ida_bytes.get_flags (meth.start_ea)
# In vs2010/Lite/oo, there is a function tail at 0x403ed0. Unfortunately another
# function tail calls that chunk, and get_func(0x403ed0) refers to the larger one.
# This results in IDA helpfully saying that the function at 0x403ed0 is named
# sub_402509. Thanks IDA!
idafunc = idaapi.get_func (meth.start_ea)
is_func = idafunc is not None and idafunc.start_ea == meth.start_ea
has_name = is_func \
and ida_bytes.has_name (flags) \
and ida_bytes.has_user_name (flags) \
and idc.get_func_name(meth.start_ea) != ""
# Does IDA have a name for this function?
if has_name:
meth.method_name = idc.get_func_name(meth.start_ea)
meth.demangled_name = idc.demangle_name (meth.method_name,
idc.get_inf_attr (idc.INF_SHORT_DN))
meth.demangled_name = meth.demangled_name if meth.demangled_name != "" else None
meth.userdef_name = True
print(" - Method %s parsed" % meth.method_name)
cls.add_method(meth)
print("All methods parsed")
return | [
"def",
"__parse_methods",
"(",
"self",
",",
"cls",
",",
"methods",
")",
":",
"print",
"(",
"\"Parsing %d methods for class %s ...\"",
"%",
"(",
"len",
"(",
"methods",
")",
",",
"cls",
".",
"ida_name",
")",
")",
"for",
"m",
"in",
"methods",
".",
"values",
"(",
")",
":",
"meth",
"=",
"PyClassMethod",
"(",
")",
"meth",
".",
"cls",
"=",
"cls",
"meth",
".",
"is_virtual",
"=",
"False",
"# no traditional methods are virtual",
"meth",
".",
"is_ctor",
"=",
"False",
"meth",
".",
"is_dtor",
"=",
"False",
"if",
"m",
"[",
"'type'",
"]",
"==",
"\"ctor\"",
":",
"meth",
".",
"is_ctor",
"=",
"True",
"elif",
"m",
"[",
"'type'",
"]",
"==",
"\"dtor\"",
"or",
"m",
"[",
"'type'",
"]",
"==",
"\"deldtor\"",
":",
"meth",
".",
"is_dtor",
"=",
"True",
"# this method is imported",
"meth",
".",
"is_import",
"=",
"False",
"if",
"m",
"[",
"'import'",
"]",
":",
"meth",
".",
"is_import",
"=",
"True",
"meth",
".",
"start_ea",
"=",
"int",
"(",
"m",
"[",
"'ea'",
"]",
",",
"16",
")",
"meth",
".",
"method_name",
"=",
"m",
"[",
"'name'",
"]",
"meth",
".",
"demangled_name",
"=",
"m",
"[",
"'demangled_name'",
"]",
"if",
"m",
"[",
"'demangled_name'",
"]",
"!=",
"\"\"",
"else",
"None",
"meth",
".",
"userdef_name",
"=",
"False",
"flags",
"=",
"ida_bytes",
".",
"get_flags",
"(",
"meth",
".",
"start_ea",
")",
"# In vs2010/Lite/oo, there is a function tail at 0x403ed0. Unfortunately another",
"# function tail calls that chunk, and get_func(0x403ed0) refers to the larger one.",
"# This results in IDA helpfully saying that the function at 0x403ed0 is named",
"# sub_402509. Thanks IDA!",
"idafunc",
"=",
"idaapi",
".",
"get_func",
"(",
"meth",
".",
"start_ea",
")",
"is_func",
"=",
"idafunc",
"is",
"not",
"None",
"and",
"idafunc",
".",
"start_ea",
"==",
"meth",
".",
"start_ea",
"has_name",
"=",
"is_func",
"and",
"ida_bytes",
".",
"has_name",
"(",
"flags",
")",
"and",
"ida_bytes",
".",
"has_user_name",
"(",
"flags",
")",
"and",
"idc",
".",
"get_func_name",
"(",
"meth",
".",
"start_ea",
")",
"!=",
"\"\"",
"# Does IDA have a name for this function?",
"if",
"has_name",
":",
"meth",
".",
"method_name",
"=",
"idc",
".",
"get_func_name",
"(",
"meth",
".",
"start_ea",
")",
"meth",
".",
"demangled_name",
"=",
"idc",
".",
"demangle_name",
"(",
"meth",
".",
"method_name",
",",
"idc",
".",
"get_inf_attr",
"(",
"idc",
".",
"INF_SHORT_DN",
")",
")",
"meth",
".",
"demangled_name",
"=",
"meth",
".",
"demangled_name",
"if",
"meth",
".",
"demangled_name",
"!=",
"\"\"",
"else",
"None",
"meth",
".",
"userdef_name",
"=",
"True",
"print",
"(",
"\" - Method %s parsed\"",
"%",
"meth",
".",
"method_name",
")",
"cls",
".",
"add_method",
"(",
"meth",
")",
"print",
"(",
"\"All methods parsed\"",
")",
"return"
] | https://github.com/cmu-sei/pharos/blob/af54b6ada58d50c046fa899452addce80e9ce8da/tools/ooanalyzer/ida/OOAnalyzer.py#L422-L482 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py | python | ParseFlags | (resp) | return tuple(mo.group('flags').split()) | Convert IMAP4 flags response to python tuple. | Convert IMAP4 flags response to python tuple. | [
"Convert",
"IMAP4",
"flags",
"response",
"to",
"python",
"tuple",
"."
] | def ParseFlags(resp):
"""Convert IMAP4 flags response to python tuple."""
mo = Flags.match(resp)
if not mo:
return ()
return tuple(mo.group('flags').split()) | [
"def",
"ParseFlags",
"(",
"resp",
")",
":",
"mo",
"=",
"Flags",
".",
"match",
"(",
"resp",
")",
"if",
"not",
"mo",
":",
"return",
"(",
")",
"return",
"tuple",
"(",
"mo",
".",
"group",
"(",
"'flags'",
")",
".",
"split",
"(",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py#L1371-L1379 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/appdirs.py | python | user_data_dir | (appname=None, appauthor=None, version=None, 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.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"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:
Mac OS X: ~/Library/Application Support/<AppName> # or ~/.config/<AppName>, if the other does not exist
Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<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=None, appauthor=None, version=None, roaming=False):
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.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"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:
Mac OS X: ~/Library/Application Support/<AppName> # or ~/.config/<AppName>, if the other does not exist
Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
That means, by default "~/.local/share/<AppName>".
"""
if system == "win32":
if appauthor is None:
appauthor = appname
const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
path = os.path.normpath(_get_win_folder(const))
if appname:
if appauthor is not False:
path = os.path.join(path, appauthor, appname)
else:
path = os.path.join(path, appname)
elif system == 'darwin':
path = os.path.expanduser('~/Library/Application Support/')
if appname:
path = os.path.join(path, appname)
else:
path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path | [
"def",
"user_data_dir",
"(",
"appname",
"=",
"None",
",",
"appauthor",
"=",
"None",
",",
"version",
"=",
"None",
",",
"roaming",
"=",
"False",
")",
":",
"if",
"system",
"==",
"\"win32\"",
":",
"if",
"appauthor",
"is",
"None",
":",
"appauthor",
"=",
"appname",
"const",
"=",
"roaming",
"and",
"\"CSIDL_APPDATA\"",
"or",
"\"CSIDL_LOCAL_APPDATA\"",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"_get_win_folder",
"(",
"const",
")",
")",
"if",
"appname",
":",
"if",
"appauthor",
"is",
"not",
"False",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"appauthor",
",",
"appname",
")",
"else",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"appname",
")",
"elif",
"system",
"==",
"'darwin'",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/Library/Application Support/'",
")",
"if",
"appname",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"appname",
")",
"else",
":",
"path",
"=",
"os",
".",
"getenv",
"(",
"'XDG_DATA_HOME'",
",",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.local/share\"",
")",
")",
"if",
"appname",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"appname",
")",
"if",
"appname",
"and",
"version",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"version",
")",
"return",
"path"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/appdirs.py#L49-L101 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/ceph_manager.py | python | CephManager.contract_pool | (self, pool_name, by, min_pgs) | Decrease the number of pgs in a pool | Decrease the number of pgs in a pool | [
"Decrease",
"the",
"number",
"of",
"pgs",
"in",
"a",
"pool"
] | def contract_pool(self, pool_name, by, min_pgs):
"""
Decrease the number of pgs in a pool
"""
with self.lock:
self.log('contract_pool %s by %s min %s' % (
pool_name, str(by), str(min_pgs)))
assert isinstance(pool_name, str)
assert isinstance(by, int)
assert pool_name in self.pools
if self.get_num_creating() > 0:
self.log('too many creating')
return False
proj = self.pools[pool_name] - by
if proj < min_pgs:
self.log('would drop below min_pgs, proj %d, currently %d' % (proj,self.pools[pool_name],))
return False
self.log("decrease pool size by %d" % (by,))
new_pg_num = self.pools[pool_name] - by
self.set_pool_property(pool_name, "pg_num", new_pg_num)
self.pools[pool_name] = new_pg_num
return True | [
"def",
"contract_pool",
"(",
"self",
",",
"pool_name",
",",
"by",
",",
"min_pgs",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"log",
"(",
"'contract_pool %s by %s min %s'",
"%",
"(",
"pool_name",
",",
"str",
"(",
"by",
")",
",",
"str",
"(",
"min_pgs",
")",
")",
")",
"assert",
"isinstance",
"(",
"pool_name",
",",
"str",
")",
"assert",
"isinstance",
"(",
"by",
",",
"int",
")",
"assert",
"pool_name",
"in",
"self",
".",
"pools",
"if",
"self",
".",
"get_num_creating",
"(",
")",
">",
"0",
":",
"self",
".",
"log",
"(",
"'too many creating'",
")",
"return",
"False",
"proj",
"=",
"self",
".",
"pools",
"[",
"pool_name",
"]",
"-",
"by",
"if",
"proj",
"<",
"min_pgs",
":",
"self",
".",
"log",
"(",
"'would drop below min_pgs, proj %d, currently %d'",
"%",
"(",
"proj",
",",
"self",
".",
"pools",
"[",
"pool_name",
"]",
",",
")",
")",
"return",
"False",
"self",
".",
"log",
"(",
"\"decrease pool size by %d\"",
"%",
"(",
"by",
",",
")",
")",
"new_pg_num",
"=",
"self",
".",
"pools",
"[",
"pool_name",
"]",
"-",
"by",
"self",
".",
"set_pool_property",
"(",
"pool_name",
",",
"\"pg_num\"",
",",
"new_pg_num",
")",
"self",
".",
"pools",
"[",
"pool_name",
"]",
"=",
"new_pg_num",
"return",
"True"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_manager.py#L2252-L2273 | ||
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/grassprovider/Grass7Algorithm.py | python | Grass7Algorithm.loadRasterLayer | (self, name, layer, external=None, band=1, destName=None) | Creates a dedicated command to load a raster into
the temporary GRASS DB.
:param name: name of the parameter.
:param layer: QgsMapLayer for the raster layer.
:param external: use r.external if True, r.in.gdal if False.
:param band: imports only specified band. None for all bands.
:param destName: force the destination name of the raster. | Creates a dedicated command to load a raster into
the temporary GRASS DB.
:param name: name of the parameter.
:param layer: QgsMapLayer for the raster layer.
:param external: use r.external if True, r.in.gdal if False.
:param band: imports only specified band. None for all bands.
:param destName: force the destination name of the raster. | [
"Creates",
"a",
"dedicated",
"command",
"to",
"load",
"a",
"raster",
"into",
"the",
"temporary",
"GRASS",
"DB",
".",
":",
"param",
"name",
":",
"name",
"of",
"the",
"parameter",
".",
":",
"param",
"layer",
":",
"QgsMapLayer",
"for",
"the",
"raster",
"layer",
".",
":",
"param",
"external",
":",
"use",
"r",
".",
"external",
"if",
"True",
"r",
".",
"in",
".",
"gdal",
"if",
"False",
".",
":",
"param",
"band",
":",
"imports",
"only",
"specified",
"band",
".",
"None",
"for",
"all",
"bands",
".",
":",
"param",
"destName",
":",
"force",
"the",
"destination",
"name",
"of",
"the",
"raster",
"."
] | def loadRasterLayer(self, name, layer, external=None, band=1, destName=None):
"""
Creates a dedicated command to load a raster into
the temporary GRASS DB.
:param name: name of the parameter.
:param layer: QgsMapLayer for the raster layer.
:param external: use r.external if True, r.in.gdal if False.
:param band: imports only specified band. None for all bands.
:param destName: force the destination name of the raster.
"""
if external is None:
external = ProcessingConfig.getSetting(Grass7Utils.GRASS_USE_REXTERNAL)
self.inputLayers.append(layer)
self.setSessionProjectionFromLayer(layer)
if not destName:
destName = 'rast_{}'.format(os.path.basename(getTempFilename()))
self.exportedLayers[name] = destName
command = '{0} input="{1}" {2}output="{3}" --overwrite -o'.format(
'r.external' if external else 'r.in.gdal',
os.path.normpath(layer.source()),
'band={} '.format(band) if band else '',
destName)
self.commands.append(command) | [
"def",
"loadRasterLayer",
"(",
"self",
",",
"name",
",",
"layer",
",",
"external",
"=",
"None",
",",
"band",
"=",
"1",
",",
"destName",
"=",
"None",
")",
":",
"if",
"external",
"is",
"None",
":",
"external",
"=",
"ProcessingConfig",
".",
"getSetting",
"(",
"Grass7Utils",
".",
"GRASS_USE_REXTERNAL",
")",
"self",
".",
"inputLayers",
".",
"append",
"(",
"layer",
")",
"self",
".",
"setSessionProjectionFromLayer",
"(",
"layer",
")",
"if",
"not",
"destName",
":",
"destName",
"=",
"'rast_{}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"getTempFilename",
"(",
")",
")",
")",
"self",
".",
"exportedLayers",
"[",
"name",
"]",
"=",
"destName",
"command",
"=",
"'{0} input=\"{1}\" {2}output=\"{3}\" --overwrite -o'",
".",
"format",
"(",
"'r.external'",
"if",
"external",
"else",
"'r.in.gdal'",
",",
"os",
".",
"path",
".",
"normpath",
"(",
"layer",
".",
"source",
"(",
")",
")",
",",
"'band={} '",
".",
"format",
"(",
"band",
")",
"if",
"band",
"else",
"''",
",",
"destName",
")",
"self",
".",
"commands",
".",
"append",
"(",
"command",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/grassprovider/Grass7Algorithm.py#L729-L751 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | TextAttr.HasBulletName | (*args, **kwargs) | return _controls_.TextAttr_HasBulletName(*args, **kwargs) | HasBulletName(self) -> bool | HasBulletName(self) -> bool | [
"HasBulletName",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasBulletName(*args, **kwargs):
"""HasBulletName(self) -> bool"""
return _controls_.TextAttr_HasBulletName(*args, **kwargs) | [
"def",
"HasBulletName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasBulletName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L1864-L1866 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/input.py | python | shuffle_batch_join | (tensors_list, batch_size, capacity,
min_after_dequeue, seed=None, enqueue_many=False,
shapes=None, allow_smaller_final_batch=False,
shared_name=None, name=None) | return _shuffle_batch_join(
tensors_list,
batch_size,
capacity,
min_after_dequeue,
keep_input=True,
seed=seed,
enqueue_many=enqueue_many,
shapes=shapes,
allow_smaller_final_batch=allow_smaller_final_batch,
shared_name=shared_name,
name=name) | Create batches by randomly shuffling tensors.
The `tensors_list` argument is a list of tuples of tensors, or a list of
dictionaries of tensors. Each element in the list is treated similarly
to the `tensors` argument of `tf.compat.v1.train.shuffle_batch()`.
This version enqueues a different list of tensors in different threads.
It adds the following to the current `Graph`:
* A shuffling queue into which tensors from `tensors_list` are enqueued.
* A `dequeue_many` operation to create batches from the queue.
* A `QueueRunner` to `QUEUE_RUNNER` collection, to enqueue the tensors
from `tensors_list`.
`len(tensors_list)` threads will be started, with thread `i` enqueuing
the tensors from `tensors_list[i]`. `tensors_list[i1][j]` must match
`tensors_list[i2][j]` in type and shape, except in the first dimension if
`enqueue_many` is true.
If `enqueue_many` is `False`, each `tensors_list[i]` is assumed
to represent a single example. An input tensor with shape `[x, y, z]`
will be output as a tensor with shape `[batch_size, x, y, z]`.
If `enqueue_many` is `True`, `tensors_list[i]` is assumed to
represent a batch of examples, where the first dimension is indexed
by example, and all members of `tensors_list[i]` should have the
same size in the first dimension. If an input tensor has shape `[*, x,
y, z]`, the output will have shape `[batch_size, x, y, z]`.
The `capacity` argument controls the how long the prefetching is allowed to
grow the queues.
The returned operation is a dequeue operation and will throw
`tf.errors.OutOfRangeError` if the input queue is exhausted. If this
operation is feeding another input queue, its queue runner will catch
this exception, however, if this operation is used in your main thread
you are responsible for catching this yourself.
If `allow_smaller_final_batch` is `True`, a smaller batch value than
`batch_size` is returned when the queue is closed and there are not enough
elements to fill the batch, otherwise the pending elements are discarded.
In addition, all output tensors' static shapes, as accessed via the
`shape` property will have a first `Dimension` value of `None`, and
operations that depend on fixed batch_size would fail.
Args:
tensors_list: A list of tuples or dictionaries of tensors to enqueue.
batch_size: An integer. The new batch size pulled from the queue.
capacity: An integer. The maximum number of elements in the queue.
min_after_dequeue: Minimum number elements in the queue after a
dequeue, used to ensure a level of mixing of elements.
seed: Seed for the random shuffling within the queue.
enqueue_many: Whether each tensor in `tensor_list_list` is a single
example.
shapes: (Optional) The shapes for each example. Defaults to the
inferred shapes for `tensors_list[i]`.
allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final
batch to be smaller if there are insufficient items left in the queue.
shared_name: (optional). If set, this queue will be shared under the given
name across multiple sessions.
name: (Optional) A name for the operations.
Returns:
A list or dictionary of tensors with the same number and types as
`tensors_list[i]`.
Raises:
ValueError: If the `shapes` are not specified, and cannot be
inferred from the elements of `tensors_list`.
@compatibility(eager)
Input pipelines based on Queues are not supported when eager execution is
enabled. Please use the `tf.data` API to ingest data under eager execution.
@end_compatibility | Create batches by randomly shuffling tensors. | [
"Create",
"batches",
"by",
"randomly",
"shuffling",
"tensors",
"."
] | def shuffle_batch_join(tensors_list, batch_size, capacity,
min_after_dequeue, seed=None, enqueue_many=False,
shapes=None, allow_smaller_final_batch=False,
shared_name=None, name=None):
"""Create batches by randomly shuffling tensors.
The `tensors_list` argument is a list of tuples of tensors, or a list of
dictionaries of tensors. Each element in the list is treated similarly
to the `tensors` argument of `tf.compat.v1.train.shuffle_batch()`.
This version enqueues a different list of tensors in different threads.
It adds the following to the current `Graph`:
* A shuffling queue into which tensors from `tensors_list` are enqueued.
* A `dequeue_many` operation to create batches from the queue.
* A `QueueRunner` to `QUEUE_RUNNER` collection, to enqueue the tensors
from `tensors_list`.
`len(tensors_list)` threads will be started, with thread `i` enqueuing
the tensors from `tensors_list[i]`. `tensors_list[i1][j]` must match
`tensors_list[i2][j]` in type and shape, except in the first dimension if
`enqueue_many` is true.
If `enqueue_many` is `False`, each `tensors_list[i]` is assumed
to represent a single example. An input tensor with shape `[x, y, z]`
will be output as a tensor with shape `[batch_size, x, y, z]`.
If `enqueue_many` is `True`, `tensors_list[i]` is assumed to
represent a batch of examples, where the first dimension is indexed
by example, and all members of `tensors_list[i]` should have the
same size in the first dimension. If an input tensor has shape `[*, x,
y, z]`, the output will have shape `[batch_size, x, y, z]`.
The `capacity` argument controls the how long the prefetching is allowed to
grow the queues.
The returned operation is a dequeue operation and will throw
`tf.errors.OutOfRangeError` if the input queue is exhausted. If this
operation is feeding another input queue, its queue runner will catch
this exception, however, if this operation is used in your main thread
you are responsible for catching this yourself.
If `allow_smaller_final_batch` is `True`, a smaller batch value than
`batch_size` is returned when the queue is closed and there are not enough
elements to fill the batch, otherwise the pending elements are discarded.
In addition, all output tensors' static shapes, as accessed via the
`shape` property will have a first `Dimension` value of `None`, and
operations that depend on fixed batch_size would fail.
Args:
tensors_list: A list of tuples or dictionaries of tensors to enqueue.
batch_size: An integer. The new batch size pulled from the queue.
capacity: An integer. The maximum number of elements in the queue.
min_after_dequeue: Minimum number elements in the queue after a
dequeue, used to ensure a level of mixing of elements.
seed: Seed for the random shuffling within the queue.
enqueue_many: Whether each tensor in `tensor_list_list` is a single
example.
shapes: (Optional) The shapes for each example. Defaults to the
inferred shapes for `tensors_list[i]`.
allow_smaller_final_batch: (Optional) Boolean. If `True`, allow the final
batch to be smaller if there are insufficient items left in the queue.
shared_name: (optional). If set, this queue will be shared under the given
name across multiple sessions.
name: (Optional) A name for the operations.
Returns:
A list or dictionary of tensors with the same number and types as
`tensors_list[i]`.
Raises:
ValueError: If the `shapes` are not specified, and cannot be
inferred from the elements of `tensors_list`.
@compatibility(eager)
Input pipelines based on Queues are not supported when eager execution is
enabled. Please use the `tf.data` API to ingest data under eager execution.
@end_compatibility
"""
return _shuffle_batch_join(
tensors_list,
batch_size,
capacity,
min_after_dequeue,
keep_input=True,
seed=seed,
enqueue_many=enqueue_many,
shapes=shapes,
allow_smaller_final_batch=allow_smaller_final_batch,
shared_name=shared_name,
name=name) | [
"def",
"shuffle_batch_join",
"(",
"tensors_list",
",",
"batch_size",
",",
"capacity",
",",
"min_after_dequeue",
",",
"seed",
"=",
"None",
",",
"enqueue_many",
"=",
"False",
",",
"shapes",
"=",
"None",
",",
"allow_smaller_final_batch",
"=",
"False",
",",
"shared_name",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"_shuffle_batch_join",
"(",
"tensors_list",
",",
"batch_size",
",",
"capacity",
",",
"min_after_dequeue",
",",
"keep_input",
"=",
"True",
",",
"seed",
"=",
"seed",
",",
"enqueue_many",
"=",
"enqueue_many",
",",
"shapes",
"=",
"shapes",
",",
"allow_smaller_final_batch",
"=",
"allow_smaller_final_batch",
",",
"shared_name",
"=",
"shared_name",
",",
"name",
"=",
"name",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/input.py#L1416-L1506 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | IKObjective.getRotationAxis | (self) | return _robotsim.IKObjective_getRotationAxis(self) | r"""
getRotationAxis(IKObjective self)
For axis rotation constraints, returns the local and global axes. | r"""
getRotationAxis(IKObjective self) | [
"r",
"getRotationAxis",
"(",
"IKObjective",
"self",
")"
] | def getRotationAxis(self) -> "void":
r"""
getRotationAxis(IKObjective self)
For axis rotation constraints, returns the local and global axes.
"""
return _robotsim.IKObjective_getRotationAxis(self) | [
"def",
"getRotationAxis",
"(",
"self",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"IKObjective_getRotationAxis",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L6517-L6525 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/third_party/jinja2/compiler.py | python | CodeGenerator.position | (self, node) | return rv | Return a human readable position for the node. | Return a human readable position for the node. | [
"Return",
"a",
"human",
"readable",
"position",
"for",
"the",
"node",
"."
] | def position(self, node):
"""Return a human readable position for the node."""
rv = 'line %d' % node.lineno
if self.name is not None:
rv += ' in ' + repr(self.name)
return rv | [
"def",
"position",
"(",
"self",
",",
"node",
")",
":",
"rv",
"=",
"'line %d'",
"%",
"node",
".",
"lineno",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"rv",
"+=",
"' in '",
"+",
"repr",
"(",
"self",
".",
"name",
")",
"return",
"rv"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/compiler.py#L752-L757 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py | python | DataFrame.to_string | (
self,
buf: Optional[FilePathOrBuffer[str]] = None,
columns: Optional[Sequence[str]] = None,
col_space: Optional[int] = None,
header: Union[bool, Sequence[str]] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: Optional[fmt.formatters_type] = None,
float_format: Optional[fmt.float_format_type] = None,
sparsify: Optional[bool] = None,
index_names: bool = True,
justify: Optional[str] = None,
max_rows: Optional[int] = None,
min_rows: Optional[int] = None,
max_cols: Optional[int] = None,
show_dimensions: bool = False,
decimal: str = ".",
line_width: Optional[int] = None,
max_colwidth: Optional[int] = None,
encoding: Optional[str] = None,
) | Render a DataFrame to a console-friendly tabular output.
%(shared_params)s
line_width : int, optional
Width to wrap a line in characters.
max_colwidth : int, optional
Max width to truncate each column in characters. By default, no limit.
.. versionadded:: 1.0.0
encoding : str, default "utf-8"
Set character encoding.
.. versionadded:: 1.0
%(returns)s
See Also
--------
to_html : Convert DataFrame to HTML.
Examples
--------
>>> d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
>>> df = pd.DataFrame(d)
>>> print(df.to_string())
col1 col2
0 1 4
1 2 5
2 3 6 | Render a DataFrame to a console-friendly tabular output.
%(shared_params)s
line_width : int, optional
Width to wrap a line in characters.
max_colwidth : int, optional
Max width to truncate each column in characters. By default, no limit. | [
"Render",
"a",
"DataFrame",
"to",
"a",
"console",
"-",
"friendly",
"tabular",
"output",
".",
"%",
"(",
"shared_params",
")",
"s",
"line_width",
":",
"int",
"optional",
"Width",
"to",
"wrap",
"a",
"line",
"in",
"characters",
".",
"max_colwidth",
":",
"int",
"optional",
"Max",
"width",
"to",
"truncate",
"each",
"column",
"in",
"characters",
".",
"By",
"default",
"no",
"limit",
"."
] | def to_string(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
columns: Optional[Sequence[str]] = None,
col_space: Optional[int] = None,
header: Union[bool, Sequence[str]] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: Optional[fmt.formatters_type] = None,
float_format: Optional[fmt.float_format_type] = None,
sparsify: Optional[bool] = None,
index_names: bool = True,
justify: Optional[str] = None,
max_rows: Optional[int] = None,
min_rows: Optional[int] = None,
max_cols: Optional[int] = None,
show_dimensions: bool = False,
decimal: str = ".",
line_width: Optional[int] = None,
max_colwidth: Optional[int] = None,
encoding: Optional[str] = None,
) -> Optional[str]:
"""
Render a DataFrame to a console-friendly tabular output.
%(shared_params)s
line_width : int, optional
Width to wrap a line in characters.
max_colwidth : int, optional
Max width to truncate each column in characters. By default, no limit.
.. versionadded:: 1.0.0
encoding : str, default "utf-8"
Set character encoding.
.. versionadded:: 1.0
%(returns)s
See Also
--------
to_html : Convert DataFrame to HTML.
Examples
--------
>>> d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
>>> df = pd.DataFrame(d)
>>> print(df.to_string())
col1 col2
0 1 4
1 2 5
2 3 6
"""
from pandas import option_context
with option_context("display.max_colwidth", max_colwidth):
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
formatters=formatters,
float_format=float_format,
sparsify=sparsify,
justify=justify,
index_names=index_names,
header=header,
index=index,
min_rows=min_rows,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=decimal,
line_width=line_width,
)
return formatter.to_string(buf=buf, encoding=encoding) | [
"def",
"to_string",
"(",
"self",
",",
"buf",
":",
"Optional",
"[",
"FilePathOrBuffer",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"columns",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"col_space",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"header",
":",
"Union",
"[",
"bool",
",",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"True",
",",
"index",
":",
"bool",
"=",
"True",
",",
"na_rep",
":",
"str",
"=",
"\"NaN\"",
",",
"formatters",
":",
"Optional",
"[",
"fmt",
".",
"formatters_type",
"]",
"=",
"None",
",",
"float_format",
":",
"Optional",
"[",
"fmt",
".",
"float_format_type",
"]",
"=",
"None",
",",
"sparsify",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"index_names",
":",
"bool",
"=",
"True",
",",
"justify",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"max_rows",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"min_rows",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"max_cols",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"show_dimensions",
":",
"bool",
"=",
"False",
",",
"decimal",
":",
"str",
"=",
"\".\"",
",",
"line_width",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"max_colwidth",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"encoding",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"from",
"pandas",
"import",
"option_context",
"with",
"option_context",
"(",
"\"display.max_colwidth\"",
",",
"max_colwidth",
")",
":",
"formatter",
"=",
"fmt",
".",
"DataFrameFormatter",
"(",
"self",
",",
"columns",
"=",
"columns",
",",
"col_space",
"=",
"col_space",
",",
"na_rep",
"=",
"na_rep",
",",
"formatters",
"=",
"formatters",
",",
"float_format",
"=",
"float_format",
",",
"sparsify",
"=",
"sparsify",
",",
"justify",
"=",
"justify",
",",
"index_names",
"=",
"index_names",
",",
"header",
"=",
"header",
",",
"index",
"=",
"index",
",",
"min_rows",
"=",
"min_rows",
",",
"max_rows",
"=",
"max_rows",
",",
"max_cols",
"=",
"max_cols",
",",
"show_dimensions",
"=",
"show_dimensions",
",",
"decimal",
"=",
"decimal",
",",
"line_width",
"=",
"line_width",
",",
")",
"return",
"formatter",
".",
"to_string",
"(",
"buf",
"=",
"buf",
",",
"encoding",
"=",
"encoding",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/frame.py#L747-L820 | ||
Manu343726/siplasplas | 9fae7559f87087cf8ef34f04bd1e774b84b2ea9c | reference/cindex.py | python | Cursor.translation_unit | (self) | return self._tu | Returns the TranslationUnit to which this Cursor belongs. | Returns the TranslationUnit to which this Cursor belongs. | [
"Returns",
"the",
"TranslationUnit",
"to",
"which",
"this",
"Cursor",
"belongs",
"."
] | def translation_unit(self):
"""Returns the TranslationUnit to which this Cursor belongs."""
# If this triggers an AttributeError, the instance was not properly
# created.
return self._tu | [
"def",
"translation_unit",
"(",
"self",
")",
":",
"# If this triggers an AttributeError, the instance was not properly",
"# created.",
"return",
"self",
".",
"_tu"
] | https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1445-L1449 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/numarray/numerictypes.py | python | NumericType.__getstate__ | (self) | support pickling protocol... no __setstate__ required. | support pickling protocol... no __setstate__ required. | [
"support",
"pickling",
"protocol",
"...",
"no",
"__setstate__",
"required",
"."
] | def __getstate__(self):
"""support pickling protocol... no __setstate__ required."""
False | [
"def",
"__getstate__",
"(",
"self",
")",
":",
"False"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/numarray/numerictypes.py#L133-L135 | ||
nasa/astrobee | 9241e67e6692810d6e275abb3165b6d02f4ca5ef | localization/sparse_mapping/tools/grow_map.py | python | add_neighbors_of_bad_images | (all_images, bad_images) | return images_to_add | Given a list of images in all_images, and a subset of them
in bad_images, create a list of images that has all the images
in bad_images, and for each such image also has the image
before it and the image after it, as they show in all_images. The
reason we want to add the neighbors for each bad image is that we
will put all these in a map, and it is not good for localization
that in a map an image shows up isolated. | Given a list of images in all_images, and a subset of them
in bad_images, create a list of images that has all the images
in bad_images, and for each such image also has the image
before it and the image after it, as they show in all_images. The
reason we want to add the neighbors for each bad image is that we
will put all these in a map, and it is not good for localization
that in a map an image shows up isolated. | [
"Given",
"a",
"list",
"of",
"images",
"in",
"all_images",
"and",
"a",
"subset",
"of",
"them",
"in",
"bad_images",
"create",
"a",
"list",
"of",
"images",
"that",
"has",
"all",
"the",
"images",
"in",
"bad_images",
"and",
"for",
"each",
"such",
"image",
"also",
"has",
"the",
"image",
"before",
"it",
"and",
"the",
"image",
"after",
"it",
"as",
"they",
"show",
"in",
"all_images",
".",
"The",
"reason",
"we",
"want",
"to",
"add",
"the",
"neighbors",
"for",
"each",
"bad",
"image",
"is",
"that",
"we",
"will",
"put",
"all",
"these",
"in",
"a",
"map",
"and",
"it",
"is",
"not",
"good",
"for",
"localization",
"that",
"in",
"a",
"map",
"an",
"image",
"shows",
"up",
"isolated",
"."
] | def add_neighbors_of_bad_images(all_images, bad_images):
"""Given a list of images in all_images, and a subset of them
in bad_images, create a list of images that has all the images
in bad_images, and for each such image also has the image
before it and the image after it, as they show in all_images. The
reason we want to add the neighbors for each bad image is that we
will put all these in a map, and it is not good for localization
that in a map an image shows up isolated.
"""
all_images_dict = {}
for image_count in range(len(all_images)):
all_images_dict[all_images[image_count]] = image_count
images_to_add_dict = {}
for bad_image in bad_images:
if bad_image not in all_images_dict:
raise Exception("Book-keeping error.")
image_count = all_images_dict[bad_image]
# Add the bad image
# print("add bad image " + bad_image)
images_to_add_dict[image_count] = bad_image
# Add its neighbors
if image_count - 1 >= 0:
# print("add neighbor " + all_images[image_count - 1])
images_to_add_dict[image_count - 1] = all_images[image_count - 1]
if image_count + 1 < len(all_images):
# print("add neighbor " + all_images[image_count + 1])
images_to_add_dict[image_count + 1] = all_images[image_count + 1]
images_to_add = []
for image_count in images_to_add_dict:
# print("---add ", images_to_add_dict[image_count])
images_to_add.append(images_to_add_dict[image_count])
return images_to_add | [
"def",
"add_neighbors_of_bad_images",
"(",
"all_images",
",",
"bad_images",
")",
":",
"all_images_dict",
"=",
"{",
"}",
"for",
"image_count",
"in",
"range",
"(",
"len",
"(",
"all_images",
")",
")",
":",
"all_images_dict",
"[",
"all_images",
"[",
"image_count",
"]",
"]",
"=",
"image_count",
"images_to_add_dict",
"=",
"{",
"}",
"for",
"bad_image",
"in",
"bad_images",
":",
"if",
"bad_image",
"not",
"in",
"all_images_dict",
":",
"raise",
"Exception",
"(",
"\"Book-keeping error.\"",
")",
"image_count",
"=",
"all_images_dict",
"[",
"bad_image",
"]",
"# Add the bad image",
"# print(\"add bad image \" + bad_image)",
"images_to_add_dict",
"[",
"image_count",
"]",
"=",
"bad_image",
"# Add its neighbors",
"if",
"image_count",
"-",
"1",
">=",
"0",
":",
"# print(\"add neighbor \" + all_images[image_count - 1])",
"images_to_add_dict",
"[",
"image_count",
"-",
"1",
"]",
"=",
"all_images",
"[",
"image_count",
"-",
"1",
"]",
"if",
"image_count",
"+",
"1",
"<",
"len",
"(",
"all_images",
")",
":",
"# print(\"add neighbor \" + all_images[image_count + 1])",
"images_to_add_dict",
"[",
"image_count",
"+",
"1",
"]",
"=",
"all_images",
"[",
"image_count",
"+",
"1",
"]",
"images_to_add",
"=",
"[",
"]",
"for",
"image_count",
"in",
"images_to_add_dict",
":",
"# print(\"---add \", images_to_add_dict[image_count])",
"images_to_add",
".",
"append",
"(",
"images_to_add_dict",
"[",
"image_count",
"]",
")",
"return",
"images_to_add"
] | https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/localization/sparse_mapping/tools/grow_map.py#L404-L442 | |
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py | python | NewCMessage | (full_message_name) | return _net_proto2___python.NewCMessage(full_message_name) | Creates a new C++ protocol message by its name. | Creates a new C++ protocol message by its name. | [
"Creates",
"a",
"new",
"C",
"++",
"protocol",
"message",
"by",
"its",
"name",
"."
] | def NewCMessage(full_message_name):
"""Creates a new C++ protocol message by its name."""
return _net_proto2___python.NewCMessage(full_message_name) | [
"def",
"NewCMessage",
"(",
"full_message_name",
")",
":",
"return",
"_net_proto2___python",
".",
"NewCMessage",
"(",
"full_message_name",
")"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py#L73-L75 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/utils/lui/lldbutil.py | python | state_type_to_str | (enum) | Returns the stateType string given an enum. | Returns the stateType string given an enum. | [
"Returns",
"the",
"stateType",
"string",
"given",
"an",
"enum",
"."
] | def state_type_to_str(enum):
"""Returns the stateType string given an enum."""
if enum == lldb.eStateInvalid:
return "invalid"
elif enum == lldb.eStateUnloaded:
return "unloaded"
elif enum == lldb.eStateConnected:
return "connected"
elif enum == lldb.eStateAttaching:
return "attaching"
elif enum == lldb.eStateLaunching:
return "launching"
elif enum == lldb.eStateStopped:
return "stopped"
elif enum == lldb.eStateRunning:
return "running"
elif enum == lldb.eStateStepping:
return "stepping"
elif enum == lldb.eStateCrashed:
return "crashed"
elif enum == lldb.eStateDetached:
return "detached"
elif enum == lldb.eStateExited:
return "exited"
elif enum == lldb.eStateSuspended:
return "suspended"
else:
raise Exception("Unknown StateType enum") | [
"def",
"state_type_to_str",
"(",
"enum",
")",
":",
"if",
"enum",
"==",
"lldb",
".",
"eStateInvalid",
":",
"return",
"\"invalid\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateUnloaded",
":",
"return",
"\"unloaded\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateConnected",
":",
"return",
"\"connected\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateAttaching",
":",
"return",
"\"attaching\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateLaunching",
":",
"return",
"\"launching\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateStopped",
":",
"return",
"\"stopped\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateRunning",
":",
"return",
"\"running\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateStepping",
":",
"return",
"\"stepping\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateCrashed",
":",
"return",
"\"crashed\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateDetached",
":",
"return",
"\"detached\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateExited",
":",
"return",
"\"exited\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateSuspended",
":",
"return",
"\"suspended\"",
"else",
":",
"raise",
"Exception",
"(",
"\"Unknown StateType enum\"",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/utils/lui/lldbutil.py#L153-L180 | ||
dartsim/dart | 495c82120c836005f2d136d4a50c8cc997fb879b | tools/cpplint.py | python | PrintUsage | (message) | Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message. | Prints a brief usage string and exits, optionally with an error message. | [
"Prints",
"a",
"brief",
"usage",
"string",
"and",
"exits",
"optionally",
"with",
"an",
"error",
"message",
"."
] | def PrintUsage(message):
"""Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE)
if message:
sys.exit('\nFATAL ERROR: ' + message)
else:
sys.exit(1) | [
"def",
"PrintUsage",
"(",
"message",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"_USAGE",
")",
"if",
"message",
":",
"sys",
".",
"exit",
"(",
"'\\nFATAL ERROR: '",
"+",
"message",
")",
"else",
":",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/tools/cpplint.py#L4662-L4672 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/ipaddress.py | python | IPv4Address.is_loopback | (self) | return self in self._constants._loopback_network | Test if the address is a loopback address.
Returns:
A boolean, True if the address is a loopback per RFC 3330. | Test if the address is a loopback address. | [
"Test",
"if",
"the",
"address",
"is",
"a",
"loopback",
"address",
"."
] | def is_loopback(self):
"""Test if the address is a loopback address.
Returns:
A boolean, True if the address is a loopback per RFC 3330.
"""
return self in self._constants._loopback_network | [
"def",
"is_loopback",
"(",
"self",
")",
":",
"return",
"self",
"in",
"self",
".",
"_constants",
".",
"_loopback_network"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ipaddress.py#L1385-L1392 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | TreeListCtrl.SetColumnImage | (*args, **kwargs) | return _gizmos.TreeListCtrl_SetColumnImage(*args, **kwargs) | SetColumnImage(self, int column, int image) | SetColumnImage(self, int column, int image) | [
"SetColumnImage",
"(",
"self",
"int",
"column",
"int",
"image",
")"
] | def SetColumnImage(*args, **kwargs):
"""SetColumnImage(self, int column, int image)"""
return _gizmos.TreeListCtrl_SetColumnImage(*args, **kwargs) | [
"def",
"SetColumnImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_SetColumnImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L626-L628 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/jinja2/meta.py | python | TrackingCodeGenerator.write | (self, x) | Don't write. | Don't write. | [
"Don",
"t",
"write",
"."
] | def write(self, x):
"""Don't write.""" | [
"def",
"write",
"(",
"self",
",",
"x",
")",
":"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/meta.py#L25-L26 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.LineCopy | (*args, **kwargs) | return _stc.StyledTextCtrl_LineCopy(*args, **kwargs) | LineCopy(self)
Copy the line containing the caret. | LineCopy(self) | [
"LineCopy",
"(",
"self",
")"
] | def LineCopy(*args, **kwargs):
"""
LineCopy(self)
Copy the line containing the caret.
"""
return _stc.StyledTextCtrl_LineCopy(*args, **kwargs) | [
"def",
"LineCopy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_LineCopy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4775-L4781 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TBigStrPool.__init__ | (self, *args) | __init__(TBigStrPool self, TSize MxBfLen=0, uint _GrowBy=16*1024*1024) -> TBigStrPool
Parameters:
MxBfLen: TSize
_GrowBy: uint
__init__(TBigStrPool self, TSize MxBfLen=0) -> TBigStrPool
Parameters:
MxBfLen: TSize
__init__(TBigStrPool self) -> TBigStrPool
__init__(TBigStrPool self, TSIn SIn, bool LoadCompact=True) -> TBigStrPool
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TBigStrPool self, TSIn SIn) -> TBigStrPool
Parameters:
SIn: TSIn &
__init__(TBigStrPool self, TBigStrPool Pool) -> TBigStrPool
Parameters:
Pool: TBigStrPool const & | __init__(TBigStrPool self, TSize MxBfLen=0, uint _GrowBy=16*1024*1024) -> TBigStrPool | [
"__init__",
"(",
"TBigStrPool",
"self",
"TSize",
"MxBfLen",
"=",
"0",
"uint",
"_GrowBy",
"=",
"16",
"*",
"1024",
"*",
"1024",
")",
"-",
">",
"TBigStrPool"
] | def __init__(self, *args):
"""
__init__(TBigStrPool self, TSize MxBfLen=0, uint _GrowBy=16*1024*1024) -> TBigStrPool
Parameters:
MxBfLen: TSize
_GrowBy: uint
__init__(TBigStrPool self, TSize MxBfLen=0) -> TBigStrPool
Parameters:
MxBfLen: TSize
__init__(TBigStrPool self) -> TBigStrPool
__init__(TBigStrPool self, TSIn SIn, bool LoadCompact=True) -> TBigStrPool
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TBigStrPool self, TSIn SIn) -> TBigStrPool
Parameters:
SIn: TSIn &
__init__(TBigStrPool self, TBigStrPool Pool) -> TBigStrPool
Parameters:
Pool: TBigStrPool const &
"""
_snap.TBigStrPool_swiginit(self,_snap.new_TBigStrPool(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_snap",
".",
"TBigStrPool_swiginit",
"(",
"self",
",",
"_snap",
".",
"new_TBigStrPool",
"(",
"*",
"args",
")",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L5690-L5721 | ||
include-what-you-use/include-what-you-use | 208fbfffa5d69364b9f78e427caa443441279283 | fix_includes.py | python | _PreviousNondeletedLine | (file_lines, line_number) | return None | Returns the line number of the previous not-deleted line, or None. | Returns the line number of the previous not-deleted line, or None. | [
"Returns",
"the",
"line",
"number",
"of",
"the",
"previous",
"not",
"-",
"deleted",
"line",
"or",
"None",
"."
] | def _PreviousNondeletedLine(file_lines, line_number):
"""Returns the line number of the previous not-deleted line, or None."""
for line_number in range(line_number - 1, -1, -1):
if not file_lines[line_number].deleted:
return line_number
return None | [
"def",
"_PreviousNondeletedLine",
"(",
"file_lines",
",",
"line_number",
")",
":",
"for",
"line_number",
"in",
"range",
"(",
"line_number",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"not",
"file_lines",
"[",
"line_number",
"]",
".",
"deleted",
":",
"return",
"line_number",
"return",
"None"
] | https://github.com/include-what-you-use/include-what-you-use/blob/208fbfffa5d69364b9f78e427caa443441279283/fix_includes.py#L814-L819 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | Locale_AddCatalogLookupPathPrefix | (*args, **kwargs) | return _gdi_.Locale_AddCatalogLookupPathPrefix(*args, **kwargs) | Locale_AddCatalogLookupPathPrefix(String prefix) | Locale_AddCatalogLookupPathPrefix(String prefix) | [
"Locale_AddCatalogLookupPathPrefix",
"(",
"String",
"prefix",
")"
] | def Locale_AddCatalogLookupPathPrefix(*args, **kwargs):
"""Locale_AddCatalogLookupPathPrefix(String prefix)"""
return _gdi_.Locale_AddCatalogLookupPathPrefix(*args, **kwargs) | [
"def",
"Locale_AddCatalogLookupPathPrefix",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Locale_AddCatalogLookupPathPrefix",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3112-L3114 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/masked/maskededit.py | python | MaskedEditMixin._OnCtrl_X | (self, event=None) | return False | Handles ctrl-x keypress in control and Cut operation on context menu.
Should return False to skip other processing. | Handles ctrl-x keypress in control and Cut operation on context menu.
Should return False to skip other processing. | [
"Handles",
"ctrl",
"-",
"x",
"keypress",
"in",
"control",
"and",
"Cut",
"operation",
"on",
"context",
"menu",
".",
"Should",
"return",
"False",
"to",
"skip",
"other",
"processing",
"."
] | def _OnCtrl_X(self, event=None):
""" Handles ctrl-x keypress in control and Cut operation on context menu.
Should return False to skip other processing. """
## dbg("MaskedEditMixin::_OnCtrl_X", indent=1)
self.Cut()
## dbg(indent=0)
return False | [
"def",
"_OnCtrl_X",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"## dbg(\"MaskedEditMixin::_OnCtrl_X\", indent=1)",
"self",
".",
"Cut",
"(",
")",
"## dbg(indent=0)",
"return",
"False"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/maskededit.py#L3341-L3347 | |
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | samples/python/tensorflow_object_detection_api/infer.py | python | TensorRTInfer.__init__ | (self, engine_path, preprocessor, detection_type, iou_threshold) | :param engine_path: The path to the serialized engine to load from disk. | :param engine_path: The path to the serialized engine to load from disk. | [
":",
"param",
"engine_path",
":",
"The",
"path",
"to",
"the",
"serialized",
"engine",
"to",
"load",
"from",
"disk",
"."
] | def __init__(self, engine_path, preprocessor, detection_type, iou_threshold):
"""
:param engine_path: The path to the serialized engine to load from disk.
"""
self.preprocessor = preprocessor
self.detection_type = detection_type
self.iou_threshold = iou_threshold
# Load TRT engine
self.logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(self.logger, namespace="")
with open(engine_path, "rb") as f, trt.Runtime(self.logger) as runtime:
self.engine = runtime.deserialize_cuda_engine(f.read())
self.context = self.engine.create_execution_context()
assert self.engine
assert self.context
# Setup I/O bindings
self.inputs = []
self.outputs = []
self.allocations = []
for i in range(self.engine.num_bindings):
is_input = False
if self.engine.binding_is_input(i):
is_input = True
name = self.engine.get_binding_name(i)
dtype = self.engine.get_binding_dtype(i)
shape = self.engine.get_binding_shape(i)
if is_input:
self.batch_size = shape[0]
size = np.dtype(trt.nptype(dtype)).itemsize
for s in shape:
size *= s
allocation = cuda.mem_alloc(size)
binding = {
'index': i,
'name': name,
'dtype': np.dtype(trt.nptype(dtype)),
'shape': list(shape),
'allocation': allocation,
}
self.allocations.append(allocation)
if self.engine.binding_is_input(i):
self.inputs.append(binding)
else:
self.outputs.append(binding)
assert self.batch_size > 0
assert len(self.inputs) > 0
assert len(self.outputs) > 0
assert len(self.allocations) > 0 | [
"def",
"__init__",
"(",
"self",
",",
"engine_path",
",",
"preprocessor",
",",
"detection_type",
",",
"iou_threshold",
")",
":",
"self",
".",
"preprocessor",
"=",
"preprocessor",
"self",
".",
"detection_type",
"=",
"detection_type",
"self",
".",
"iou_threshold",
"=",
"iou_threshold",
"# Load TRT engine",
"self",
".",
"logger",
"=",
"trt",
".",
"Logger",
"(",
"trt",
".",
"Logger",
".",
"ERROR",
")",
"trt",
".",
"init_libnvinfer_plugins",
"(",
"self",
".",
"logger",
",",
"namespace",
"=",
"\"\"",
")",
"with",
"open",
"(",
"engine_path",
",",
"\"rb\"",
")",
"as",
"f",
",",
"trt",
".",
"Runtime",
"(",
"self",
".",
"logger",
")",
"as",
"runtime",
":",
"self",
".",
"engine",
"=",
"runtime",
".",
"deserialize_cuda_engine",
"(",
"f",
".",
"read",
"(",
")",
")",
"self",
".",
"context",
"=",
"self",
".",
"engine",
".",
"create_execution_context",
"(",
")",
"assert",
"self",
".",
"engine",
"assert",
"self",
".",
"context",
"# Setup I/O bindings",
"self",
".",
"inputs",
"=",
"[",
"]",
"self",
".",
"outputs",
"=",
"[",
"]",
"self",
".",
"allocations",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"engine",
".",
"num_bindings",
")",
":",
"is_input",
"=",
"False",
"if",
"self",
".",
"engine",
".",
"binding_is_input",
"(",
"i",
")",
":",
"is_input",
"=",
"True",
"name",
"=",
"self",
".",
"engine",
".",
"get_binding_name",
"(",
"i",
")",
"dtype",
"=",
"self",
".",
"engine",
".",
"get_binding_dtype",
"(",
"i",
")",
"shape",
"=",
"self",
".",
"engine",
".",
"get_binding_shape",
"(",
"i",
")",
"if",
"is_input",
":",
"self",
".",
"batch_size",
"=",
"shape",
"[",
"0",
"]",
"size",
"=",
"np",
".",
"dtype",
"(",
"trt",
".",
"nptype",
"(",
"dtype",
")",
")",
".",
"itemsize",
"for",
"s",
"in",
"shape",
":",
"size",
"*=",
"s",
"allocation",
"=",
"cuda",
".",
"mem_alloc",
"(",
"size",
")",
"binding",
"=",
"{",
"'index'",
":",
"i",
",",
"'name'",
":",
"name",
",",
"'dtype'",
":",
"np",
".",
"dtype",
"(",
"trt",
".",
"nptype",
"(",
"dtype",
")",
")",
",",
"'shape'",
":",
"list",
"(",
"shape",
")",
",",
"'allocation'",
":",
"allocation",
",",
"}",
"self",
".",
"allocations",
".",
"append",
"(",
"allocation",
")",
"if",
"self",
".",
"engine",
".",
"binding_is_input",
"(",
"i",
")",
":",
"self",
".",
"inputs",
".",
"append",
"(",
"binding",
")",
"else",
":",
"self",
".",
"outputs",
".",
"append",
"(",
"binding",
")",
"assert",
"self",
".",
"batch_size",
">",
"0",
"assert",
"len",
"(",
"self",
".",
"inputs",
")",
">",
"0",
"assert",
"len",
"(",
"self",
".",
"outputs",
")",
">",
"0",
"assert",
"len",
"(",
"self",
".",
"allocations",
")",
">",
"0"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/tensorflow_object_detection_api/infer.py#L37-L86 | ||
OpenXRay/xray-15 | 1390dfb08ed20997d7e8c95147ea8e8cb71f5e86 | cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/scripted/basicShape.py | python | basicShape.boundingBox | (self) | return result | Returns the bounding box for the shape.
In this case just use the radius and height attributes
to determine the bounding box. | Returns the bounding box for the shape.
In this case just use the radius and height attributes
to determine the bounding box. | [
"Returns",
"the",
"bounding",
"box",
"for",
"the",
"shape",
".",
"In",
"this",
"case",
"just",
"use",
"the",
"radius",
"and",
"height",
"attributes",
"to",
"determine",
"the",
"bounding",
"box",
"."
] | def boundingBox(self):
"""
Returns the bounding box for the shape.
In this case just use the radius and height attributes
to determine the bounding box.
"""
result = OpenMaya.MBoundingBox()
geom = self.geometry()
r = geom.radius
result.expand(OpenMaya.MPoint(r,r,r))
result.expand(OpenMaya.MPoint(-r,-r,-r))
r = geom.height/2.0
result.expand(OpenMaya.MPoint(r,r,r))
result.expand(OpenMaya.MPoint(-r,-r,-r))
r = geom.width/2.0
result.expand(OpenMaya.MPoint(r,r,r))
result.expand(OpenMaya.MPoint(-r,-r,-r))
return result | [
"def",
"boundingBox",
"(",
"self",
")",
":",
"result",
"=",
"OpenMaya",
".",
"MBoundingBox",
"(",
")",
"geom",
"=",
"self",
".",
"geometry",
"(",
")",
"r",
"=",
"geom",
".",
"radius",
"result",
".",
"expand",
"(",
"OpenMaya",
".",
"MPoint",
"(",
"r",
",",
"r",
",",
"r",
")",
")",
"result",
".",
"expand",
"(",
"OpenMaya",
".",
"MPoint",
"(",
"-",
"r",
",",
"-",
"r",
",",
"-",
"r",
")",
")",
"r",
"=",
"geom",
".",
"height",
"/",
"2.0",
"result",
".",
"expand",
"(",
"OpenMaya",
".",
"MPoint",
"(",
"r",
",",
"r",
",",
"r",
")",
")",
"result",
".",
"expand",
"(",
"OpenMaya",
".",
"MPoint",
"(",
"-",
"r",
",",
"-",
"r",
",",
"-",
"r",
")",
")",
"r",
"=",
"geom",
".",
"width",
"/",
"2.0",
"result",
".",
"expand",
"(",
"OpenMaya",
".",
"MPoint",
"(",
"r",
",",
"r",
",",
"r",
")",
")",
"result",
".",
"expand",
"(",
"OpenMaya",
".",
"MPoint",
"(",
"-",
"r",
",",
"-",
"r",
",",
"-",
"r",
")",
")",
"return",
"result"
] | https://github.com/OpenXRay/xray-15/blob/1390dfb08ed20997d7e8c95147ea8e8cb71f5e86/cs/sdk/3d_sdk/maya/ver-2008/devkit/plug-ins/scripted/basicShape.py#L212-L234 | |
nileshkulkarni/csm | 0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc | csm/utils/image.py | python | compute_dt | (mask) | return dist | Computes distance transform of mask. | Computes distance transform of mask. | [
"Computes",
"distance",
"transform",
"of",
"mask",
"."
] | def compute_dt(mask):
"""
Computes distance transform of mask.
"""
from scipy.ndimage import distance_transform_edt
dist = distance_transform_edt(1-mask) / max(mask.shape)
return dist | [
"def",
"compute_dt",
"(",
"mask",
")",
":",
"from",
"scipy",
".",
"ndimage",
"import",
"distance_transform_edt",
"dist",
"=",
"distance_transform_edt",
"(",
"1",
"-",
"mask",
")",
"/",
"max",
"(",
"mask",
".",
"shape",
")",
"return",
"dist"
] | https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/utils/image.py#L99-L105 | |
gnina/gnina | b9ae032f52fc7a8153987bde09c0efa3620d8bb6 | caffe/python/caffe/coord_map.py | python | inverse | (coord_map) | return ax, 1 / a, -b / a | Invert a coord map by de-scaling and un-shifting;
this gives the backward mapping for the gradient. | Invert a coord map by de-scaling and un-shifting;
this gives the backward mapping for the gradient. | [
"Invert",
"a",
"coord",
"map",
"by",
"de",
"-",
"scaling",
"and",
"un",
"-",
"shifting",
";",
"this",
"gives",
"the",
"backward",
"mapping",
"for",
"the",
"gradient",
"."
] | def inverse(coord_map):
"""
Invert a coord map by de-scaling and un-shifting;
this gives the backward mapping for the gradient.
"""
ax, a, b = coord_map
return ax, 1 / a, -b / a | [
"def",
"inverse",
"(",
"coord_map",
")",
":",
"ax",
",",
"a",
",",
"b",
"=",
"coord_map",
"return",
"ax",
",",
"1",
"/",
"a",
",",
"-",
"b",
"/",
"a"
] | https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/python/caffe/coord_map.py#L106-L112 | |
LLNL/lbann | 26083e6c86050302ce33148aea70f62e61cacb92 | python/lbann/modules/graph/sparse/GCNConv.py | python | GCNConv.forward | (self, node_feature_mat, source_indices, target_indices) | return reduced_features | Apply GCN
Args:
node_feature_mat (Layer): Node feature matrix with the shape of (num_nodes,input_channels)
source_indices (Layer): Source node indices of the edges with shape (num_nodes)
target_indices (Layer): Target node indices of the edges with shape (num_nodes)
Returns:
(Layer) : The output after kernel ops. The output can passed into another Graph Conv layer
directly | Apply GCN | [
"Apply",
"GCN"
] | def forward(self, node_feature_mat, source_indices, target_indices):
"""Apply GCN
Args:
node_feature_mat (Layer): Node feature matrix with the shape of (num_nodes,input_channels)
source_indices (Layer): Source node indices of the edges with shape (num_nodes)
target_indices (Layer): Target node indices of the edges with shape (num_nodes)
Returns:
(Layer) : The output after kernel ops. The output can passed into another Graph Conv layer
directly
"""
self.instance += 1
name = f"{self.name}_{self.instance}"
new_features = self.nn(node_feature_mat) # W \times node_feature_mat
# If distconv enabled, the output dimensions of the feature matrix are 3D
# We convert it to 2D for the graph expan and reduce operations
# Note: This check will be obsolete once distconv scatter-gather is supported
if self.is_distconv:
new_features = lbann.Reshape(new_features,
dims=str_list([self.num_nodes, self.output_channel_size]),
name=f"{name}+_distconv_reshape")
neighborhoods = GraphExpand(new_features, target_indices)
reduced_features = GraphReduce(neighborhoods, source_indices, [self.num_nodes, self.output_channel_size])
return reduced_features | [
"def",
"forward",
"(",
"self",
",",
"node_feature_mat",
",",
"source_indices",
",",
"target_indices",
")",
":",
"self",
".",
"instance",
"+=",
"1",
"name",
"=",
"f\"{self.name}_{self.instance}\"",
"new_features",
"=",
"self",
".",
"nn",
"(",
"node_feature_mat",
")",
"# W \\times node_feature_mat",
"# If distconv enabled, the output dimensions of the feature matrix are 3D",
"# We convert it to 2D for the graph expan and reduce operations",
"# Note: This check will be obsolete once distconv scatter-gather is supported ",
"if",
"self",
".",
"is_distconv",
":",
"new_features",
"=",
"lbann",
".",
"Reshape",
"(",
"new_features",
",",
"dims",
"=",
"str_list",
"(",
"[",
"self",
".",
"num_nodes",
",",
"self",
".",
"output_channel_size",
"]",
")",
",",
"name",
"=",
"f\"{name}+_distconv_reshape\"",
")",
"neighborhoods",
"=",
"GraphExpand",
"(",
"new_features",
",",
"target_indices",
")",
"reduced_features",
"=",
"GraphReduce",
"(",
"neighborhoods",
",",
"source_indices",
",",
"[",
"self",
".",
"num_nodes",
",",
"self",
".",
"output_channel_size",
"]",
")",
"return",
"reduced_features"
] | https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/modules/graph/sparse/GCNConv.py#L97-L124 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/imaplib.py | python | IMAP4.lsub | (self, directory='""', pattern='*') | return self._untagged_response(typ, dat, name) | List 'subscribed' mailbox names in directory matching pattern.
(typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
'data' are tuples of message part envelope and data. | List 'subscribed' mailbox names in directory matching pattern. | [
"List",
"subscribed",
"mailbox",
"names",
"in",
"directory",
"matching",
"pattern",
"."
] | def lsub(self, directory='""', pattern='*'):
"""List 'subscribed' mailbox names in directory matching pattern.
(typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
'data' are tuples of message part envelope and data.
"""
name = 'LSUB'
typ, dat = self._simple_command(name, directory, pattern)
return self._untagged_response(typ, dat, name) | [
"def",
"lsub",
"(",
"self",
",",
"directory",
"=",
"'\"\"'",
",",
"pattern",
"=",
"'*'",
")",
":",
"name",
"=",
"'LSUB'",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"name",
",",
"directory",
",",
"pattern",
")",
"return",
"self",
".",
"_untagged_response",
"(",
"typ",
",",
"dat",
",",
"name",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/imaplib.py#L647-L656 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/distutils/misc_util.py | python | Configuration.have_f77c | (self) | return flag | Check for availability of Fortran 77 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 77 compiler is available (because a simple Fortran 77
code was able to be compiled successfully). | Check for availability of Fortran 77 compiler. | [
"Check",
"for",
"availability",
"of",
"Fortran",
"77",
"compiler",
"."
] | def have_f77c(self):
"""Check for availability of Fortran 77 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 77 compiler is available (because a simple Fortran 77
code was able to be compiled successfully).
"""
simple_fortran_subroutine = '''
subroutine simple
end
'''
config_cmd = self.get_config_cmd()
flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77')
return flag | [
"def",
"have_f77c",
"(",
"self",
")",
":",
"simple_fortran_subroutine",
"=",
"'''\n subroutine simple\n end\n '''",
"config_cmd",
"=",
"self",
".",
"get_config_cmd",
"(",
")",
"flag",
"=",
"config_cmd",
".",
"try_compile",
"(",
"simple_fortran_subroutine",
",",
"lang",
"=",
"'f77'",
")",
"return",
"flag"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/misc_util.py#L1781-L1798 | |
PyMesh/PyMesh | 384ba882b7558ba6e8653ed263c419226c22bddf | python/pymesh/aabb_tree.py | python | do_intersect | (mesh, nodes, elements) | return r | Check if each element intersects the mesh.
Args:
mesh (:class:`Mesh`): Input mesh.
nodes(:class:`numpy.ndarray`): The nodes of the elements.
elements (:class:`numpy.ndarray`): Connectivity of the nodes.
Returns:
A list indicating if each element intersects the mesh. | Check if each element intersects the mesh. | [
"Check",
"if",
"each",
"element",
"intersects",
"the",
"mesh",
"."
] | def do_intersect(mesh, nodes, elements):
""" Check if each element intersects the mesh.
Args:
mesh (:class:`Mesh`): Input mesh.
nodes(:class:`numpy.ndarray`): The nodes of the elements.
elements (:class:`numpy.ndarray`): Connectivity of the nodes.
Returns:
A list indicating if each element intersects the mesh.
"""
tree = AABBTree()
tree.load_mesh(mesh)
assert(elements.ndim == 2)
elem_type = elements.shape[1]
if (elem_type == 2):
r =tree.do_intersect_segments(nodes, elements) != 0
else:
raise NotImplementedError(
"AABB tree does not support element consisting of {} nodes"\
.format(elem_type))
return r | [
"def",
"do_intersect",
"(",
"mesh",
",",
"nodes",
",",
"elements",
")",
":",
"tree",
"=",
"AABBTree",
"(",
")",
"tree",
".",
"load_mesh",
"(",
"mesh",
")",
"assert",
"(",
"elements",
".",
"ndim",
"==",
"2",
")",
"elem_type",
"=",
"elements",
".",
"shape",
"[",
"1",
"]",
"if",
"(",
"elem_type",
"==",
"2",
")",
":",
"r",
"=",
"tree",
".",
"do_intersect_segments",
"(",
"nodes",
",",
"elements",
")",
"!=",
"0",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"AABB tree does not support element consisting of {} nodes\"",
".",
"format",
"(",
"elem_type",
")",
")",
"return",
"r"
] | https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/aabb_tree.py#L162-L184 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Main/glue/vboxapi.py | python | VirtualBoxManager.closeMachineSession | (self, oSession) | return True | Closes a session opened by openMachineSession.
Ignores None parameters. | Closes a session opened by openMachineSession.
Ignores None parameters. | [
"Closes",
"a",
"session",
"opened",
"by",
"openMachineSession",
".",
"Ignores",
"None",
"parameters",
"."
] | def closeMachineSession(self, oSession):
"""
Closes a session opened by openMachineSession.
Ignores None parameters.
"""
if oSession is not None:
oSession.unlockMachine()
return True | [
"def",
"closeMachineSession",
"(",
"self",
",",
"oSession",
")",
":",
"if",
"oSession",
"is",
"not",
"None",
":",
"oSession",
".",
"unlockMachine",
"(",
")",
"return",
"True"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Main/glue/vboxapi.py#L1122-L1129 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/configprovider.py | python | ConfigValueStore.set_config_provider | (self, logical_name, provider) | Set the provider for a config value.
This provides control over how a particular configuration value is
loaded. This replaces the provider for ``logical_name`` with the new
``provider``.
:type logical_name: str
:param logical_name: The name of the config value to change the config
provider for.
:type provider: :class:`botocore.configprovider.BaseProvider`
:param provider: The new provider that should be responsible for
providing a value for the config named ``logical_name``. | Set the provider for a config value. | [
"Set",
"the",
"provider",
"for",
"a",
"config",
"value",
"."
] | def set_config_provider(self, logical_name, provider):
"""Set the provider for a config value.
This provides control over how a particular configuration value is
loaded. This replaces the provider for ``logical_name`` with the new
``provider``.
:type logical_name: str
:param logical_name: The name of the config value to change the config
provider for.
:type provider: :class:`botocore.configprovider.BaseProvider`
:param provider: The new provider that should be responsible for
providing a value for the config named ``logical_name``.
"""
self._mapping[logical_name] = provider | [
"def",
"set_config_provider",
"(",
"self",
",",
"logical_name",
",",
"provider",
")",
":",
"self",
".",
"_mapping",
"[",
"logical_name",
"]",
"=",
"provider"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/configprovider.py#L330-L345 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/message.py | python | Message.get_content_maintype | (self) | return ctype.split('/')[0] | Return the message's main content type.
This is the `maintype' part of the string returned by
get_content_type(). | Return the message's main content type. | [
"Return",
"the",
"message",
"s",
"main",
"content",
"type",
"."
] | def get_content_maintype(self):
"""Return the message's main content type.
This is the `maintype' part of the string returned by
get_content_type().
"""
ctype = self.get_content_type()
return ctype.split('/')[0] | [
"def",
"get_content_maintype",
"(",
"self",
")",
":",
"ctype",
"=",
"self",
".",
"get_content_type",
"(",
")",
"return",
"ctype",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/message.py#L588-L595 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.