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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dicecco1/fpga_caffe | 7a191704efd7873071cfef35772d7e7bf3e3cfd6 | scripts/cpp_lint.py | python | CheckCaffeRandom | (filename, clean_lines, linenum, error) | Checks for calls to C random functions (rand, rand_r, random, ...).
Caffe code should (almost) always use the caffe_rng_* functions rather
than these, as the internal state of these C functions is independent of the
native Caffe RNG system which should produce deterministic results for a
fixed Caffe seed set using Caffe::set_random_seed(...).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for calls to C random functions (rand, rand_r, random, ...). | [
"Checks",
"for",
"calls",
"to",
"C",
"random",
"functions",
"(",
"rand",
"rand_r",
"random",
"...",
")",
"."
] | def CheckCaffeRandom(filename, clean_lines, linenum, error):
"""Checks for calls to C random functions (rand, rand_r, random, ...).
Caffe code should (almost) always use the caffe_rng_* functions rather
than these, as the internal state of these C functions is independent of the
native Caffe RNG system which should produce deterministic results for a
fixed Caffe seed set using Caffe::set_random_seed(...).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for function in c_random_function_list:
ix = line.find(function)
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
error(filename, linenum, 'caffe/random_fn', 2,
'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '
+ function +
') to ensure results are deterministic for a fixed Caffe seed.') | [
"def",
"CheckCaffeRandom",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"for",
"function",
"in",
"c_random_function_list",
":",
"ix",
"=",
"line",
".",
"find",
"(",
"function",
")",
"# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison",
"if",
"ix",
">=",
"0",
"and",
"(",
"ix",
"==",
"0",
"or",
"(",
"not",
"line",
"[",
"ix",
"-",
"1",
"]",
".",
"isalnum",
"(",
")",
"and",
"line",
"[",
"ix",
"-",
"1",
"]",
"not",
"in",
"(",
"'_'",
",",
"'.'",
",",
"'>'",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'caffe/random_fn'",
",",
"2",
",",
"'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '",
"+",
"function",
"+",
"') to ensure results are deterministic for a fixed Caffe seed.'",
")"
] | https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/scripts/cpp_lint.py#L1644-L1667 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/text_format.py | python | _Parser._MergeScalarField | (self, tokenizer, message, field) | Merges a single scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: A protocol message to record the data.
field: The descriptor of the field to be merged.
Raises:
ParseError: In case of text parsing problems.
RuntimeError: On runtime errors. | Merges a single scalar field into a message. | [
"Merges",
"a",
"single",
"scalar",
"field",
"into",
"a",
"message",
"."
] | def _MergeScalarField(self, tokenizer, message, field):
"""Merges a single scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: A protocol message to record the data.
field: The descriptor of the field to be merged.
Raises:
ParseError: In case of text parsing problems.
RuntimeError: On runtime errors.
"""
_ = self.allow_unknown_extension
value = None
if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
descriptor.FieldDescriptor.TYPE_SINT32,
descriptor.FieldDescriptor.TYPE_SFIXED32):
value = _ConsumeInt32(tokenizer)
elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
descriptor.FieldDescriptor.TYPE_SINT64,
descriptor.FieldDescriptor.TYPE_SFIXED64):
value = _ConsumeInt64(tokenizer)
elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
descriptor.FieldDescriptor.TYPE_FIXED32):
value = _ConsumeUint32(tokenizer)
elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
descriptor.FieldDescriptor.TYPE_FIXED64):
value = _ConsumeUint64(tokenizer)
elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
descriptor.FieldDescriptor.TYPE_DOUBLE):
value = tokenizer.ConsumeFloat()
elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
value = tokenizer.ConsumeBool()
elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
value = tokenizer.ConsumeString()
elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
value = tokenizer.ConsumeByteString()
elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
value = tokenizer.ConsumeEnum(field)
else:
raise RuntimeError('Unknown field type %d' % field.type)
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
if field.is_extension:
message.Extensions[field].append(value)
else:
getattr(message, field.name).append(value)
else:
if field.is_extension:
if (not self._allow_multiple_scalars and
not self._IsProto3Syntax(message) and
message.HasExtension(field)):
raise tokenizer.ParseErrorPreviousToken(
'Message type "%s" should not have multiple "%s" extensions.' %
(message.DESCRIPTOR.full_name, field.full_name))
else:
message.Extensions[field] = value
else:
duplicate_error = False
if not self._allow_multiple_scalars:
if self._IsProto3Syntax(message):
# Proto3 doesn't represent presence so we try best effort to check
# multiple scalars by compare to default values.
duplicate_error = bool(getattr(message, field.name))
else:
duplicate_error = message.HasField(field.name)
if duplicate_error:
raise tokenizer.ParseErrorPreviousToken(
'Message type "%s" should not have multiple "%s" fields.' %
(message.DESCRIPTOR.full_name, field.name))
else:
setattr(message, field.name, value) | [
"def",
"_MergeScalarField",
"(",
"self",
",",
"tokenizer",
",",
"message",
",",
"field",
")",
":",
"_",
"=",
"self",
".",
"allow_unknown_extension",
"value",
"=",
"None",
"if",
"field",
".",
"type",
"in",
"(",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_INT32",
",",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_SINT32",
",",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_SFIXED32",
")",
":",
"value",
"=",
"_ConsumeInt32",
"(",
"tokenizer",
")",
"elif",
"field",
".",
"type",
"in",
"(",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_INT64",
",",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_SINT64",
",",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_SFIXED64",
")",
":",
"value",
"=",
"_ConsumeInt64",
"(",
"tokenizer",
")",
"elif",
"field",
".",
"type",
"in",
"(",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_UINT32",
",",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_FIXED32",
")",
":",
"value",
"=",
"_ConsumeUint32",
"(",
"tokenizer",
")",
"elif",
"field",
".",
"type",
"in",
"(",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_UINT64",
",",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_FIXED64",
")",
":",
"value",
"=",
"_ConsumeUint64",
"(",
"tokenizer",
")",
"elif",
"field",
".",
"type",
"in",
"(",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_FLOAT",
",",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_DOUBLE",
")",
":",
"value",
"=",
"tokenizer",
".",
"ConsumeFloat",
"(",
")",
"elif",
"field",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_BOOL",
":",
"value",
"=",
"tokenizer",
".",
"ConsumeBool",
"(",
")",
"elif",
"field",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_STRING",
":",
"value",
"=",
"tokenizer",
".",
"ConsumeString",
"(",
")",
"elif",
"field",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_BYTES",
":",
"value",
"=",
"tokenizer",
".",
"ConsumeByteString",
"(",
")",
"elif",
"field",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_ENUM",
":",
"value",
"=",
"tokenizer",
".",
"ConsumeEnum",
"(",
"field",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Unknown field type %d'",
"%",
"field",
".",
"type",
")",
"if",
"field",
".",
"label",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"if",
"field",
".",
"is_extension",
":",
"message",
".",
"Extensions",
"[",
"field",
"]",
".",
"append",
"(",
"value",
")",
"else",
":",
"getattr",
"(",
"message",
",",
"field",
".",
"name",
")",
".",
"append",
"(",
"value",
")",
"else",
":",
"if",
"field",
".",
"is_extension",
":",
"if",
"(",
"not",
"self",
".",
"_allow_multiple_scalars",
"and",
"not",
"self",
".",
"_IsProto3Syntax",
"(",
"message",
")",
"and",
"message",
".",
"HasExtension",
"(",
"field",
")",
")",
":",
"raise",
"tokenizer",
".",
"ParseErrorPreviousToken",
"(",
"'Message type \"%s\" should not have multiple \"%s\" extensions.'",
"%",
"(",
"message",
".",
"DESCRIPTOR",
".",
"full_name",
",",
"field",
".",
"full_name",
")",
")",
"else",
":",
"message",
".",
"Extensions",
"[",
"field",
"]",
"=",
"value",
"else",
":",
"duplicate_error",
"=",
"False",
"if",
"not",
"self",
".",
"_allow_multiple_scalars",
":",
"if",
"self",
".",
"_IsProto3Syntax",
"(",
"message",
")",
":",
"# Proto3 doesn't represent presence so we try best effort to check",
"# multiple scalars by compare to default values.",
"duplicate_error",
"=",
"bool",
"(",
"getattr",
"(",
"message",
",",
"field",
".",
"name",
")",
")",
"else",
":",
"duplicate_error",
"=",
"message",
".",
"HasField",
"(",
"field",
".",
"name",
")",
"if",
"duplicate_error",
":",
"raise",
"tokenizer",
".",
"ParseErrorPreviousToken",
"(",
"'Message type \"%s\" should not have multiple \"%s\" fields.'",
"%",
"(",
"message",
".",
"DESCRIPTOR",
".",
"full_name",
",",
"field",
".",
"name",
")",
")",
"else",
":",
"setattr",
"(",
"message",
",",
"field",
".",
"name",
",",
"value",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/text_format.py#L1071-L1144 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/ndimage/measurements.py | python | histogram | (input, min, max, bins, labels=None, index=None) | return labeled_comprehension(input, labels, index, _hist, object, None,
pass_positions=False) | Calculate the histogram of the values of an array, optionally at labels.
Histogram calculates the frequency of values in an array within bins
determined by `min`, `max`, and `bins`. The `labels` and `index`
keywords can limit the scope of the histogram to specified sub-regions
within the array.
Parameters
----------
input : array_like
Data for which to calculate histogram.
min, max : int
Minimum and maximum values of range of histogram bins.
bins : int
Number of bins.
labels : array_like, optional
Labels for objects in `input`.
If not None, must be same shape as `input`.
index : int or sequence of ints, optional
Label or labels for which to calculate histogram. If None, all values
where label is greater than zero are used
Returns
-------
hist : ndarray
Histogram counts.
Examples
--------
>>> a = np.array([[ 0. , 0.2146, 0.5962, 0. ],
... [ 0. , 0.7778, 0. , 0. ],
... [ 0. , 0. , 0. , 0. ],
... [ 0. , 0. , 0.7181, 0.2787],
... [ 0. , 0. , 0.6573, 0.3094]])
>>> from scipy import ndimage
>>> ndimage.measurements.histogram(a, 0, 1, 10)
array([13, 0, 2, 1, 0, 1, 1, 2, 0, 0])
With labels and no indices, non-zero elements are counted:
>>> lbl, nlbl = ndimage.label(a)
>>> ndimage.measurements.histogram(a, 0, 1, 10, lbl)
array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0])
Indices can be used to count only certain objects:
>>> ndimage.measurements.histogram(a, 0, 1, 10, lbl, 2)
array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0]) | Calculate the histogram of the values of an array, optionally at labels. | [
"Calculate",
"the",
"histogram",
"of",
"the",
"values",
"of",
"an",
"array",
"optionally",
"at",
"labels",
"."
] | def histogram(input, min, max, bins, labels=None, index=None):
"""
Calculate the histogram of the values of an array, optionally at labels.
Histogram calculates the frequency of values in an array within bins
determined by `min`, `max`, and `bins`. The `labels` and `index`
keywords can limit the scope of the histogram to specified sub-regions
within the array.
Parameters
----------
input : array_like
Data for which to calculate histogram.
min, max : int
Minimum and maximum values of range of histogram bins.
bins : int
Number of bins.
labels : array_like, optional
Labels for objects in `input`.
If not None, must be same shape as `input`.
index : int or sequence of ints, optional
Label or labels for which to calculate histogram. If None, all values
where label is greater than zero are used
Returns
-------
hist : ndarray
Histogram counts.
Examples
--------
>>> a = np.array([[ 0. , 0.2146, 0.5962, 0. ],
... [ 0. , 0.7778, 0. , 0. ],
... [ 0. , 0. , 0. , 0. ],
... [ 0. , 0. , 0.7181, 0.2787],
... [ 0. , 0. , 0.6573, 0.3094]])
>>> from scipy import ndimage
>>> ndimage.measurements.histogram(a, 0, 1, 10)
array([13, 0, 2, 1, 0, 1, 1, 2, 0, 0])
With labels and no indices, non-zero elements are counted:
>>> lbl, nlbl = ndimage.label(a)
>>> ndimage.measurements.histogram(a, 0, 1, 10, lbl)
array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0])
Indices can be used to count only certain objects:
>>> ndimage.measurements.histogram(a, 0, 1, 10, lbl, 2)
array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])
"""
_bins = numpy.linspace(min, max, bins + 1)
def _hist(vals):
return numpy.histogram(vals, _bins)[0]
return labeled_comprehension(input, labels, index, _hist, object, None,
pass_positions=False) | [
"def",
"histogram",
"(",
"input",
",",
"min",
",",
"max",
",",
"bins",
",",
"labels",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"_bins",
"=",
"numpy",
".",
"linspace",
"(",
"min",
",",
"max",
",",
"bins",
"+",
"1",
")",
"def",
"_hist",
"(",
"vals",
")",
":",
"return",
"numpy",
".",
"histogram",
"(",
"vals",
",",
"_bins",
")",
"[",
"0",
"]",
"return",
"labeled_comprehension",
"(",
"input",
",",
"labels",
",",
"index",
",",
"_hist",
",",
"object",
",",
"None",
",",
"pass_positions",
"=",
"False",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/ndimage/measurements.py#L1336-L1394 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | models/AI-Model-Zoo/caffe-xilinx/tools/extra/parse_log.py | python | fix_initial_nan_learning_rate | (dict_list) | Correct initial value of learning rate
Learning rate is normally not printed until after the initial test and
training step, which means the initial testing and training rows have
LearningRate = NaN. Fix this by copying over the LearningRate from the
second row, if it exists. | Correct initial value of learning rate | [
"Correct",
"initial",
"value",
"of",
"learning",
"rate"
] | def fix_initial_nan_learning_rate(dict_list):
"""Correct initial value of learning rate
Learning rate is normally not printed until after the initial test and
training step, which means the initial testing and training rows have
LearningRate = NaN. Fix this by copying over the LearningRate from the
second row, if it exists.
"""
if len(dict_list) > 1:
dict_list[0]['LearningRate'] = dict_list[1]['LearningRate'] | [
"def",
"fix_initial_nan_learning_rate",
"(",
"dict_list",
")",
":",
"if",
"len",
"(",
"dict_list",
")",
">",
"1",
":",
"dict_list",
"[",
"0",
"]",
"[",
"'LearningRate'",
"]",
"=",
"dict_list",
"[",
"1",
"]",
"[",
"'LearningRate'",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/tools/extra/parse_log.py#L119-L129 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py | python | Series.dot | (self, other) | Compute the dot product between the Series and the columns of other.
This method computes the dot product between the Series and another
one, or the Series and each columns of a DataFrame, or the Series and
each columns of an array.
It can also be called using `self @ other` in Python >= 3.5.
Parameters
----------
other : Series, DataFrame or array-like
The other object to compute the dot product with its columns.
Returns
-------
scalar, Series or numpy.ndarray
Return the dot product of the Series and other if other is a
Series, the Series of the dot product of Series and each rows of
other if other is a DataFrame or a numpy.ndarray between the Series
and each columns of the numpy array.
See Also
--------
DataFrame.dot: Compute the matrix product with the DataFrame.
Series.mul: Multiplication of series and other, element-wise.
Notes
-----
The Series and other has to share the same index if other is a Series
or a DataFrame.
Examples
--------
>>> s = pd.Series([0, 1, 2, 3])
>>> other = pd.Series([-1, 2, -3, 4])
>>> s.dot(other)
8
>>> s @ other
8
>>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]])
>>> s.dot(df)
0 24
1 14
dtype: int64
>>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]])
>>> s.dot(arr)
array([24, 14]) | Compute the dot product between the Series and the columns of other. | [
"Compute",
"the",
"dot",
"product",
"between",
"the",
"Series",
"and",
"the",
"columns",
"of",
"other",
"."
] | def dot(self, other):
"""
Compute the dot product between the Series and the columns of other.
This method computes the dot product between the Series and another
one, or the Series and each columns of a DataFrame, or the Series and
each columns of an array.
It can also be called using `self @ other` in Python >= 3.5.
Parameters
----------
other : Series, DataFrame or array-like
The other object to compute the dot product with its columns.
Returns
-------
scalar, Series or numpy.ndarray
Return the dot product of the Series and other if other is a
Series, the Series of the dot product of Series and each rows of
other if other is a DataFrame or a numpy.ndarray between the Series
and each columns of the numpy array.
See Also
--------
DataFrame.dot: Compute the matrix product with the DataFrame.
Series.mul: Multiplication of series and other, element-wise.
Notes
-----
The Series and other has to share the same index if other is a Series
or a DataFrame.
Examples
--------
>>> s = pd.Series([0, 1, 2, 3])
>>> other = pd.Series([-1, 2, -3, 4])
>>> s.dot(other)
8
>>> s @ other
8
>>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]])
>>> s.dot(df)
0 24
1 14
dtype: int64
>>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]])
>>> s.dot(arr)
array([24, 14])
"""
if isinstance(other, (Series, ABCDataFrame)):
common = self.index.union(other.index)
if len(common) > len(self.index) or len(common) > len(other.index):
raise ValueError("matrices are not aligned")
left = self.reindex(index=common, copy=False)
right = other.reindex(index=common, copy=False)
lvals = left.values
rvals = right.values
else:
lvals = self.values
rvals = np.asarray(other)
if lvals.shape[0] != rvals.shape[0]:
raise Exception(
f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}"
)
if isinstance(other, ABCDataFrame):
return self._constructor(
np.dot(lvals, rvals), index=other.columns
).__finalize__(self)
elif isinstance(other, Series):
return np.dot(lvals, rvals)
elif isinstance(rvals, np.ndarray):
return np.dot(lvals, rvals)
else: # pragma: no cover
raise TypeError(f"unsupported type: {type(other)}") | [
"def",
"dot",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"(",
"Series",
",",
"ABCDataFrame",
")",
")",
":",
"common",
"=",
"self",
".",
"index",
".",
"union",
"(",
"other",
".",
"index",
")",
"if",
"len",
"(",
"common",
")",
">",
"len",
"(",
"self",
".",
"index",
")",
"or",
"len",
"(",
"common",
")",
">",
"len",
"(",
"other",
".",
"index",
")",
":",
"raise",
"ValueError",
"(",
"\"matrices are not aligned\"",
")",
"left",
"=",
"self",
".",
"reindex",
"(",
"index",
"=",
"common",
",",
"copy",
"=",
"False",
")",
"right",
"=",
"other",
".",
"reindex",
"(",
"index",
"=",
"common",
",",
"copy",
"=",
"False",
")",
"lvals",
"=",
"left",
".",
"values",
"rvals",
"=",
"right",
".",
"values",
"else",
":",
"lvals",
"=",
"self",
".",
"values",
"rvals",
"=",
"np",
".",
"asarray",
"(",
"other",
")",
"if",
"lvals",
".",
"shape",
"[",
"0",
"]",
"!=",
"rvals",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"Exception",
"(",
"f\"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}\"",
")",
"if",
"isinstance",
"(",
"other",
",",
"ABCDataFrame",
")",
":",
"return",
"self",
".",
"_constructor",
"(",
"np",
".",
"dot",
"(",
"lvals",
",",
"rvals",
")",
",",
"index",
"=",
"other",
".",
"columns",
")",
".",
"__finalize__",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"other",
",",
"Series",
")",
":",
"return",
"np",
".",
"dot",
"(",
"lvals",
",",
"rvals",
")",
"elif",
"isinstance",
"(",
"rvals",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"np",
".",
"dot",
"(",
"lvals",
",",
"rvals",
")",
"else",
":",
"# pragma: no cover",
"raise",
"TypeError",
"(",
"f\"unsupported type: {type(other)}\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py#L2406-L2482 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/symtable.py | python | Symbol.get_namespace | (self) | return self.__namespaces[0] | Returns the single namespace bound to this name.
Raises ValueError if the name is bound to multiple namespaces. | Returns the single namespace bound to this name. | [
"Returns",
"the",
"single",
"namespace",
"bound",
"to",
"this",
"name",
"."
] | def get_namespace(self):
"""Returns the single namespace bound to this name.
Raises ValueError if the name is bound to multiple namespaces.
"""
if len(self.__namespaces) != 1:
raise ValueError("name is bound to multiple namespaces")
return self.__namespaces[0] | [
"def",
"get_namespace",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"__namespaces",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"name is bound to multiple namespaces\"",
")",
"return",
"self",
".",
"__namespaces",
"[",
"0",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/symtable.py#L222-L229 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/transform.py | python | keep_t_if_possible_handler | (info, t) | Transform a tensor into itself (identity) if possible.
This handler transform a tensor into itself if the source and destination
graph are the same. Otherwise it will create a placeholder.
This handler is typically used to transform a hidden input tensors.
Args:
info: Transform._TmpInfo instance.
t: tensor whose input must be transformed into a place holder.
Returns:
The tensor generated by the newly created place holder. | Transform a tensor into itself (identity) if possible. | [
"Transform",
"a",
"tensor",
"into",
"itself",
"(",
"identity",
")",
"if",
"possible",
"."
] | def keep_t_if_possible_handler(info, t):
"""Transform a tensor into itself (identity) if possible.
This handler transform a tensor into itself if the source and destination
graph are the same. Otherwise it will create a placeholder.
This handler is typically used to transform a hidden input tensors.
Args:
info: Transform._TmpInfo instance.
t: tensor whose input must be transformed into a place holder.
Returns:
The tensor generated by the newly created place holder.
"""
if info.graph is info.graph_:
return t
else:
return replace_t_with_placeholder_handler(info, t) | [
"def",
"keep_t_if_possible_handler",
"(",
"info",
",",
"t",
")",
":",
"if",
"info",
".",
"graph",
"is",
"info",
".",
"graph_",
":",
"return",
"t",
"else",
":",
"return",
"replace_t_with_placeholder_handler",
"(",
"info",
",",
"t",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/transform.py#L66-L82 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/timeseries/examples/lstm.py | python | _LSTMModel._prediction_step | (self, current_times, state) | return new_state_tuple, {"mean": self._scale_back_data(next_prediction)} | Advance the RNN state using a previous observation or prediction. | Advance the RNN state using a previous observation or prediction. | [
"Advance",
"the",
"RNN",
"state",
"using",
"a",
"previous",
"observation",
"or",
"prediction",
"."
] | def _prediction_step(self, current_times, state):
"""Advance the RNN state using a previous observation or prediction."""
_, previous_observation_or_prediction, lstm_state = state
lstm_output, new_lstm_state = self._lstm_cell_run(
inputs=previous_observation_or_prediction, state=lstm_state)
next_prediction = self._predict_from_lstm_output(lstm_output)
new_state_tuple = (current_times, next_prediction, new_lstm_state)
return new_state_tuple, {"mean": self._scale_back_data(next_prediction)} | [
"def",
"_prediction_step",
"(",
"self",
",",
"current_times",
",",
"state",
")",
":",
"_",
",",
"previous_observation_or_prediction",
",",
"lstm_state",
"=",
"state",
"lstm_output",
",",
"new_lstm_state",
"=",
"self",
".",
"_lstm_cell_run",
"(",
"inputs",
"=",
"previous_observation_or_prediction",
",",
"state",
"=",
"lstm_state",
")",
"next_prediction",
"=",
"self",
".",
"_predict_from_lstm_output",
"(",
"lstm_output",
")",
"new_state_tuple",
"=",
"(",
"current_times",
",",
"next_prediction",
",",
"new_lstm_state",
")",
"return",
"new_state_tuple",
",",
"{",
"\"mean\"",
":",
"self",
".",
"_scale_back_data",
"(",
"next_prediction",
")",
"}"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/examples/lstm.py#L145-L152 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/FortranCommon.py | python | add_f03_to_env | (env) | Add Builders and construction variables for f03 to an Environment. | Add Builders and construction variables for f03 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f03",
"to",
"an",
"Environment",
"."
] | def add_f03_to_env(env):
"""Add Builders and construction variables for f03 to an Environment."""
try:
F03Suffixes = env['F03FILESUFFIXES']
except KeyError:
F03Suffixes = ['.f03']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F03PPSuffixes = env['F03PPFILESUFFIXES']
except KeyError:
F03PPSuffixes = []
DialectAddToEnv(env, "F03", F03Suffixes, F03PPSuffixes,
support_module = 1) | [
"def",
"add_f03_to_env",
"(",
"env",
")",
":",
"try",
":",
"F03Suffixes",
"=",
"env",
"[",
"'F03FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F03Suffixes",
"=",
"[",
"'.f03'",
"]",
"#print(\"Adding %s to f95 suffixes\" % F95Suffixes)",
"try",
":",
"F03PPSuffixes",
"=",
"env",
"[",
"'F03PPFILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F03PPSuffixes",
"=",
"[",
"]",
"DialectAddToEnv",
"(",
"env",
",",
"\"F03\"",
",",
"F03Suffixes",
",",
"F03PPSuffixes",
",",
"support_module",
"=",
"1",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/FortranCommon.py#L236-L250 | ||
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/EditorLib/Effect.py | python | EffectLogic.getScopedLabelInput | (self) | return( self.getScopedLayer(layerLogic) ) | return a vtkImageData corresponding to the scope | return a vtkImageData corresponding to the scope | [
"return",
"a",
"vtkImageData",
"corresponding",
"to",
"the",
"scope"
] | def getScopedLabelInput(self):
"""return a vtkImageData corresponding to the scope"""
layerLogic = self.sliceLogic.GetLabelLayer()
return( self.getScopedLayer(layerLogic) ) | [
"def",
"getScopedLabelInput",
"(",
"self",
")",
":",
"layerLogic",
"=",
"self",
".",
"sliceLogic",
".",
"GetLabelLayer",
"(",
")",
"return",
"(",
"self",
".",
"getScopedLayer",
"(",
"layerLogic",
")",
")"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/Effect.py#L386-L389 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py | python | WriteOnDiff | (filename) | return Writer() | Write to a file only if the new contents differ.
Arguments:
filename: name of the file to potentially write to.
Returns:
A file like object which will write to temporary file and only overwrite
the target if it differs (on close). | Write to a file only if the new contents differ. | [
"Write",
"to",
"a",
"file",
"only",
"if",
"the",
"new",
"contents",
"differ",
"."
] | def WriteOnDiff(filename):
"""Write to a file only if the new contents differ.
Arguments:
filename: name of the file to potentially write to.
Returns:
A file like object which will write to temporary file and only overwrite
the target if it differs (on close).
"""
class Writer(object):
"""Wrapper around file which only covers the target if it differs."""
def __init__(self):
# On Cygwin remove the "dir" argument because `C:` prefixed paths are treated as relative,
# consequently ending up with current dir "/cygdrive/c/..." being prefixed to those, which was
# obviously a non-existent path, for example: "/cygdrive/c/<some folder>/C:\<my win style abs path>".
# See https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp for more details
base_temp_dir = "" if IsCygwin() else os.path.dirname(filename)
# Pick temporary file.
tmp_fd, self.tmp_path = tempfile.mkstemp(
suffix='.tmp',
prefix=os.path.split(filename)[1] + '.gyp.',
dir=base_temp_dir)
try:
self.tmp_file = os.fdopen(tmp_fd, 'wb')
except Exception:
# Don't leave turds behind.
os.unlink(self.tmp_path)
raise
def __getattr__(self, attrname):
# Delegate everything else to self.tmp_file
return getattr(self.tmp_file, attrname)
def close(self):
try:
# Close tmp file.
self.tmp_file.close()
# Determine if different.
same = False
try:
same = filecmp.cmp(self.tmp_path, filename, False)
except OSError as e:
if e.errno != errno.ENOENT:
raise
if same:
# The new file is identical to the old one, just get rid of the new
# one.
os.unlink(self.tmp_path)
else:
# The new file is different from the old one, or there is no old one.
# Rename the new file to the permanent name.
#
# tempfile.mkstemp uses an overly restrictive mode, resulting in a
# file that can only be read by the owner, regardless of the umask.
# There's no reason to not respect the umask here, which means that
# an extra hoop is required to fetch it and reset the new file's mode.
#
# No way to get the umask without setting a new one? Set a safe one
# and then set it back to the old value.
umask = os.umask(0o77)
os.umask(umask)
os.chmod(self.tmp_path, 0o666 & ~umask)
if sys.platform == 'win32' and os.path.exists(filename):
# NOTE: on windows (but not cygwin) rename will not replace an
# existing file, so it must be preceded with a remove. Sadly there
# is no way to make the switch atomic.
os.remove(filename)
os.rename(self.tmp_path, filename)
except Exception:
# Don't leave turds behind.
os.unlink(self.tmp_path)
raise
def write(self, s):
self.tmp_file.write(s.encode('utf-8'))
return Writer() | [
"def",
"WriteOnDiff",
"(",
"filename",
")",
":",
"class",
"Writer",
"(",
"object",
")",
":",
"\"\"\"Wrapper around file which only covers the target if it differs.\"\"\"",
"def",
"__init__",
"(",
"self",
")",
":",
"# On Cygwin remove the \"dir\" argument because `C:` prefixed paths are treated as relative,",
"# consequently ending up with current dir \"/cygdrive/c/...\" being prefixed to those, which was",
"# obviously a non-existent path, for example: \"/cygdrive/c/<some folder>/C:\\<my win style abs path>\".",
"# See https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp for more details",
"base_temp_dir",
"=",
"\"\"",
"if",
"IsCygwin",
"(",
")",
"else",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"# Pick temporary file.",
"tmp_fd",
",",
"self",
".",
"tmp_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.tmp'",
",",
"prefix",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"[",
"1",
"]",
"+",
"'.gyp.'",
",",
"dir",
"=",
"base_temp_dir",
")",
"try",
":",
"self",
".",
"tmp_file",
"=",
"os",
".",
"fdopen",
"(",
"tmp_fd",
",",
"'wb'",
")",
"except",
"Exception",
":",
"# Don't leave turds behind.",
"os",
".",
"unlink",
"(",
"self",
".",
"tmp_path",
")",
"raise",
"def",
"__getattr__",
"(",
"self",
",",
"attrname",
")",
":",
"# Delegate everything else to self.tmp_file",
"return",
"getattr",
"(",
"self",
".",
"tmp_file",
",",
"attrname",
")",
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"# Close tmp file.",
"self",
".",
"tmp_file",
".",
"close",
"(",
")",
"# Determine if different.",
"same",
"=",
"False",
"try",
":",
"same",
"=",
"filecmp",
".",
"cmp",
"(",
"self",
".",
"tmp_path",
",",
"filename",
",",
"False",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"if",
"same",
":",
"# The new file is identical to the old one, just get rid of the new",
"# one.",
"os",
".",
"unlink",
"(",
"self",
".",
"tmp_path",
")",
"else",
":",
"# The new file is different from the old one, or there is no old one.",
"# Rename the new file to the permanent name.",
"#",
"# tempfile.mkstemp uses an overly restrictive mode, resulting in a",
"# file that can only be read by the owner, regardless of the umask.",
"# There's no reason to not respect the umask here, which means that",
"# an extra hoop is required to fetch it and reset the new file's mode.",
"#",
"# No way to get the umask without setting a new one? Set a safe one",
"# and then set it back to the old value.",
"umask",
"=",
"os",
".",
"umask",
"(",
"0o77",
")",
"os",
".",
"umask",
"(",
"umask",
")",
"os",
".",
"chmod",
"(",
"self",
".",
"tmp_path",
",",
"0o666",
"&",
"~",
"umask",
")",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"# NOTE: on windows (but not cygwin) rename will not replace an",
"# existing file, so it must be preceded with a remove. Sadly there",
"# is no way to make the switch atomic.",
"os",
".",
"remove",
"(",
"filename",
")",
"os",
".",
"rename",
"(",
"self",
".",
"tmp_path",
",",
"filename",
")",
"except",
"Exception",
":",
"# Don't leave turds behind.",
"os",
".",
"unlink",
"(",
"self",
".",
"tmp_path",
")",
"raise",
"def",
"write",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"tmp_file",
".",
"write",
"(",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"Writer",
"(",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py#L334-L412 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xmlDoc.htmlSaveFileEnc | (self, filename, encoding) | return ret | Dump an HTML document to a file using a given encoding and
formatting returns/spaces are added. | Dump an HTML document to a file using a given encoding and
formatting returns/spaces are added. | [
"Dump",
"an",
"HTML",
"document",
"to",
"a",
"file",
"using",
"a",
"given",
"encoding",
"and",
"formatting",
"returns",
"/",
"spaces",
"are",
"added",
"."
] | def htmlSaveFileEnc(self, filename, encoding):
"""Dump an HTML document to a file using a given encoding and
formatting returns/spaces are added. """
ret = libxml2mod.htmlSaveFileEnc(filename, self._o, encoding)
return ret | [
"def",
"htmlSaveFileEnc",
"(",
"self",
",",
"filename",
",",
"encoding",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlSaveFileEnc",
"(",
"filename",
",",
"self",
".",
"_o",
",",
"encoding",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4057-L4061 | |
pristineio/webrtc-mirror | 7a5bcdffaab90a05bc1146b2b1ea71c004e54d71 | PRESUBMIT.py | python | _CheckChangeHasBugField | (input_api, output_api) | Requires that the changelist have a BUG= field.
This check is stricter than the one in depot_tools/presubmit_canned_checks.py
since it fails the presubmit if the BUG= field is missing or doesn't contain
a bug reference. | Requires that the changelist have a BUG= field. | [
"Requires",
"that",
"the",
"changelist",
"have",
"a",
"BUG",
"=",
"field",
"."
] | def _CheckChangeHasBugField(input_api, output_api):
"""Requires that the changelist have a BUG= field.
This check is stricter than the one in depot_tools/presubmit_canned_checks.py
since it fails the presubmit if the BUG= field is missing or doesn't contain
a bug reference.
"""
if input_api.change.BUG:
return []
else:
return [output_api.PresubmitError(
'The BUG=[bug number] field is mandatory. Please create a bug and '
'reference it using either of:\n'
' * https://bugs.webrtc.org - reference it using BUG=webrtc:XXXX\n'
' * https://crbug.com - reference it using BUG=chromium:XXXXXX')] | [
"def",
"_CheckChangeHasBugField",
"(",
"input_api",
",",
"output_api",
")",
":",
"if",
"input_api",
".",
"change",
".",
"BUG",
":",
"return",
"[",
"]",
"else",
":",
"return",
"[",
"output_api",
".",
"PresubmitError",
"(",
"'The BUG=[bug number] field is mandatory. Please create a bug and '",
"'reference it using either of:\\n'",
"' * https://bugs.webrtc.org - reference it using BUG=webrtc:XXXX\\n'",
"' * https://crbug.com - reference it using BUG=chromium:XXXXXX'",
")",
"]"
] | https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/PRESUBMIT.py#L425-L439 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_CertifyX509_REQUEST.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.reserved = buf.readSizedByteBuf()
inSchemeScheme = buf.readShort()
self.inScheme = UnionFactory.create('TPMU_SIG_SCHEME', inSchemeScheme)
self.inScheme.initFromTpm(buf)
self.partialCertificate = buf.readSizedByteBuf() | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"reserved",
"=",
"buf",
".",
"readSizedByteBuf",
"(",
")",
"inSchemeScheme",
"=",
"buf",
".",
"readShort",
"(",
")",
"self",
".",
"inScheme",
"=",
"UnionFactory",
".",
"create",
"(",
"'TPMU_SIG_SCHEME'",
",",
"inSchemeScheme",
")",
"self",
".",
"inScheme",
".",
"initFromTpm",
"(",
"buf",
")",
"self",
".",
"partialCertificate",
"=",
"buf",
".",
"readSizedByteBuf",
"(",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L13156-L13162 | ||
cztomczak/cefpython | 5679f28cec18a57a56e298da2927aac8d8f83ad6 | tools/build.py | python | generate_cefpython_module_variables | () | return ret | Global variables that will be appended to cefpython.pyx sources. | Global variables that will be appended to cefpython.pyx sources. | [
"Global",
"variables",
"that",
"will",
"be",
"appended",
"to",
"cefpython",
".",
"pyx",
"sources",
"."
] | def generate_cefpython_module_variables():
"""Global variables that will be appended to cefpython.pyx sources."""
ret = ('__version__ = "{0}"\n'.format(VERSION))
version = get_cefpython_version()
chrome_version = "{0}.{1}.{2}.{3}".format(
version["CHROME_VERSION_MAJOR"], version["CHROME_VERSION_MINOR"],
version["CHROME_VERSION_BUILD"], version["CHROME_VERSION_PATCH"])
ret += ('__chrome_version__ = "{0}"\n'.format(chrome_version))
ret += ('__cef_version__ = "{0}"\n'.format(version["CEF_VERSION"]))
ret += ('__cef_api_hash_platform__ = "{0}"\n'
.format(version["CEF_API_HASH_PLATFORM"]))
ret += ('__cef_api_hash_universal__ = "{0}"\n'
.format(version["CEF_API_HASH_UNIVERSAL"]))
ret += ('__cef_commit_hash__ = "{0}"\n'
.format(version["CEF_COMMIT_HASH"]))
ret += ('__cef_commit_number__ = "{0}"\n'
.format(version["CEF_COMMIT_NUMBER"]))
return ret | [
"def",
"generate_cefpython_module_variables",
"(",
")",
":",
"ret",
"=",
"(",
"'__version__ = \"{0}\"\\n'",
".",
"format",
"(",
"VERSION",
")",
")",
"version",
"=",
"get_cefpython_version",
"(",
")",
"chrome_version",
"=",
"\"{0}.{1}.{2}.{3}\"",
".",
"format",
"(",
"version",
"[",
"\"CHROME_VERSION_MAJOR\"",
"]",
",",
"version",
"[",
"\"CHROME_VERSION_MINOR\"",
"]",
",",
"version",
"[",
"\"CHROME_VERSION_BUILD\"",
"]",
",",
"version",
"[",
"\"CHROME_VERSION_PATCH\"",
"]",
")",
"ret",
"+=",
"(",
"'__chrome_version__ = \"{0}\"\\n'",
".",
"format",
"(",
"chrome_version",
")",
")",
"ret",
"+=",
"(",
"'__cef_version__ = \"{0}\"\\n'",
".",
"format",
"(",
"version",
"[",
"\"CEF_VERSION\"",
"]",
")",
")",
"ret",
"+=",
"(",
"'__cef_api_hash_platform__ = \"{0}\"\\n'",
".",
"format",
"(",
"version",
"[",
"\"CEF_API_HASH_PLATFORM\"",
"]",
")",
")",
"ret",
"+=",
"(",
"'__cef_api_hash_universal__ = \"{0}\"\\n'",
".",
"format",
"(",
"version",
"[",
"\"CEF_API_HASH_UNIVERSAL\"",
"]",
")",
")",
"ret",
"+=",
"(",
"'__cef_commit_hash__ = \"{0}\"\\n'",
".",
"format",
"(",
"version",
"[",
"\"CEF_COMMIT_HASH\"",
"]",
")",
")",
"ret",
"+=",
"(",
"'__cef_commit_number__ = \"{0}\"\\n'",
".",
"format",
"(",
"version",
"[",
"\"CEF_COMMIT_NUMBER\"",
"]",
")",
")",
"return",
"ret"
] | https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/build.py#L706-L723 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DropTarget.OnDrop | (*args, **kwargs) | return _misc_.DropTarget_OnDrop(*args, **kwargs) | OnDrop(self, int x, int y) -> bool | OnDrop(self, int x, int y) -> bool | [
"OnDrop",
"(",
"self",
"int",
"x",
"int",
"y",
")",
"-",
">",
"bool"
] | def OnDrop(*args, **kwargs):
"""OnDrop(self, int x, int y) -> bool"""
return _misc_.DropTarget_OnDrop(*args, **kwargs) | [
"def",
"OnDrop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DropTarget_OnDrop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L5579-L5581 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/bindings/python/clang/cindex.py | python | CompileCommand.arguments | (self) | Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable | Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString. | [
"Get",
"an",
"iterable",
"object",
"providing",
"each",
"argument",
"in",
"the",
"command",
"line",
"for",
"the",
"compiler",
"invocation",
"as",
"a",
"_CXString",
"."
] | def arguments(self):
"""
Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable
"""
length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
for i in range(length):
yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) | [
"def",
"arguments",
"(",
"self",
")",
":",
"length",
"=",
"conf",
".",
"lib",
".",
"clang_CompileCommand_getNumArgs",
"(",
"self",
".",
"cmd",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"yield",
"conf",
".",
"lib",
".",
"clang_CompileCommand_getArg",
"(",
"self",
".",
"cmd",
",",
"i",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/bindings/python/clang/cindex.py#L3189-L3198 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/array_ops.py | python | flipud | (m) | return flip(m, 0) | Flips the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Args:
m (Tensor): Input array.
Returns:
Tensor.
Raises:
TypeError: If the input is not a tensor.
Supported Platforms:
``GPU`` ``CPU``
Example:
>>> import mindspore.numpy as np
>>> A = np.arange(8.0).reshape((2,2,2))
>>> output = np.flipud(A)
>>> print(output)
[[[4. 5.]
[6. 7.]]
[[0. 1.]
[2. 3.]]] | Flips the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before. | [
"Flips",
"the",
"entries",
"in",
"each",
"column",
"in",
"the",
"up",
"/",
"down",
"direction",
".",
"Rows",
"are",
"preserved",
"but",
"appear",
"in",
"a",
"different",
"order",
"than",
"before",
"."
] | def flipud(m):
"""
Flips the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Args:
m (Tensor): Input array.
Returns:
Tensor.
Raises:
TypeError: If the input is not a tensor.
Supported Platforms:
``GPU`` ``CPU``
Example:
>>> import mindspore.numpy as np
>>> A = np.arange(8.0).reshape((2,2,2))
>>> output = np.flipud(A)
>>> print(output)
[[[4. 5.]
[6. 7.]]
[[0. 1.]
[2. 3.]]]
"""
return flip(m, 0) | [
"def",
"flipud",
"(",
"m",
")",
":",
"return",
"flip",
"(",
"m",
",",
"0",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/array_ops.py#L1684-L1711 | |
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | python/caffe/MultilabelDataLayer.py | python | Multilabel_Data_Layer.backward | (self, top, propagate_down, bottom) | These layers does not back propagate | These layers does not back propagate | [
"These",
"layers",
"does",
"not",
"back",
"propagate"
] | def backward(self, top, propagate_down, bottom):
"""
These layers does not back propagate
"""
pass | [
"def",
"backward",
"(",
"self",
",",
"top",
",",
"propagate_down",
",",
"bottom",
")",
":",
"pass"
] | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/MultilabelDataLayer.py#L106-L110 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Display.GetName | (*args, **kwargs) | return _misc_.Display_GetName(*args, **kwargs) | GetName(self) -> String
Returns the display's name. A name is not available on all platforms. | GetName(self) -> String | [
"GetName",
"(",
"self",
")",
"-",
">",
"String"
] | def GetName(*args, **kwargs):
"""
GetName(self) -> String
Returns the display's name. A name is not available on all platforms.
"""
return _misc_.Display_GetName(*args, **kwargs) | [
"def",
"GetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Display_GetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6148-L6154 | |
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | tools/extra/parse_log.py | python | parse_log | (path_to_log) | return train_dict_list, test_dict_list | Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_list are lists of dicts that define the table
rows | Parse log file
Returns (train_dict_list, test_dict_list) | [
"Parse",
"log",
"file",
"Returns",
"(",
"train_dict_list",
"test_dict_list",
")"
] | def parse_log(path_to_log):
"""Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_list are lists of dicts that define the table
rows
"""
regex_iteration = re.compile('Iteration (\d+)')
regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_learning_rate = re.compile('lr = ([-+]?[0-9]*\.?[0-9]+([eE]?[-+]?[0-9]+)?)')
# Pick out lines of interest
iteration = -1
learning_rate = float('NaN')
train_dict_list = []
test_dict_list = []
train_row = None
test_row = None
logfile_year = extract_seconds.get_log_created_year(path_to_log)
with open(path_to_log) as f:
start_time = extract_seconds.get_start_time(f, logfile_year)
for line in f:
iteration_match = regex_iteration.search(line)
if iteration_match:
iteration = float(iteration_match.group(1))
if iteration == -1:
# Only start parsing for other stuff if we've found the first
# iteration
continue
time = extract_seconds.extract_datetime_from_line(line,
logfile_year)
seconds = (time - start_time).total_seconds()
learning_rate_match = regex_learning_rate.search(line)
if learning_rate_match:
learning_rate = float(learning_rate_match.group(1))
train_dict_list, train_row = parse_line_for_net_output(
regex_train_output, train_row, train_dict_list,
line, iteration, seconds, learning_rate
)
test_dict_list, test_row = parse_line_for_net_output(
regex_test_output, test_row, test_dict_list,
line, iteration, seconds, learning_rate
)
fix_initial_nan_learning_rate(train_dict_list)
fix_initial_nan_learning_rate(test_dict_list)
return train_dict_list, test_dict_list | [
"def",
"parse_log",
"(",
"path_to_log",
")",
":",
"regex_iteration",
"=",
"re",
".",
"compile",
"(",
"'Iteration (\\d+)'",
")",
"regex_train_output",
"=",
"re",
".",
"compile",
"(",
"'Train net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'",
")",
"regex_test_output",
"=",
"re",
".",
"compile",
"(",
"'Test net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'",
")",
"regex_learning_rate",
"=",
"re",
".",
"compile",
"(",
"'lr = ([-+]?[0-9]*\\.?[0-9]+([eE]?[-+]?[0-9]+)?)'",
")",
"# Pick out lines of interest",
"iteration",
"=",
"-",
"1",
"learning_rate",
"=",
"float",
"(",
"'NaN'",
")",
"train_dict_list",
"=",
"[",
"]",
"test_dict_list",
"=",
"[",
"]",
"train_row",
"=",
"None",
"test_row",
"=",
"None",
"logfile_year",
"=",
"extract_seconds",
".",
"get_log_created_year",
"(",
"path_to_log",
")",
"with",
"open",
"(",
"path_to_log",
")",
"as",
"f",
":",
"start_time",
"=",
"extract_seconds",
".",
"get_start_time",
"(",
"f",
",",
"logfile_year",
")",
"for",
"line",
"in",
"f",
":",
"iteration_match",
"=",
"regex_iteration",
".",
"search",
"(",
"line",
")",
"if",
"iteration_match",
":",
"iteration",
"=",
"float",
"(",
"iteration_match",
".",
"group",
"(",
"1",
")",
")",
"if",
"iteration",
"==",
"-",
"1",
":",
"# Only start parsing for other stuff if we've found the first",
"# iteration",
"continue",
"time",
"=",
"extract_seconds",
".",
"extract_datetime_from_line",
"(",
"line",
",",
"logfile_year",
")",
"seconds",
"=",
"(",
"time",
"-",
"start_time",
")",
".",
"total_seconds",
"(",
")",
"learning_rate_match",
"=",
"regex_learning_rate",
".",
"search",
"(",
"line",
")",
"if",
"learning_rate_match",
":",
"learning_rate",
"=",
"float",
"(",
"learning_rate_match",
".",
"group",
"(",
"1",
")",
")",
"train_dict_list",
",",
"train_row",
"=",
"parse_line_for_net_output",
"(",
"regex_train_output",
",",
"train_row",
",",
"train_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
"test_dict_list",
",",
"test_row",
"=",
"parse_line_for_net_output",
"(",
"regex_test_output",
",",
"test_row",
",",
"test_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
"fix_initial_nan_learning_rate",
"(",
"train_dict_list",
")",
"fix_initial_nan_learning_rate",
"(",
"test_dict_list",
")",
"return",
"train_dict_list",
",",
"test_dict_list"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/tools/extra/parse_log.py#L17-L71 | |
martinmoene/span-lite | 8f7935ff4e502ee023990d356d6578b8293eda74 | script/create-cov-rpt.py | python | executable_name | ( f ) | return os.path.basename( f ) | Folder where the executable is | Folder where the executable is | [
"Folder",
"where",
"the",
"executable",
"is"
] | def executable_name( f ):
"""Folder where the executable is"""
return os.path.basename( f ) | [
"def",
"executable_name",
"(",
"f",
")",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")"
] | https://github.com/martinmoene/span-lite/blob/8f7935ff4e502ee023990d356d6578b8293eda74/script/create-cov-rpt.py#L37-L39 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/_vendor/packaging/markers.py | python | Marker.evaluate | (self, environment=None) | return _evaluate_markers(self._markers, current_environment) | Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process. | Evaluate a marker. | [
"Evaluate",
"a",
"marker",
"."
] | def evaluate(self, environment=None):
"""Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process.
"""
current_environment = default_environment()
if environment is not None:
current_environment.update(environment)
return _evaluate_markers(self._markers, current_environment) | [
"def",
"evaluate",
"(",
"self",
",",
"environment",
"=",
"None",
")",
":",
"current_environment",
"=",
"default_environment",
"(",
")",
"if",
"environment",
"is",
"not",
"None",
":",
"current_environment",
".",
"update",
"(",
"environment",
")",
"return",
"_evaluate_markers",
"(",
"self",
".",
"_markers",
",",
"current_environment",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/_vendor/packaging/markers.py#L288-L301 | |
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Base/Python/slicer/util.py | python | arrayFromModelCellDataModified | (modelNode, arrayName) | Indicate that modification of a numpy array returned by :py:meth:`arrayFromModelCellData` has been completed. | Indicate that modification of a numpy array returned by :py:meth:`arrayFromModelCellData` has been completed. | [
"Indicate",
"that",
"modification",
"of",
"a",
"numpy",
"array",
"returned",
"by",
":",
"py",
":",
"meth",
":",
"arrayFromModelCellData",
"has",
"been",
"completed",
"."
] | def arrayFromModelCellDataModified(modelNode, arrayName):
"""Indicate that modification of a numpy array returned by :py:meth:`arrayFromModelCellData` has been completed."""
arrayVtk = _vtkArrayFromModelData(modelNode, arrayName, 'cell')
arrayVtk.Modified() | [
"def",
"arrayFromModelCellDataModified",
"(",
"modelNode",
",",
"arrayName",
")",
":",
"arrayVtk",
"=",
"_vtkArrayFromModelData",
"(",
"modelNode",
",",
"arrayName",
",",
"'cell'",
")",
"arrayVtk",
".",
"Modified",
"(",
")"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L1570-L1573 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | App.SetOutputWindowAttributes | (self, title=None, pos=None, size=None) | Set the title, position and/or size of the output window if
the stdio has been redirected. This should be called before
any output would cause the output window to be created. | Set the title, position and/or size of the output window if
the stdio has been redirected. This should be called before
any output would cause the output window to be created. | [
"Set",
"the",
"title",
"position",
"and",
"/",
"or",
"size",
"of",
"the",
"output",
"window",
"if",
"the",
"stdio",
"has",
"been",
"redirected",
".",
"This",
"should",
"be",
"called",
"before",
"any",
"output",
"would",
"cause",
"the",
"output",
"window",
"to",
"be",
"created",
"."
] | def SetOutputWindowAttributes(self, title=None, pos=None, size=None):
"""
Set the title, position and/or size of the output window if
the stdio has been redirected. This should be called before
any output would cause the output window to be created.
"""
if self.stdioWin:
if title is not None:
self.stdioWin.title = title
if pos is not None:
self.stdioWin.pos = pos
if size is not None:
self.stdioWin.size = size | [
"def",
"SetOutputWindowAttributes",
"(",
"self",
",",
"title",
"=",
"None",
",",
"pos",
"=",
"None",
",",
"size",
"=",
"None",
")",
":",
"if",
"self",
".",
"stdioWin",
":",
"if",
"title",
"is",
"not",
"None",
":",
"self",
".",
"stdioWin",
".",
"title",
"=",
"title",
"if",
"pos",
"is",
"not",
"None",
":",
"self",
".",
"stdioWin",
".",
"pos",
"=",
"pos",
"if",
"size",
"is",
"not",
"None",
":",
"self",
".",
"stdioWin",
".",
"size",
"=",
"size"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L8677-L8689 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/profiler/pprof_profiler.py | python | profile | (graph, run_metadata, output_dir=None) | return profile_files | Generate profiles in pprof format.
See https://github.com/google/pprof/blob/master/proto/profile.proto
for pprof proto format.
Args:
graph: A `Graph` object.
run_metadata: A `RunMetadata` proto.
output_dir: (string) Directory to output pprof profile to.
Profile files for each device will be stored in compressed
serialized proto format. If output_dir is None, profile protos
will be printed to stdout instead.
Returns:
List of output files created by this profile call.
(Note: this list will be empty if output_dir is None) | Generate profiles in pprof format. | [
"Generate",
"profiles",
"in",
"pprof",
"format",
"."
] | def profile(graph, run_metadata, output_dir=None):
"""Generate profiles in pprof format.
See https://github.com/google/pprof/blob/master/proto/profile.proto
for pprof proto format.
Args:
graph: A `Graph` object.
run_metadata: A `RunMetadata` proto.
output_dir: (string) Directory to output pprof profile to.
Profile files for each device will be stored in compressed
serialized proto format. If output_dir is None, profile protos
will be printed to stdout instead.
Returns:
List of output files created by this profile call.
(Note: this list will be empty if output_dir is None)
"""
profiles = get_profiles(graph, run_metadata)
output_file_template = None
if output_dir:
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
time_suffix = time.strftime('%Y%m%d%H%M%S')
output_file_template = os.path.join(
output_dir, '%s_' + time_suffix + '.pb.gz')
profile_files = []
for device, pprof_proto in profiles.items():
if output_file_template is None:
print('No output directory specified, printing to stdout instead.')
print(pprof_proto)
else:
device_name = str(device).strip('/').translate(
maketrans('/:', '__'))
profile_file = output_file_template % device_name
profile_files.append(profile_file)
with gzip.open(profile_file, 'w') as output_file:
print('Writing profile to %s...' % profile_file)
output_file.write(pprof_proto.SerializeToString())
return profile_files | [
"def",
"profile",
"(",
"graph",
",",
"run_metadata",
",",
"output_dir",
"=",
"None",
")",
":",
"profiles",
"=",
"get_profiles",
"(",
"graph",
",",
"run_metadata",
")",
"output_file_template",
"=",
"None",
"if",
"output_dir",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"output_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"output_dir",
")",
"time_suffix",
"=",
"time",
".",
"strftime",
"(",
"'%Y%m%d%H%M%S'",
")",
"output_file_template",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'%s_'",
"+",
"time_suffix",
"+",
"'.pb.gz'",
")",
"profile_files",
"=",
"[",
"]",
"for",
"device",
",",
"pprof_proto",
"in",
"profiles",
".",
"items",
"(",
")",
":",
"if",
"output_file_template",
"is",
"None",
":",
"print",
"(",
"'No output directory specified, printing to stdout instead.'",
")",
"print",
"(",
"pprof_proto",
")",
"else",
":",
"device_name",
"=",
"str",
"(",
"device",
")",
".",
"strip",
"(",
"'/'",
")",
".",
"translate",
"(",
"maketrans",
"(",
"'/:'",
",",
"'__'",
")",
")",
"profile_file",
"=",
"output_file_template",
"%",
"device_name",
"profile_files",
".",
"append",
"(",
"profile_file",
")",
"with",
"gzip",
".",
"open",
"(",
"profile_file",
",",
"'w'",
")",
"as",
"output_file",
":",
"print",
"(",
"'Writing profile to %s...'",
"%",
"profile_file",
")",
"output_file",
".",
"write",
"(",
"pprof_proto",
".",
"SerializeToString",
"(",
")",
")",
"return",
"profile_files"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/profiler/pprof_profiler.py#L405-L445 | |
facebook/proxygen | a9ca025af207787815cb01eee1971cd572c7a81e | build/fbcode_builder/getdeps/cargo.py | python | CargoBuilder._resolve_crate_to_path | (crate, git_conf) | Tries to find <crate> in git_conf["inst_dir"] by searching a [package]
keyword followed by name = "<crate>". | Tries to find <crate> in git_conf["inst_dir"] by searching a [package]
keyword followed by name = "<crate>". | [
"Tries",
"to",
"find",
"<crate",
">",
"in",
"git_conf",
"[",
"inst_dir",
"]",
"by",
"searching",
"a",
"[",
"package",
"]",
"keyword",
"followed",
"by",
"name",
"=",
"<crate",
">",
"."
] | def _resolve_crate_to_path(crate, git_conf):
"""
Tries to find <crate> in git_conf["inst_dir"] by searching a [package]
keyword followed by name = "<crate>".
"""
source_dir = git_conf["source_dir"]
search_pattern = '[package]\nname = "{}"'.format(crate)
for root, _, files in os.walk(source_dir):
for fname in files:
if fname == "Cargo.toml":
with open(os.path.join(root, fname), "r") as f:
if search_pattern in f.read():
return root
raise Exception("Failed to found crate {} in path {}".format(crate, source_dir)) | [
"def",
"_resolve_crate_to_path",
"(",
"crate",
",",
"git_conf",
")",
":",
"source_dir",
"=",
"git_conf",
"[",
"\"source_dir\"",
"]",
"search_pattern",
"=",
"'[package]\\nname = \"{}\"'",
".",
"format",
"(",
"crate",
")",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"source_dir",
")",
":",
"for",
"fname",
"in",
"files",
":",
"if",
"fname",
"==",
"\"Cargo.toml\"",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"fname",
")",
",",
"\"r\"",
")",
"as",
"f",
":",
"if",
"search_pattern",
"in",
"f",
".",
"read",
"(",
")",
":",
"return",
"root",
"raise",
"Exception",
"(",
"\"Failed to found crate {} in path {}\"",
".",
"format",
"(",
"crate",
",",
"source_dir",
")",
")"
] | https://github.com/facebook/proxygen/blob/a9ca025af207787815cb01eee1971cd572c7a81e/build/fbcode_builder/getdeps/cargo.py#L300-L315 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/_lib/decorator.py | python | append | (a, vancestors) | Append ``a`` to the list of the virtual ancestors, unless it is already
included. | Append ``a`` to the list of the virtual ancestors, unless it is already
included. | [
"Append",
"a",
"to",
"the",
"list",
"of",
"the",
"virtual",
"ancestors",
"unless",
"it",
"is",
"already",
"included",
"."
] | def append(a, vancestors):
"""
Append ``a`` to the list of the virtual ancestors, unless it is already
included.
"""
add = True
for j, va in enumerate(vancestors):
if issubclass(va, a):
add = False
break
if issubclass(a, va):
vancestors[j] = a
add = False
if add:
vancestors.append(a) | [
"def",
"append",
"(",
"a",
",",
"vancestors",
")",
":",
"add",
"=",
"True",
"for",
"j",
",",
"va",
"in",
"enumerate",
"(",
"vancestors",
")",
":",
"if",
"issubclass",
"(",
"va",
",",
"a",
")",
":",
"add",
"=",
"False",
"break",
"if",
"issubclass",
"(",
"a",
",",
"va",
")",
":",
"vancestors",
"[",
"j",
"]",
"=",
"a",
"add",
"=",
"False",
"if",
"add",
":",
"vancestors",
".",
"append",
"(",
"a",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/_lib/decorator.py#L305-L319 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/io/netcdf.py | python | netcdf_variable._apply_missing_value | (data, missing_value) | return newdata | Applies the given missing value to the data array.
Returns a numpy.ma array, with any value equal to missing_value masked
out (unless missing_value is None, in which case the original array is
returned). | Applies the given missing value to the data array. | [
"Applies",
"the",
"given",
"missing",
"value",
"to",
"the",
"data",
"array",
"."
] | def _apply_missing_value(data, missing_value):
"""
Applies the given missing value to the data array.
Returns a numpy.ma array, with any value equal to missing_value masked
out (unless missing_value is None, in which case the original array is
returned).
"""
if missing_value is None:
newdata = data
else:
try:
missing_value_isnan = np.isnan(missing_value)
except (TypeError, NotImplementedError):
# some data types (e.g., characters) cannot be tested for NaN
missing_value_isnan = False
if missing_value_isnan:
mymask = np.isnan(data)
else:
mymask = (data == missing_value)
newdata = np.ma.masked_where(mymask, data)
return newdata | [
"def",
"_apply_missing_value",
"(",
"data",
",",
"missing_value",
")",
":",
"if",
"missing_value",
"is",
"None",
":",
"newdata",
"=",
"data",
"else",
":",
"try",
":",
"missing_value_isnan",
"=",
"np",
".",
"isnan",
"(",
"missing_value",
")",
"except",
"(",
"TypeError",
",",
"NotImplementedError",
")",
":",
"# some data types (e.g., characters) cannot be tested for NaN",
"missing_value_isnan",
"=",
"False",
"if",
"missing_value_isnan",
":",
"mymask",
"=",
"np",
".",
"isnan",
"(",
"data",
")",
"else",
":",
"mymask",
"=",
"(",
"data",
"==",
"missing_value",
")",
"newdata",
"=",
"np",
".",
"ma",
".",
"masked_where",
"(",
"mymask",
",",
"data",
")",
"return",
"newdata"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/netcdf.py#L1007-L1032 | |
limbo018/DREAMPlace | 146c3b9fd003d1acd52c96d9fd02e3f0a05154e4 | dreamplace/ops/draw_place/PlaceDrawer.py | python | PlaceDrawer.forward | (pos,
node_size_x,
node_size_y,
pin_offset_x,
pin_offset_y,
pin2node_map,
xl,
yl,
xh,
yh,
site_width,
row_height,
bin_size_x,
bin_size_y,
num_movable_nodes,
num_filler_nodes,
filename,
iteration=None) | return 1 | @brief python implementation of placement drawer.
@param pos locations of cells
@param node_size_x array of cell width
@param node_size_y array of cell height
@param pin_offset_x pin offset to cell origin
@param pin_offset_y pin offset to cell origin
@param pin2node_map map pin to cell
@param xl left boundary
@param yl bottom boundary
@param xh right boundary
@param yh top boundary
@param site_width width of placement site
@param row_height height of placement row, equivalent to height of placement site
@param bin_size_x bin width
@param bin_size_y bin height
@param num_movable_nodes number of movable cells
@param num_filler_nodes number of filler cells
@param filename output filename
@param iteration current optimization step | [] | def forward(pos,
node_size_x,
node_size_y,
pin_offset_x,
pin_offset_y,
pin2node_map,
xl,
yl,
xh,
yh,
site_width,
row_height,
bin_size_x,
bin_size_y,
num_movable_nodes,
num_filler_nodes,
filename,
iteration=None):
"""
@brief python implementation of placement drawer.
@param pos locations of cells
@param node_size_x array of cell width
@param node_size_y array of cell height
@param pin_offset_x pin offset to cell origin
@param pin_offset_y pin offset to cell origin
@param pin2node_map map pin to cell
@param xl left boundary
@param yl bottom boundary
@param xh right boundary
@param yh top boundary
@param site_width width of placement site
@param row_height height of placement row, equivalent to height of placement site
@param bin_size_x bin width
@param bin_size_y bin height
@param num_movable_nodes number of movable cells
@param num_filler_nodes number of filler cells
@param filename output filename
@param iteration current optimization step
"""
num_nodes = len(pos) // 2
num_movable_nodes = num_movable_nodes
num_filler_nodes = num_filler_nodes
num_physical_nodes = num_nodes - num_filler_nodes
num_bins_x = int(math.ceil((xh - xl) / bin_size_x))
num_bins_y = int(math.ceil((yh - yl) / bin_size_y))
x = np.array(pos[:num_nodes])
y = np.array(pos[num_nodes:])
node_size_x = np.array(node_size_x)
node_size_y = np.array(node_size_y)
pin_offset_x = np.array(pin_offset_x)
pin_offset_y = np.array(pin_offset_y)
pin2node_map = np.array(pin2node_map)
try:
tt = time.time()
if xh - xl < yh - yl:
height = 800
width = round(height * (xh - xl) / (yh - yl))
else:
width = 800
height = round(width * (yh - yl) / (xh -xl))
line_width = 0.1
padding = 0
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
# Do not use scale function.
# This is not compatible with show_text
if num_movable_nodes < num_physical_nodes:
layout_xl = min(
np.amin(x[num_movable_nodes:num_physical_nodes]), xl)
layout_yl = min(
np.amin(y[num_movable_nodes:num_physical_nodes]), yl)
layout_xh = max(
np.amax(x[num_movable_nodes:num_physical_nodes] +
node_size_x[num_movable_nodes:num_physical_nodes]),
xh)
layout_yh = max(
np.amax(y[num_movable_nodes:num_physical_nodes] +
node_size_y[num_movable_nodes:num_physical_nodes]),
yh)
else:
layout_xl = xl
layout_yl = yl
layout_xh = xh
layout_yh = yh
def bin_xl(id_x):
"""
@param id_x horizontal index
@return bin xl
"""
return xl + id_x * bin_size_x
def bin_xh(id_x):
"""
@param id_x horizontal index
@return bin xh
"""
return min(bin_xl(id_x) + bin_size_x, xh)
def bin_yl(id_y):
"""
@param id_y vertical index
@return bin yl
"""
return yl + id_y * bin_size_y
def bin_yh(id_y):
"""
@param id_y vertical index
@return bin yh
"""
return min(bin_yl(id_y) + bin_size_y, yh)
def normalize_x(xx):
return (xx - (layout_xl - padding * bin_size_x)) / (
layout_xh - layout_xl + padding * 2 * bin_size_x) * width
def normalize_y(xx):
return (xx - (layout_yl - padding * bin_size_y)) / (
layout_yh - layout_yl + padding * 2 * bin_size_y) * height
def draw_rect(x1, y1, x2, y2):
ctx.move_to(x1, y1)
ctx.line_to(x1, y2)
ctx.line_to(x2, y2)
ctx.line_to(x2, y1)
ctx.close_path()
ctx.stroke()
# draw layout region
ctx.set_source_rgb(1, 1, 1)
draw_layout_xl = normalize_x(layout_xl - padding * bin_size_x)
draw_layout_yl = normalize_y(layout_yl - padding * bin_size_y)
draw_layout_xh = normalize_x(layout_xh + padding * bin_size_x)
draw_layout_yh = normalize_y(layout_yh + padding * bin_size_y)
ctx.rectangle(draw_layout_xl, draw_layout_yl, draw_layout_xh,
draw_layout_yh)
ctx.fill()
ctx.set_line_width(line_width)
ctx.set_source_rgba(0.1, 0.1, 0.1, alpha=0.8)
ctx.move_to(normalize_x(xl), normalize_y(yl))
ctx.line_to(normalize_x(xl), normalize_y(yh))
ctx.line_to(normalize_x(xh), normalize_y(yh))
ctx.line_to(normalize_x(xh), normalize_y(yl))
ctx.close_path()
ctx.stroke()
## draw bins
#for i in range(1, num_bins_x):
# ctx.move_to(normalize_x(bin_xl(i)), normalize_y(yl))
# ctx.line_to(normalize_x(bin_xl(i)), normalize_y(yh))
# ctx.close_path()
# ctx.stroke()
#for i in range(1, num_bins_y):
# ctx.move_to(normalize_x(xl), normalize_y(bin_yl(i)))
# ctx.line_to(normalize_x(xh), normalize_y(bin_yl(i)))
# ctx.close_path()
# ctx.stroke()
# draw cells
ctx.set_font_size(16)
ctx.select_font_face("monospace", cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
node_xl = x
node_yl = layout_yl + layout_yh - (y + node_size_y[0:len(y)]
) # flip y
node_xh = node_xl + node_size_x[0:len(x)]
node_yh = layout_yl + layout_yh - y # flip y
node_xl = normalize_x(node_xl)
node_yl = normalize_y(node_yl)
node_xh = normalize_x(node_xh)
node_yh = normalize_y(node_yh)
ctx.set_line_width(line_width)
#print("plot layout")
# draw fixed macros
ctx.set_source_rgba(1, 0, 0, alpha=0.5)
for i in range(num_movable_nodes, num_physical_nodes):
ctx.rectangle(node_xl[i], node_yl[i], node_xh[i] - node_xl[i],
node_yh[i] -
node_yl[i]) # Rectangle(xl, yl, w, h)
ctx.fill()
ctx.set_source_rgba(0, 0, 0, alpha=1.0) # Solid color
for i in range(num_movable_nodes, num_physical_nodes):
draw_rect(node_xl[i], node_yl[i], node_xh[i], node_yh[i])
# draw fillers
if len(node_xl) > num_physical_nodes: # filler is included
ctx.set_line_width(line_width)
ctx.set_source_rgba(115 / 255.0,
115 / 255.0,
125 / 255.0,
alpha=0.5) # Solid color
for i in range(num_physical_nodes, num_nodes):
ctx.rectangle(node_xl[i], node_yl[i],
node_xh[i] - node_xl[i], node_yh[i] -
node_yl[i]) # Rectangle(xl, yl, w, h)
ctx.fill()
ctx.set_source_rgba(230 / 255.0,
230 / 255.0,
250 / 255.0,
alpha=0.3) # Solid color
for i in range(num_physical_nodes, num_nodes):
draw_rect(node_xl[i], node_yl[i], node_xh[i], node_yh[i])
# draw cells
ctx.set_line_width(line_width * 2)
ctx.set_source_rgba(0, 0, 1, alpha=0.5) # Solid color
for i in range(num_movable_nodes):
ctx.rectangle(node_xl[i], node_yl[i], node_xh[i] - node_xl[i],
node_yh[i] -
node_yl[i]) # Rectangle(xl, yl, w, h)
ctx.fill()
ctx.set_source_rgba(0, 0, 0.8, alpha=0.8) # Solid color
for i in range(num_movable_nodes):
draw_rect(node_xl[i], node_yl[i], node_xh[i], node_yh[i])
## draw cell indices
#for i in range(num_nodes):
# ctx.move_to((node_xl[i]+node_xh[i])/2, (node_yl[i]+node_yh[i])/2)
# ctx.show_text("%d" % (i))
# show iteration
if iteration:
ctx.set_source_rgb(0, 0, 0)
ctx.set_line_width(line_width * 10)
ctx.select_font_face("monospace", cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
ctx.set_font_size(32)
ctx.move_to(normalize_x((xl + xh) / 2),
normalize_y((yl + yh) / 2))
ctx.show_text('{:04}'.format(iteration))
surface.write_to_png(filename) # Output to PNG
print("[I] plotting to %s takes %.3f seconds" %
(filename, time.time() - tt))
except Exception as e:
print("[E] failed to plot")
print(str(e))
return 0
return 1 | [
"def",
"forward",
"(",
"pos",
",",
"node_size_x",
",",
"node_size_y",
",",
"pin_offset_x",
",",
"pin_offset_y",
",",
"pin2node_map",
",",
"xl",
",",
"yl",
",",
"xh",
",",
"yh",
",",
"site_width",
",",
"row_height",
",",
"bin_size_x",
",",
"bin_size_y",
",",
"num_movable_nodes",
",",
"num_filler_nodes",
",",
"filename",
",",
"iteration",
"=",
"None",
")",
":",
"num_nodes",
"=",
"len",
"(",
"pos",
")",
"//",
"2",
"num_movable_nodes",
"=",
"num_movable_nodes",
"num_filler_nodes",
"=",
"num_filler_nodes",
"num_physical_nodes",
"=",
"num_nodes",
"-",
"num_filler_nodes",
"num_bins_x",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"(",
"xh",
"-",
"xl",
")",
"/",
"bin_size_x",
")",
")",
"num_bins_y",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"(",
"yh",
"-",
"yl",
")",
"/",
"bin_size_y",
")",
")",
"x",
"=",
"np",
".",
"array",
"(",
"pos",
"[",
":",
"num_nodes",
"]",
")",
"y",
"=",
"np",
".",
"array",
"(",
"pos",
"[",
"num_nodes",
":",
"]",
")",
"node_size_x",
"=",
"np",
".",
"array",
"(",
"node_size_x",
")",
"node_size_y",
"=",
"np",
".",
"array",
"(",
"node_size_y",
")",
"pin_offset_x",
"=",
"np",
".",
"array",
"(",
"pin_offset_x",
")",
"pin_offset_y",
"=",
"np",
".",
"array",
"(",
"pin_offset_y",
")",
"pin2node_map",
"=",
"np",
".",
"array",
"(",
"pin2node_map",
")",
"try",
":",
"tt",
"=",
"time",
".",
"time",
"(",
")",
"if",
"xh",
"-",
"xl",
"<",
"yh",
"-",
"yl",
":",
"height",
"=",
"800",
"width",
"=",
"round",
"(",
"height",
"*",
"(",
"xh",
"-",
"xl",
")",
"/",
"(",
"yh",
"-",
"yl",
")",
")",
"else",
":",
"width",
"=",
"800",
"height",
"=",
"round",
"(",
"width",
"*",
"(",
"yh",
"-",
"yl",
")",
"/",
"(",
"xh",
"-",
"xl",
")",
")",
"line_width",
"=",
"0.1",
"padding",
"=",
"0",
"surface",
"=",
"cairo",
".",
"ImageSurface",
"(",
"cairo",
".",
"FORMAT_ARGB32",
",",
"width",
",",
"height",
")",
"ctx",
"=",
"cairo",
".",
"Context",
"(",
"surface",
")",
"# Do not use scale function.",
"# This is not compatible with show_text",
"if",
"num_movable_nodes",
"<",
"num_physical_nodes",
":",
"layout_xl",
"=",
"min",
"(",
"np",
".",
"amin",
"(",
"x",
"[",
"num_movable_nodes",
":",
"num_physical_nodes",
"]",
")",
",",
"xl",
")",
"layout_yl",
"=",
"min",
"(",
"np",
".",
"amin",
"(",
"y",
"[",
"num_movable_nodes",
":",
"num_physical_nodes",
"]",
")",
",",
"yl",
")",
"layout_xh",
"=",
"max",
"(",
"np",
".",
"amax",
"(",
"x",
"[",
"num_movable_nodes",
":",
"num_physical_nodes",
"]",
"+",
"node_size_x",
"[",
"num_movable_nodes",
":",
"num_physical_nodes",
"]",
")",
",",
"xh",
")",
"layout_yh",
"=",
"max",
"(",
"np",
".",
"amax",
"(",
"y",
"[",
"num_movable_nodes",
":",
"num_physical_nodes",
"]",
"+",
"node_size_y",
"[",
"num_movable_nodes",
":",
"num_physical_nodes",
"]",
")",
",",
"yh",
")",
"else",
":",
"layout_xl",
"=",
"xl",
"layout_yl",
"=",
"yl",
"layout_xh",
"=",
"xh",
"layout_yh",
"=",
"yh",
"def",
"bin_xl",
"(",
"id_x",
")",
":",
"\"\"\"\n @param id_x horizontal index \n @return bin xl\n \"\"\"",
"return",
"xl",
"+",
"id_x",
"*",
"bin_size_x",
"def",
"bin_xh",
"(",
"id_x",
")",
":",
"\"\"\"\n @param id_x horizontal index \n @return bin xh\n \"\"\"",
"return",
"min",
"(",
"bin_xl",
"(",
"id_x",
")",
"+",
"bin_size_x",
",",
"xh",
")",
"def",
"bin_yl",
"(",
"id_y",
")",
":",
"\"\"\"\n @param id_y vertical index \n @return bin yl\n \"\"\"",
"return",
"yl",
"+",
"id_y",
"*",
"bin_size_y",
"def",
"bin_yh",
"(",
"id_y",
")",
":",
"\"\"\"\n @param id_y vertical index \n @return bin yh\n \"\"\"",
"return",
"min",
"(",
"bin_yl",
"(",
"id_y",
")",
"+",
"bin_size_y",
",",
"yh",
")",
"def",
"normalize_x",
"(",
"xx",
")",
":",
"return",
"(",
"xx",
"-",
"(",
"layout_xl",
"-",
"padding",
"*",
"bin_size_x",
")",
")",
"/",
"(",
"layout_xh",
"-",
"layout_xl",
"+",
"padding",
"*",
"2",
"*",
"bin_size_x",
")",
"*",
"width",
"def",
"normalize_y",
"(",
"xx",
")",
":",
"return",
"(",
"xx",
"-",
"(",
"layout_yl",
"-",
"padding",
"*",
"bin_size_y",
")",
")",
"/",
"(",
"layout_yh",
"-",
"layout_yl",
"+",
"padding",
"*",
"2",
"*",
"bin_size_y",
")",
"*",
"height",
"def",
"draw_rect",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
":",
"ctx",
".",
"move_to",
"(",
"x1",
",",
"y1",
")",
"ctx",
".",
"line_to",
"(",
"x1",
",",
"y2",
")",
"ctx",
".",
"line_to",
"(",
"x2",
",",
"y2",
")",
"ctx",
".",
"line_to",
"(",
"x2",
",",
"y1",
")",
"ctx",
".",
"close_path",
"(",
")",
"ctx",
".",
"stroke",
"(",
")",
"# draw layout region",
"ctx",
".",
"set_source_rgb",
"(",
"1",
",",
"1",
",",
"1",
")",
"draw_layout_xl",
"=",
"normalize_x",
"(",
"layout_xl",
"-",
"padding",
"*",
"bin_size_x",
")",
"draw_layout_yl",
"=",
"normalize_y",
"(",
"layout_yl",
"-",
"padding",
"*",
"bin_size_y",
")",
"draw_layout_xh",
"=",
"normalize_x",
"(",
"layout_xh",
"+",
"padding",
"*",
"bin_size_x",
")",
"draw_layout_yh",
"=",
"normalize_y",
"(",
"layout_yh",
"+",
"padding",
"*",
"bin_size_y",
")",
"ctx",
".",
"rectangle",
"(",
"draw_layout_xl",
",",
"draw_layout_yl",
",",
"draw_layout_xh",
",",
"draw_layout_yh",
")",
"ctx",
".",
"fill",
"(",
")",
"ctx",
".",
"set_line_width",
"(",
"line_width",
")",
"ctx",
".",
"set_source_rgba",
"(",
"0.1",
",",
"0.1",
",",
"0.1",
",",
"alpha",
"=",
"0.8",
")",
"ctx",
".",
"move_to",
"(",
"normalize_x",
"(",
"xl",
")",
",",
"normalize_y",
"(",
"yl",
")",
")",
"ctx",
".",
"line_to",
"(",
"normalize_x",
"(",
"xl",
")",
",",
"normalize_y",
"(",
"yh",
")",
")",
"ctx",
".",
"line_to",
"(",
"normalize_x",
"(",
"xh",
")",
",",
"normalize_y",
"(",
"yh",
")",
")",
"ctx",
".",
"line_to",
"(",
"normalize_x",
"(",
"xh",
")",
",",
"normalize_y",
"(",
"yl",
")",
")",
"ctx",
".",
"close_path",
"(",
")",
"ctx",
".",
"stroke",
"(",
")",
"## draw bins",
"#for i in range(1, num_bins_x):",
"# ctx.move_to(normalize_x(bin_xl(i)), normalize_y(yl))",
"# ctx.line_to(normalize_x(bin_xl(i)), normalize_y(yh))",
"# ctx.close_path()",
"# ctx.stroke()",
"#for i in range(1, num_bins_y):",
"# ctx.move_to(normalize_x(xl), normalize_y(bin_yl(i)))",
"# ctx.line_to(normalize_x(xh), normalize_y(bin_yl(i)))",
"# ctx.close_path()",
"# ctx.stroke()",
"# draw cells",
"ctx",
".",
"set_font_size",
"(",
"16",
")",
"ctx",
".",
"select_font_face",
"(",
"\"monospace\"",
",",
"cairo",
".",
"FONT_SLANT_NORMAL",
",",
"cairo",
".",
"FONT_WEIGHT_NORMAL",
")",
"node_xl",
"=",
"x",
"node_yl",
"=",
"layout_yl",
"+",
"layout_yh",
"-",
"(",
"y",
"+",
"node_size_y",
"[",
"0",
":",
"len",
"(",
"y",
")",
"]",
")",
"# flip y",
"node_xh",
"=",
"node_xl",
"+",
"node_size_x",
"[",
"0",
":",
"len",
"(",
"x",
")",
"]",
"node_yh",
"=",
"layout_yl",
"+",
"layout_yh",
"-",
"y",
"# flip y",
"node_xl",
"=",
"normalize_x",
"(",
"node_xl",
")",
"node_yl",
"=",
"normalize_y",
"(",
"node_yl",
")",
"node_xh",
"=",
"normalize_x",
"(",
"node_xh",
")",
"node_yh",
"=",
"normalize_y",
"(",
"node_yh",
")",
"ctx",
".",
"set_line_width",
"(",
"line_width",
")",
"#print(\"plot layout\")",
"# draw fixed macros",
"ctx",
".",
"set_source_rgba",
"(",
"1",
",",
"0",
",",
"0",
",",
"alpha",
"=",
"0.5",
")",
"for",
"i",
"in",
"range",
"(",
"num_movable_nodes",
",",
"num_physical_nodes",
")",
":",
"ctx",
".",
"rectangle",
"(",
"node_xl",
"[",
"i",
"]",
",",
"node_yl",
"[",
"i",
"]",
",",
"node_xh",
"[",
"i",
"]",
"-",
"node_xl",
"[",
"i",
"]",
",",
"node_yh",
"[",
"i",
"]",
"-",
"node_yl",
"[",
"i",
"]",
")",
"# Rectangle(xl, yl, w, h)",
"ctx",
".",
"fill",
"(",
")",
"ctx",
".",
"set_source_rgba",
"(",
"0",
",",
"0",
",",
"0",
",",
"alpha",
"=",
"1.0",
")",
"# Solid color",
"for",
"i",
"in",
"range",
"(",
"num_movable_nodes",
",",
"num_physical_nodes",
")",
":",
"draw_rect",
"(",
"node_xl",
"[",
"i",
"]",
",",
"node_yl",
"[",
"i",
"]",
",",
"node_xh",
"[",
"i",
"]",
",",
"node_yh",
"[",
"i",
"]",
")",
"# draw fillers",
"if",
"len",
"(",
"node_xl",
")",
">",
"num_physical_nodes",
":",
"# filler is included",
"ctx",
".",
"set_line_width",
"(",
"line_width",
")",
"ctx",
".",
"set_source_rgba",
"(",
"115",
"/",
"255.0",
",",
"115",
"/",
"255.0",
",",
"125",
"/",
"255.0",
",",
"alpha",
"=",
"0.5",
")",
"# Solid color",
"for",
"i",
"in",
"range",
"(",
"num_physical_nodes",
",",
"num_nodes",
")",
":",
"ctx",
".",
"rectangle",
"(",
"node_xl",
"[",
"i",
"]",
",",
"node_yl",
"[",
"i",
"]",
",",
"node_xh",
"[",
"i",
"]",
"-",
"node_xl",
"[",
"i",
"]",
",",
"node_yh",
"[",
"i",
"]",
"-",
"node_yl",
"[",
"i",
"]",
")",
"# Rectangle(xl, yl, w, h)",
"ctx",
".",
"fill",
"(",
")",
"ctx",
".",
"set_source_rgba",
"(",
"230",
"/",
"255.0",
",",
"230",
"/",
"255.0",
",",
"250",
"/",
"255.0",
",",
"alpha",
"=",
"0.3",
")",
"# Solid color",
"for",
"i",
"in",
"range",
"(",
"num_physical_nodes",
",",
"num_nodes",
")",
":",
"draw_rect",
"(",
"node_xl",
"[",
"i",
"]",
",",
"node_yl",
"[",
"i",
"]",
",",
"node_xh",
"[",
"i",
"]",
",",
"node_yh",
"[",
"i",
"]",
")",
"# draw cells",
"ctx",
".",
"set_line_width",
"(",
"line_width",
"*",
"2",
")",
"ctx",
".",
"set_source_rgba",
"(",
"0",
",",
"0",
",",
"1",
",",
"alpha",
"=",
"0.5",
")",
"# Solid color",
"for",
"i",
"in",
"range",
"(",
"num_movable_nodes",
")",
":",
"ctx",
".",
"rectangle",
"(",
"node_xl",
"[",
"i",
"]",
",",
"node_yl",
"[",
"i",
"]",
",",
"node_xh",
"[",
"i",
"]",
"-",
"node_xl",
"[",
"i",
"]",
",",
"node_yh",
"[",
"i",
"]",
"-",
"node_yl",
"[",
"i",
"]",
")",
"# Rectangle(xl, yl, w, h)",
"ctx",
".",
"fill",
"(",
")",
"ctx",
".",
"set_source_rgba",
"(",
"0",
",",
"0",
",",
"0.8",
",",
"alpha",
"=",
"0.8",
")",
"# Solid color",
"for",
"i",
"in",
"range",
"(",
"num_movable_nodes",
")",
":",
"draw_rect",
"(",
"node_xl",
"[",
"i",
"]",
",",
"node_yl",
"[",
"i",
"]",
",",
"node_xh",
"[",
"i",
"]",
",",
"node_yh",
"[",
"i",
"]",
")",
"## draw cell indices",
"#for i in range(num_nodes):",
"# ctx.move_to((node_xl[i]+node_xh[i])/2, (node_yl[i]+node_yh[i])/2)",
"# ctx.show_text(\"%d\" % (i))",
"# show iteration",
"if",
"iteration",
":",
"ctx",
".",
"set_source_rgb",
"(",
"0",
",",
"0",
",",
"0",
")",
"ctx",
".",
"set_line_width",
"(",
"line_width",
"*",
"10",
")",
"ctx",
".",
"select_font_face",
"(",
"\"monospace\"",
",",
"cairo",
".",
"FONT_SLANT_NORMAL",
",",
"cairo",
".",
"FONT_WEIGHT_NORMAL",
")",
"ctx",
".",
"set_font_size",
"(",
"32",
")",
"ctx",
".",
"move_to",
"(",
"normalize_x",
"(",
"(",
"xl",
"+",
"xh",
")",
"/",
"2",
")",
",",
"normalize_y",
"(",
"(",
"yl",
"+",
"yh",
")",
"/",
"2",
")",
")",
"ctx",
".",
"show_text",
"(",
"'{:04}'",
".",
"format",
"(",
"iteration",
")",
")",
"surface",
".",
"write_to_png",
"(",
"filename",
")",
"# Output to PNG",
"print",
"(",
"\"[I] plotting to %s takes %.3f seconds\"",
"%",
"(",
"filename",
",",
"time",
".",
"time",
"(",
")",
"-",
"tt",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"[E] failed to plot\"",
")",
"print",
"(",
"str",
"(",
"e",
")",
")",
"return",
"0",
"return",
"1"
] | https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/ops/draw_place/PlaceDrawer.py#L21-L258 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | FlexGridSizer.RemoveGrowableCol | (*args, **kwargs) | return _core_.FlexGridSizer_RemoveGrowableCol(*args, **kwargs) | RemoveGrowableCol(self, size_t idx)
Specifies that column *idx* is no longer growable. | RemoveGrowableCol(self, size_t idx) | [
"RemoveGrowableCol",
"(",
"self",
"size_t",
"idx",
")"
] | def RemoveGrowableCol(*args, **kwargs):
"""
RemoveGrowableCol(self, size_t idx)
Specifies that column *idx* is no longer growable.
"""
return _core_.FlexGridSizer_RemoveGrowableCol(*args, **kwargs) | [
"def",
"RemoveGrowableCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"FlexGridSizer_RemoveGrowableCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L15374-L15380 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/dist.py | python | Distribution.get_command_obj | (self, command, create=1) | return cmd_obj | Return the command object for 'command'. Normally this object
is cached on a previous call to 'get_command_obj()'; if no command
object for 'command' is in the cache, then we either create and
return it (if 'create' is true) or return None. | Return the command object for 'command'. Normally this object
is cached on a previous call to 'get_command_obj()'; if no command
object for 'command' is in the cache, then we either create and
return it (if 'create' is true) or return None. | [
"Return",
"the",
"command",
"object",
"for",
"command",
".",
"Normally",
"this",
"object",
"is",
"cached",
"on",
"a",
"previous",
"call",
"to",
"get_command_obj",
"()",
";",
"if",
"no",
"command",
"object",
"for",
"command",
"is",
"in",
"the",
"cache",
"then",
"we",
"either",
"create",
"and",
"return",
"it",
"(",
"if",
"create",
"is",
"true",
")",
"or",
"return",
"None",
"."
] | def get_command_obj(self, command, create=1):
"""Return the command object for 'command'. Normally this object
is cached on a previous call to 'get_command_obj()'; if no command
object for 'command' is in the cache, then we either create and
return it (if 'create' is true) or return None.
"""
cmd_obj = self.command_obj.get(command)
if not cmd_obj and create:
if DEBUG:
self.announce("Distribution.get_command_obj(): " \
"creating '%s' command object" % command)
klass = self.get_command_class(command)
cmd_obj = self.command_obj[command] = klass(self)
self.have_run[command] = 0
# Set any options that were supplied in config files
# or on the command line. (NB. support for error
# reporting is lame here: any errors aren't reported
# until 'finalize_options()' is called, which means
# we won't report the source of the error.)
options = self.command_options.get(command)
if options:
self._set_command_options(cmd_obj, options)
return cmd_obj | [
"def",
"get_command_obj",
"(",
"self",
",",
"command",
",",
"create",
"=",
"1",
")",
":",
"cmd_obj",
"=",
"self",
".",
"command_obj",
".",
"get",
"(",
"command",
")",
"if",
"not",
"cmd_obj",
"and",
"create",
":",
"if",
"DEBUG",
":",
"self",
".",
"announce",
"(",
"\"Distribution.get_command_obj(): \"",
"\"creating '%s' command object\"",
"%",
"command",
")",
"klass",
"=",
"self",
".",
"get_command_class",
"(",
"command",
")",
"cmd_obj",
"=",
"self",
".",
"command_obj",
"[",
"command",
"]",
"=",
"klass",
"(",
"self",
")",
"self",
".",
"have_run",
"[",
"command",
"]",
"=",
"0",
"# Set any options that were supplied in config files",
"# or on the command line. (NB. support for error",
"# reporting is lame here: any errors aren't reported",
"# until 'finalize_options()' is called, which means",
"# we won't report the source of the error.)",
"options",
"=",
"self",
".",
"command_options",
".",
"get",
"(",
"command",
")",
"if",
"options",
":",
"self",
".",
"_set_command_options",
"(",
"cmd_obj",
",",
"options",
")",
"return",
"cmd_obj"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/dist.py#L833-L858 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/back/remove_last_softmax_pattern.py | python | RemoveLastSoftMaxPattern.replace_pattern | (graph: Graph, match: dict) | Removes output SoftMax layer
:param graph: graph to operate on
:param match: dictionary with matched nodes | Removes output SoftMax layer
:param graph: graph to operate on
:param match: dictionary with matched nodes | [
"Removes",
"output",
"SoftMax",
"layer",
":",
"param",
"graph",
":",
"graph",
"to",
"operate",
"on",
":",
"param",
"match",
":",
"dictionary",
"with",
"matched",
"nodes"
] | def replace_pattern(graph: Graph, match: dict):
"""
Removes output SoftMax layer
:param graph: graph to operate on
:param match: dictionary with matched nodes
"""
if len(match['softmax_data'].out_nodes()) == 1:
remove_op_node_with_data_node(graph, match['softmax_node'])
else:
log.error("SoftMax is not last layer, so can't be removed", extra={'is_warning': True}) | [
"def",
"replace_pattern",
"(",
"graph",
":",
"Graph",
",",
"match",
":",
"dict",
")",
":",
"if",
"len",
"(",
"match",
"[",
"'softmax_data'",
"]",
".",
"out_nodes",
"(",
")",
")",
"==",
"1",
":",
"remove_op_node_with_data_node",
"(",
"graph",
",",
"match",
"[",
"'softmax_node'",
"]",
")",
"else",
":",
"log",
".",
"error",
"(",
"\"SoftMax is not last layer, so can't be removed\"",
",",
"extra",
"=",
"{",
"'is_warning'",
":",
"True",
"}",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/back/remove_last_softmax_pattern.py#L31-L40 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/fps/connection.py | python | FPSConnection.refund | (self, action, response, **kw) | return self.get_object(action, kw, response) | Refunds a previously completed transaction. | Refunds a previously completed transaction. | [
"Refunds",
"a",
"previously",
"completed",
"transaction",
"."
] | def refund(self, action, response, **kw):
"""
Refunds a previously completed transaction.
"""
return self.get_object(action, kw, response) | [
"def",
"refund",
"(",
"self",
",",
"action",
",",
"response",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"get_object",
"(",
"action",
",",
"kw",
",",
"response",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/fps/connection.py#L273-L277 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/graph_editor/transform.py | python | transform_tensor_into_placeholder_handler | (info, t) | return t_ | Transform a tensor into a placeholder tensor.
This handler is typically used to transform a subgraph input tensor into a
placeholder.
Args:
info: Transform._Info instance.
t: tensor whose input must be transformed into a place holder.
Returns:
The tensor generated by the newly created place holder. | Transform a tensor into a placeholder tensor. | [
"Transform",
"a",
"tensor",
"into",
"a",
"placeholder",
"tensor",
"."
] | def transform_tensor_into_placeholder_handler(info, t):
"""Transform a tensor into a placeholder tensor.
This handler is typically used to transform a subgraph input tensor into a
placeholder.
Args:
info: Transform._Info instance.
t: tensor whose input must be transformed into a place holder.
Returns:
The tensor generated by the newly created place holder.
"""
with info.graph_.as_default():
t_ = util.make_placeholder_from_tensor(t, scope=info.scope_)
return t_ | [
"def",
"transform_tensor_into_placeholder_handler",
"(",
"info",
",",
"t",
")",
":",
"with",
"info",
".",
"graph_",
".",
"as_default",
"(",
")",
":",
"t_",
"=",
"util",
".",
"make_placeholder_from_tensor",
"(",
"t",
",",
"scope",
"=",
"info",
".",
"scope_",
")",
"return",
"t_"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/transform.py#L34-L48 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Canvas.find_above | (self, tagOrId) | return self.find('above', tagOrId) | Return items above TAGORID. | Return items above TAGORID. | [
"Return",
"items",
"above",
"TAGORID",
"."
] | def find_above(self, tagOrId):
"""Return items above TAGORID."""
return self.find('above', tagOrId) | [
"def",
"find_above",
"(",
"self",
",",
"tagOrId",
")",
":",
"return",
"self",
".",
"find",
"(",
"'above'",
",",
"tagOrId",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2294-L2296 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/opset1/ops.py | python | relu | (node: NodeInput, name: Optional[str] = None) | return _get_node_factory_opset1().create("Relu", [node]) | Perform rectified linear unit operation on input node element-wise.
:param node: One of: input node, array or scalar.
:param name: The optional output node name.
:return: The new node performing relu operation on its input element-wise. | Perform rectified linear unit operation on input node element-wise. | [
"Perform",
"rectified",
"linear",
"unit",
"operation",
"on",
"input",
"node",
"element",
"-",
"wise",
"."
] | def relu(node: NodeInput, name: Optional[str] = None) -> Node:
"""Perform rectified linear unit operation on input node element-wise.
:param node: One of: input node, array or scalar.
:param name: The optional output node name.
:return: The new node performing relu operation on its input element-wise.
"""
return _get_node_factory_opset1().create("Relu", [node]) | [
"def",
"relu",
"(",
"node",
":",
"NodeInput",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Node",
":",
"return",
"_get_node_factory_opset1",
"(",
")",
".",
"create",
"(",
"\"Relu\"",
",",
"[",
"node",
"]",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset1/ops.py#L2247-L2254 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/difflib.py | python | SequenceMatcher.set_seq2 | (self, b) | Set the second sequence to be compared.
The first sequence to be compared is not changed.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.set_seq2("abcd")
>>> s.ratio()
1.0
>>>
SequenceMatcher computes and caches detailed information about the
second sequence, so if you want to compare one sequence S against
many sequences, use .set_seq2(S) once and call .set_seq1(x)
repeatedly for each of the other sequences.
See also set_seqs() and set_seq1(). | Set the second sequence to be compared. | [
"Set",
"the",
"second",
"sequence",
"to",
"be",
"compared",
"."
] | def set_seq2(self, b):
"""Set the second sequence to be compared.
The first sequence to be compared is not changed.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.set_seq2("abcd")
>>> s.ratio()
1.0
>>>
SequenceMatcher computes and caches detailed information about the
second sequence, so if you want to compare one sequence S against
many sequences, use .set_seq2(S) once and call .set_seq1(x)
repeatedly for each of the other sequences.
See also set_seqs() and set_seq1().
"""
if b is self.b:
return
self.b = b
self.matching_blocks = self.opcodes = None
self.fullbcount = None
self.__chain_b() | [
"def",
"set_seq2",
"(",
"self",
",",
"b",
")",
":",
"if",
"b",
"is",
"self",
".",
"b",
":",
"return",
"self",
".",
"b",
"=",
"b",
"self",
".",
"matching_blocks",
"=",
"self",
".",
"opcodes",
"=",
"None",
"self",
".",
"fullbcount",
"=",
"None",
"self",
".",
"__chain_b",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/difflib.py#L253-L279 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextCtrl.MoveHome | (*args, **kwargs) | return _richtext.RichTextCtrl_MoveHome(*args, **kwargs) | MoveHome(self, int flags=0) -> bool
Move to the start of the buffer | MoveHome(self, int flags=0) -> bool | [
"MoveHome",
"(",
"self",
"int",
"flags",
"=",
"0",
")",
"-",
">",
"bool"
] | def MoveHome(*args, **kwargs):
"""
MoveHome(self, int flags=0) -> bool
Move to the start of the buffer
"""
return _richtext.RichTextCtrl_MoveHome(*args, **kwargs) | [
"def",
"MoveHome",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_MoveHome",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3784-L3790 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/algorithm_detail/calculate_sans_transmission.py | python | _get_corrected_wavelength_workspace | (workspace, wav_range, detector_ids, calculate_transmission_state, data_type) | return group_ws.getItem(0) | Performs a prompt peak correction, a background correction, converts to wavelength and rebins.
:param workspace: the workspace which is being corrected.
:param wav_range: the wavelength corresponding to this run
:param detector_ids: a list of relevant detector ids
:param calculate_transmission_state: a SANSStateCalculateTransmission state
:param data_type The component of the instrument which is to be reduced
:return: a corrected workspace. | Performs a prompt peak correction, a background correction, converts to wavelength and rebins. | [
"Performs",
"a",
"prompt",
"peak",
"correction",
"a",
"background",
"correction",
"converts",
"to",
"wavelength",
"and",
"rebins",
"."
] | def _get_corrected_wavelength_workspace(workspace, wav_range, detector_ids, calculate_transmission_state, data_type):
"""
Performs a prompt peak correction, a background correction, converts to wavelength and rebins.
:param workspace: the workspace which is being corrected.
:param wav_range: the wavelength corresponding to this run
:param detector_ids: a list of relevant detector ids
:param calculate_transmission_state: a SANSStateCalculateTransmission state
:param data_type The component of the instrument which is to be reduced
:return: a corrected workspace.
"""
# Extract the relevant spectra. These include
# 1. The incident monitor spectrum
# 2. The transmission spectra, be it monitor or ROI based.
# A previous implementation of this code had a comment which suggested
# that we have to exclude unused spectra as the interpolation runs into
# problems if we don't.
extract_name = "ExtractSpectra"
extract_options = {"InputWorkspace": workspace,
"OutputWorkspace": EMPTY_NAME,
"DetectorList": detector_ids}
extract_alg = create_unmanaged_algorithm(extract_name, **extract_options)
extract_alg.execute()
workspace = extract_alg.getProperty("OutputWorkspace").value
# Make sure that we still have spectra in the workspace
if workspace.getNumberHistograms() == 0:
raise RuntimeError("SANSCalculateTransmissionCorrection: The transmission workspace does "
"not seem to have any spectra.")
# ----------------------------------
# Perform the prompt peak correction
# ----------------------------------
prompt_peak_correction_min = calculate_transmission_state.prompt_peak_correction_min
prompt_peak_correction_max = calculate_transmission_state.prompt_peak_correction_max
prompt_peak_correction_enabled = calculate_transmission_state.prompt_peak_correction_enabled
workspace = _perform_prompt_peak_correction(workspace, prompt_peak_correction_min,
prompt_peak_correction_max, prompt_peak_correction_enabled)
# ---------------------------------------
# Perform the flat background correction
# ---------------------------------------
# The flat background correction has two parts:
# 1. Corrections on monitors
# 2. Corrections on regular detectors
# Monitor flat background correction
workspace_indices_of_monitors = list(get_workspace_indices_for_monitors(workspace))
background_tof_monitor_start = calculate_transmission_state.background_TOF_monitor_start
background_tof_monitor_stop = calculate_transmission_state.background_TOF_monitor_stop
background_tof_general_start = calculate_transmission_state.background_TOF_general_start
background_tof_general_stop = calculate_transmission_state.background_TOF_general_stop
workspace = apply_flat_background_correction_to_monitors(workspace,
workspace_indices_of_monitors,
background_tof_monitor_start,
background_tof_monitor_stop,
background_tof_general_start,
background_tof_general_stop)
# Detector flat background correction
flat_background_correction_start = calculate_transmission_state.background_TOF_roi_start
flat_background_correction_stop = calculate_transmission_state.background_TOF_roi_stop
workspace = apply_flat_background_correction_to_detectors(workspace, flat_background_correction_start,
flat_background_correction_stop)
# ---------------------------------------
# Convert to wavelength and rebin
# ---------------------------------------
# The wavelength setting is reasonably complex.
# 1. Use full wavelength range
# 2. Use standard settings
if calculate_transmission_state.use_full_wavelength_range:
wavelength_low = calculate_transmission_state.wavelength_full_range_low
wavelength_high = calculate_transmission_state.wavelength_full_range_high
else:
fit_state = calculate_transmission_state.fit[data_type.value]
wavelength_low = fit_state.wavelength_low if fit_state.wavelength_low else wav_range[0]
wavelength_high = fit_state.wavelength_high if fit_state.wavelength_high else wav_range[1]
wavelength_step = calculate_transmission_state.wavelength_interval.wavelength_step
rebin_type = calculate_transmission_state.rebin_type
wavelength_step_type = calculate_transmission_state.wavelength_step_type_lin_log
convert_name = "SANSConvertToWavelengthAndRebin"
convert_options = {"InputWorkspace": workspace,
"WavelengthPairs": json.dumps([(wavelength_low, wavelength_high)]),
"WavelengthStep": wavelength_step,
"WavelengthStepType": wavelength_step_type.value,
"RebinMode": rebin_type.value}
convert_alg = create_unmanaged_algorithm(convert_name, **convert_options)
convert_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
convert_alg.setProperty("OutputWorkspace", workspace)
convert_alg.execute()
group_ws = convert_alg.getProperty("OutputWorkspace").value
return group_ws.getItem(0) | [
"def",
"_get_corrected_wavelength_workspace",
"(",
"workspace",
",",
"wav_range",
",",
"detector_ids",
",",
"calculate_transmission_state",
",",
"data_type",
")",
":",
"# Extract the relevant spectra. These include",
"# 1. The incident monitor spectrum",
"# 2. The transmission spectra, be it monitor or ROI based.",
"# A previous implementation of this code had a comment which suggested",
"# that we have to exclude unused spectra as the interpolation runs into",
"# problems if we don't.",
"extract_name",
"=",
"\"ExtractSpectra\"",
"extract_options",
"=",
"{",
"\"InputWorkspace\"",
":",
"workspace",
",",
"\"OutputWorkspace\"",
":",
"EMPTY_NAME",
",",
"\"DetectorList\"",
":",
"detector_ids",
"}",
"extract_alg",
"=",
"create_unmanaged_algorithm",
"(",
"extract_name",
",",
"*",
"*",
"extract_options",
")",
"extract_alg",
".",
"execute",
"(",
")",
"workspace",
"=",
"extract_alg",
".",
"getProperty",
"(",
"\"OutputWorkspace\"",
")",
".",
"value",
"# Make sure that we still have spectra in the workspace",
"if",
"workspace",
".",
"getNumberHistograms",
"(",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"SANSCalculateTransmissionCorrection: The transmission workspace does \"",
"\"not seem to have any spectra.\"",
")",
"# ----------------------------------",
"# Perform the prompt peak correction",
"# ----------------------------------",
"prompt_peak_correction_min",
"=",
"calculate_transmission_state",
".",
"prompt_peak_correction_min",
"prompt_peak_correction_max",
"=",
"calculate_transmission_state",
".",
"prompt_peak_correction_max",
"prompt_peak_correction_enabled",
"=",
"calculate_transmission_state",
".",
"prompt_peak_correction_enabled",
"workspace",
"=",
"_perform_prompt_peak_correction",
"(",
"workspace",
",",
"prompt_peak_correction_min",
",",
"prompt_peak_correction_max",
",",
"prompt_peak_correction_enabled",
")",
"# ---------------------------------------",
"# Perform the flat background correction",
"# ---------------------------------------",
"# The flat background correction has two parts:",
"# 1. Corrections on monitors",
"# 2. Corrections on regular detectors",
"# Monitor flat background correction",
"workspace_indices_of_monitors",
"=",
"list",
"(",
"get_workspace_indices_for_monitors",
"(",
"workspace",
")",
")",
"background_tof_monitor_start",
"=",
"calculate_transmission_state",
".",
"background_TOF_monitor_start",
"background_tof_monitor_stop",
"=",
"calculate_transmission_state",
".",
"background_TOF_monitor_stop",
"background_tof_general_start",
"=",
"calculate_transmission_state",
".",
"background_TOF_general_start",
"background_tof_general_stop",
"=",
"calculate_transmission_state",
".",
"background_TOF_general_stop",
"workspace",
"=",
"apply_flat_background_correction_to_monitors",
"(",
"workspace",
",",
"workspace_indices_of_monitors",
",",
"background_tof_monitor_start",
",",
"background_tof_monitor_stop",
",",
"background_tof_general_start",
",",
"background_tof_general_stop",
")",
"# Detector flat background correction",
"flat_background_correction_start",
"=",
"calculate_transmission_state",
".",
"background_TOF_roi_start",
"flat_background_correction_stop",
"=",
"calculate_transmission_state",
".",
"background_TOF_roi_stop",
"workspace",
"=",
"apply_flat_background_correction_to_detectors",
"(",
"workspace",
",",
"flat_background_correction_start",
",",
"flat_background_correction_stop",
")",
"# ---------------------------------------",
"# Convert to wavelength and rebin",
"# ---------------------------------------",
"# The wavelength setting is reasonably complex.",
"# 1. Use full wavelength range",
"# 2. Use standard settings",
"if",
"calculate_transmission_state",
".",
"use_full_wavelength_range",
":",
"wavelength_low",
"=",
"calculate_transmission_state",
".",
"wavelength_full_range_low",
"wavelength_high",
"=",
"calculate_transmission_state",
".",
"wavelength_full_range_high",
"else",
":",
"fit_state",
"=",
"calculate_transmission_state",
".",
"fit",
"[",
"data_type",
".",
"value",
"]",
"wavelength_low",
"=",
"fit_state",
".",
"wavelength_low",
"if",
"fit_state",
".",
"wavelength_low",
"else",
"wav_range",
"[",
"0",
"]",
"wavelength_high",
"=",
"fit_state",
".",
"wavelength_high",
"if",
"fit_state",
".",
"wavelength_high",
"else",
"wav_range",
"[",
"1",
"]",
"wavelength_step",
"=",
"calculate_transmission_state",
".",
"wavelength_interval",
".",
"wavelength_step",
"rebin_type",
"=",
"calculate_transmission_state",
".",
"rebin_type",
"wavelength_step_type",
"=",
"calculate_transmission_state",
".",
"wavelength_step_type_lin_log",
"convert_name",
"=",
"\"SANSConvertToWavelengthAndRebin\"",
"convert_options",
"=",
"{",
"\"InputWorkspace\"",
":",
"workspace",
",",
"\"WavelengthPairs\"",
":",
"json",
".",
"dumps",
"(",
"[",
"(",
"wavelength_low",
",",
"wavelength_high",
")",
"]",
")",
",",
"\"WavelengthStep\"",
":",
"wavelength_step",
",",
"\"WavelengthStepType\"",
":",
"wavelength_step_type",
".",
"value",
",",
"\"RebinMode\"",
":",
"rebin_type",
".",
"value",
"}",
"convert_alg",
"=",
"create_unmanaged_algorithm",
"(",
"convert_name",
",",
"*",
"*",
"convert_options",
")",
"convert_alg",
".",
"setPropertyValue",
"(",
"\"OutputWorkspace\"",
",",
"EMPTY_NAME",
")",
"convert_alg",
".",
"setProperty",
"(",
"\"OutputWorkspace\"",
",",
"workspace",
")",
"convert_alg",
".",
"execute",
"(",
")",
"group_ws",
"=",
"convert_alg",
".",
"getProperty",
"(",
"\"OutputWorkspace\"",
")",
".",
"value",
"return",
"group_ws",
".",
"getItem",
"(",
"0",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/calculate_sans_transmission.py#L179-L273 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Ctc.py | python | CtcLoss.skip | (self, value) | Specifies if blank labels may be skipped when aligning. | Specifies if blank labels may be skipped when aligning. | [
"Specifies",
"if",
"blank",
"labels",
"may",
"be",
"skipped",
"when",
"aligning",
"."
] | def skip(self, value):
"""Specifies if blank labels may be skipped when aligning.
"""
self._internal.set_skip(bool(value)) | [
"def",
"skip",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_internal",
".",
"set_skip",
"(",
"bool",
"(",
"value",
")",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Ctc.py#L146-L149 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/wsgiref/headers.py | python | Headers.__delitem__ | (self,name) | Delete all occurrences of a header, if present.
Does *not* raise an exception if the header is missing. | Delete all occurrences of a header, if present. | [
"Delete",
"all",
"occurrences",
"of",
"a",
"header",
"if",
"present",
"."
] | def __delitem__(self,name):
"""Delete all occurrences of a header, if present.
Does *not* raise an exception if the header is missing.
"""
name = name.lower()
self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name] | [
"def",
"__delitem__",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"self",
".",
"_headers",
"[",
":",
"]",
"=",
"[",
"kv",
"for",
"kv",
"in",
"self",
".",
"_headers",
"if",
"kv",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"name",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/wsgiref/headers.py#L48-L54 | ||
llvm-dcpu16/llvm-dcpu16 | ae6b01fecd03219677e391d4421df5d966d80dcf | bindings/python/llvm/object.py | python | Symbol.expire | (self) | Mark the object as expired to prevent future API accesses.
This is called internally by this module and it is unlikely that
external callers have a legitimate reason for using it. | Mark the object as expired to prevent future API accesses. | [
"Mark",
"the",
"object",
"as",
"expired",
"to",
"prevent",
"future",
"API",
"accesses",
"."
] | def expire(self):
"""Mark the object as expired to prevent future API accesses.
This is called internally by this module and it is unlikely that
external callers have a legitimate reason for using it.
"""
self.expired = True | [
"def",
"expire",
"(",
"self",
")",
":",
"self",
".",
"expired",
"=",
"True"
] | https://github.com/llvm-dcpu16/llvm-dcpu16/blob/ae6b01fecd03219677e391d4421df5d966d80dcf/bindings/python/llvm/object.py#L351-L357 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py | python | Minitaur._GetDelayedObservation | (self, latency) | return observation | Get observation that is delayed by the amount specified in latency.
Args:
latency: The latency (in seconds) of the delayed observation.
Returns:
observation: The observation which was actually latency seconds ago. | Get observation that is delayed by the amount specified in latency. | [
"Get",
"observation",
"that",
"is",
"delayed",
"by",
"the",
"amount",
"specified",
"in",
"latency",
"."
] | def _GetDelayedObservation(self, latency):
"""Get observation that is delayed by the amount specified in latency.
Args:
latency: The latency (in seconds) of the delayed observation.
Returns:
observation: The observation which was actually latency seconds ago.
"""
if latency <= 0 or len(self._observation_history) == 1:
observation = self._observation_history[0]
else:
n_steps_ago = int(latency / self.time_step)
if n_steps_ago + 1 >= len(self._observation_history):
return self._observation_history[-1]
remaining_latency = latency - n_steps_ago * self.time_step
blend_alpha = remaining_latency / self.time_step
observation = ((1.0 - blend_alpha) * np.array(self._observation_history[n_steps_ago]) +
blend_alpha * np.array(self._observation_history[n_steps_ago + 1]))
return observation | [
"def",
"_GetDelayedObservation",
"(",
"self",
",",
"latency",
")",
":",
"if",
"latency",
"<=",
"0",
"or",
"len",
"(",
"self",
".",
"_observation_history",
")",
"==",
"1",
":",
"observation",
"=",
"self",
".",
"_observation_history",
"[",
"0",
"]",
"else",
":",
"n_steps_ago",
"=",
"int",
"(",
"latency",
"/",
"self",
".",
"time_step",
")",
"if",
"n_steps_ago",
"+",
"1",
">=",
"len",
"(",
"self",
".",
"_observation_history",
")",
":",
"return",
"self",
".",
"_observation_history",
"[",
"-",
"1",
"]",
"remaining_latency",
"=",
"latency",
"-",
"n_steps_ago",
"*",
"self",
".",
"time_step",
"blend_alpha",
"=",
"remaining_latency",
"/",
"self",
".",
"time_step",
"observation",
"=",
"(",
"(",
"1.0",
"-",
"blend_alpha",
")",
"*",
"np",
".",
"array",
"(",
"self",
".",
"_observation_history",
"[",
"n_steps_ago",
"]",
")",
"+",
"blend_alpha",
"*",
"np",
".",
"array",
"(",
"self",
".",
"_observation_history",
"[",
"n_steps_ago",
"+",
"1",
"]",
")",
")",
"return",
"observation"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py#L848-L866 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Wrapping/Generators/Python/itk/support/extras.py | python | templated_class.__getitem__ | (self, template_parameters) | return templated_class.__templated_class_and_parameters__(
self, template_parameters
) | Return a pair class-template parameters ready to be instantiated.
The template parameters may be validated if the custom class provide
the static method check_template_parameters(parameters). | Return a pair class-template parameters ready to be instantiated. | [
"Return",
"a",
"pair",
"class",
"-",
"template",
"parameters",
"ready",
"to",
"be",
"instantiated",
"."
] | def __getitem__(self, template_parameters):
"""Return a pair class-template parameters ready to be instantiated.
The template parameters may be validated if the custom class provide
the static method check_template_parameters(parameters).
"""
if not isinstance(template_parameters, tuple):
template_parameters = (template_parameters,)
return templated_class.__templated_class_and_parameters__(
self, template_parameters
) | [
"def",
"__getitem__",
"(",
"self",
",",
"template_parameters",
")",
":",
"if",
"not",
"isinstance",
"(",
"template_parameters",
",",
"tuple",
")",
":",
"template_parameters",
"=",
"(",
"template_parameters",
",",
")",
"return",
"templated_class",
".",
"__templated_class_and_parameters__",
"(",
"self",
",",
"template_parameters",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Wrapping/Generators/Python/itk/support/extras.py#L1354-L1364 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/PyShell.py | python | ModifiedInterpreter.open_remote_stack_viewer | (self) | return | Initiate the remote stack viewer from a separate thread.
This method is called from the subprocess, and by returning from this
method we allow the subprocess to unblock. After a bit the shell
requests the subprocess to open the remote stack viewer which returns a
static object looking at the last exception. It is queried through
the RPC mechanism. | Initiate the remote stack viewer from a separate thread. | [
"Initiate",
"the",
"remote",
"stack",
"viewer",
"from",
"a",
"separate",
"thread",
"."
] | def open_remote_stack_viewer(self):
"""Initiate the remote stack viewer from a separate thread.
This method is called from the subprocess, and by returning from this
method we allow the subprocess to unblock. After a bit the shell
requests the subprocess to open the remote stack viewer which returns a
static object looking at the last exception. It is queried through
the RPC mechanism.
"""
self.tkconsole.text.after(300, self.remote_stack_viewer)
return | [
"def",
"open_remote_stack_viewer",
"(",
"self",
")",
":",
"self",
".",
"tkconsole",
".",
"text",
".",
"after",
"(",
"300",
",",
"self",
".",
"remote_stack_viewer",
")",
"return"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/PyShell.py#L612-L623 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/tempfile.py | python | gettempprefixb | () | return _os.fsencode(gettempprefix()) | The default prefix for temporary directories as bytes. | The default prefix for temporary directories as bytes. | [
"The",
"default",
"prefix",
"for",
"temporary",
"directories",
"as",
"bytes",
"."
] | def gettempprefixb():
"""The default prefix for temporary directories as bytes."""
return _os.fsencode(gettempprefix()) | [
"def",
"gettempprefixb",
"(",
")",
":",
"return",
"_os",
".",
"fsencode",
"(",
"gettempprefix",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/tempfile.py#L278-L280 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/skia/bench/gen_bench_expectations.py | python | main | () | Reads bench data points, then calculate and export expectations. | Reads bench data points, then calculate and export expectations. | [
"Reads",
"bench",
"data",
"points",
"then",
"calculate",
"and",
"export",
"expectations",
"."
] | def main():
"""Reads bench data points, then calculate and export expectations.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-a', '--representation_alg', default='25th',
help='bench representation algorithm to use, see bench_util.py.')
parser.add_argument(
'-b', '--builder', required=True,
help='name of the builder whose bench ranges we are computing.')
parser.add_argument(
'-d', '--input_dir', required=True,
help='a directory containing bench data files.')
parser.add_argument(
'-o', '--output_file', required=True,
help='file path and name for storing the output bench expectations.')
parser.add_argument(
'-r', '--git_revision', required=True,
help='the git hash to indicate the revision of input data to use.')
parser.add_argument(
'-t', '--back_track', required=False, default=10,
help='the number of commit hashes backwards to look to include' +
'in the calculations.')
parser.add_argument(
'-m', '--max_commits', required=False, default=1,
help='the number of commit hashes to include in the calculations.')
args = parser.parse_args()
builder = args.builder
data_points = bench_util.parse_skp_bench_data(
args.input_dir, args.git_revision, args.representation_alg)
parent_commits = get_parent_commits(args.git_revision, args.back_track)
print "Using commits: {}".format(parent_commits)
suffixes = get_file_suffixes(args.git_revision, args.input_dir)
print "Using suffixes: {}".format(suffixes)
# TODO(kelvinly): Find a better approach to than directly copying from
# the GS server?
downloaded_commits = []
for idx, commit in enumerate(parent_commits):
num_downloaded = download_bench_data(
builder, commit, suffixes, args.input_dir)
if num_downloaded > 0:
downloaded_commits.append((num_downloaded, idx, commit))
if len(downloaded_commits) < args.max_commits:
print ('Less than desired number of commits found. Please increase'
'--back_track in later runs')
trunc_commits = sorted(downloaded_commits, reverse=True)[:args.max_commits]
extra_data = []
for _, idx, commit in trunc_commits:
extra_data.append((idx, bench_util.parse_skp_bench_data(
args.input_dir, commit, args.representation_alg)))
expectations_dict = create_expectations_dict(data_points, builder,
extra_data)
out_lines = []
keys = expectations_dict.keys()
keys.sort()
for (config, bench) in keys:
(expected, lower_bound, upper_bound) = expectations_dict[(config, bench)]
out_lines.append('%(bench)s_%(config)s_,%(builder)s-%(representation)s,'
'%(expected)s,%(lower_bound)s,%(upper_bound)s' % {
'bench': bench,
'config': config,
'builder': builder,
'representation': args.representation_alg,
'expected': expected,
'lower_bound': lower_bound,
'upper_bound': upper_bound})
with open(args.output_file, 'w') as file_handle:
file_handle.write('\n'.join(out_lines)) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"'--representation_alg'",
",",
"default",
"=",
"'25th'",
",",
"help",
"=",
"'bench representation algorithm to use, see bench_util.py.'",
")",
"parser",
".",
"add_argument",
"(",
"'-b'",
",",
"'--builder'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'name of the builder whose bench ranges we are computing.'",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--input_dir'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'a directory containing bench data files.'",
")",
"parser",
".",
"add_argument",
"(",
"'-o'",
",",
"'--output_file'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'file path and name for storing the output bench expectations.'",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--git_revision'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'the git hash to indicate the revision of input data to use.'",
")",
"parser",
".",
"add_argument",
"(",
"'-t'",
",",
"'--back_track'",
",",
"required",
"=",
"False",
",",
"default",
"=",
"10",
",",
"help",
"=",
"'the number of commit hashes backwards to look to include'",
"+",
"'in the calculations.'",
")",
"parser",
".",
"add_argument",
"(",
"'-m'",
",",
"'--max_commits'",
",",
"required",
"=",
"False",
",",
"default",
"=",
"1",
",",
"help",
"=",
"'the number of commit hashes to include in the calculations.'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"builder",
"=",
"args",
".",
"builder",
"data_points",
"=",
"bench_util",
".",
"parse_skp_bench_data",
"(",
"args",
".",
"input_dir",
",",
"args",
".",
"git_revision",
",",
"args",
".",
"representation_alg",
")",
"parent_commits",
"=",
"get_parent_commits",
"(",
"args",
".",
"git_revision",
",",
"args",
".",
"back_track",
")",
"print",
"\"Using commits: {}\"",
".",
"format",
"(",
"parent_commits",
")",
"suffixes",
"=",
"get_file_suffixes",
"(",
"args",
".",
"git_revision",
",",
"args",
".",
"input_dir",
")",
"print",
"\"Using suffixes: {}\"",
".",
"format",
"(",
"suffixes",
")",
"# TODO(kelvinly): Find a better approach to than directly copying from",
"# the GS server?",
"downloaded_commits",
"=",
"[",
"]",
"for",
"idx",
",",
"commit",
"in",
"enumerate",
"(",
"parent_commits",
")",
":",
"num_downloaded",
"=",
"download_bench_data",
"(",
"builder",
",",
"commit",
",",
"suffixes",
",",
"args",
".",
"input_dir",
")",
"if",
"num_downloaded",
">",
"0",
":",
"downloaded_commits",
".",
"append",
"(",
"(",
"num_downloaded",
",",
"idx",
",",
"commit",
")",
")",
"if",
"len",
"(",
"downloaded_commits",
")",
"<",
"args",
".",
"max_commits",
":",
"print",
"(",
"'Less than desired number of commits found. Please increase'",
"'--back_track in later runs'",
")",
"trunc_commits",
"=",
"sorted",
"(",
"downloaded_commits",
",",
"reverse",
"=",
"True",
")",
"[",
":",
"args",
".",
"max_commits",
"]",
"extra_data",
"=",
"[",
"]",
"for",
"_",
",",
"idx",
",",
"commit",
"in",
"trunc_commits",
":",
"extra_data",
".",
"append",
"(",
"(",
"idx",
",",
"bench_util",
".",
"parse_skp_bench_data",
"(",
"args",
".",
"input_dir",
",",
"commit",
",",
"args",
".",
"representation_alg",
")",
")",
")",
"expectations_dict",
"=",
"create_expectations_dict",
"(",
"data_points",
",",
"builder",
",",
"extra_data",
")",
"out_lines",
"=",
"[",
"]",
"keys",
"=",
"expectations_dict",
".",
"keys",
"(",
")",
"keys",
".",
"sort",
"(",
")",
"for",
"(",
"config",
",",
"bench",
")",
"in",
"keys",
":",
"(",
"expected",
",",
"lower_bound",
",",
"upper_bound",
")",
"=",
"expectations_dict",
"[",
"(",
"config",
",",
"bench",
")",
"]",
"out_lines",
".",
"append",
"(",
"'%(bench)s_%(config)s_,%(builder)s-%(representation)s,'",
"'%(expected)s,%(lower_bound)s,%(upper_bound)s'",
"%",
"{",
"'bench'",
":",
"bench",
",",
"'config'",
":",
"config",
",",
"'builder'",
":",
"builder",
",",
"'representation'",
":",
"args",
".",
"representation_alg",
",",
"'expected'",
":",
"expected",
",",
"'lower_bound'",
":",
"lower_bound",
",",
"'upper_bound'",
":",
"upper_bound",
"}",
")",
"with",
"open",
"(",
"args",
".",
"output_file",
",",
"'w'",
")",
"as",
"file_handle",
":",
"file_handle",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"out_lines",
")",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/bench/gen_bench_expectations.py#L144-L219 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Toplevel.__init__ | (self, master=None, cnf={}, **kw) | Construct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class,
colormap, container, cursor, height, highlightbackground,
highlightcolor, highlightthickness, menu, relief, screen, takefocus,
use, visual, width. | Construct a toplevel widget with the parent MASTER. | [
"Construct",
"a",
"toplevel",
"widget",
"with",
"the",
"parent",
"MASTER",
"."
] | def __init__(self, master=None, cnf={}, **kw):
"""Construct a toplevel widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, class,
colormap, container, cursor, height, highlightbackground,
highlightcolor, highlightthickness, menu, relief, screen, takefocus,
use, visual, width."""
if kw:
cnf = _cnfmerge((cnf, kw))
extra = ()
for wmkey in ['screen', 'class_', 'class', 'visual',
'colormap']:
if wmkey in cnf:
val = cnf[wmkey]
# TBD: a hack needed because some keys
# are not valid as keyword arguments
if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
else: opt = '-'+wmkey
extra = extra + (opt, val)
del cnf[wmkey]
BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
root = self._root()
self.iconname(root.iconname())
self.title(root.title())
self.protocol("WM_DELETE_WINDOW", self.destroy) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"cnf",
"=",
"{",
"}",
",",
"*",
"*",
"kw",
")",
":",
"if",
"kw",
":",
"cnf",
"=",
"_cnfmerge",
"(",
"(",
"cnf",
",",
"kw",
")",
")",
"extra",
"=",
"(",
")",
"for",
"wmkey",
"in",
"[",
"'screen'",
",",
"'class_'",
",",
"'class'",
",",
"'visual'",
",",
"'colormap'",
"]",
":",
"if",
"wmkey",
"in",
"cnf",
":",
"val",
"=",
"cnf",
"[",
"wmkey",
"]",
"# TBD: a hack needed because some keys",
"# are not valid as keyword arguments",
"if",
"wmkey",
"[",
"-",
"1",
"]",
"==",
"'_'",
":",
"opt",
"=",
"'-'",
"+",
"wmkey",
"[",
":",
"-",
"1",
"]",
"else",
":",
"opt",
"=",
"'-'",
"+",
"wmkey",
"extra",
"=",
"extra",
"+",
"(",
"opt",
",",
"val",
")",
"del",
"cnf",
"[",
"wmkey",
"]",
"BaseWidget",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"'toplevel'",
",",
"cnf",
",",
"{",
"}",
",",
"extra",
")",
"root",
"=",
"self",
".",
"_root",
"(",
")",
"self",
".",
"iconname",
"(",
"root",
".",
"iconname",
"(",
")",
")",
"self",
".",
"title",
"(",
"root",
".",
"title",
"(",
")",
")",
"self",
".",
"protocol",
"(",
"\"WM_DELETE_WINDOW\"",
",",
"self",
".",
"destroy",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2322-L2346 | ||
google/clif | cab24d6a105609a65c95a36a1712ae3c20c7b5df | clif/pybind11/cindex/extractor.py | python | Function.from_cindex | (cls, cursor: Cursor, namespace: Text) | return cls(fq_name, is_pure_virtual, arguments, return_type) | Create a Type object from cindex cursor. | Create a Type object from cindex cursor. | [
"Create",
"a",
"Type",
"object",
"from",
"cindex",
"cursor",
"."
] | def from_cindex(cls, cursor: Cursor, namespace: Text):
"""Create a Type object from cindex cursor."""
fq_name = '::'.join([namespace, cursor.spelling])
is_pure_virtual = cursor.is_pure_virtual_method()
arguments = [
Type.from_cindex(x) for x in cursor.type.argument_types()
]
if cursor.type == TypeKind.VOID:
return_type = [Type.void()]
else:
return_type = [
Type.from_cindex(cursor.type.get_result())
]
return cls(fq_name, is_pure_virtual, arguments, return_type) | [
"def",
"from_cindex",
"(",
"cls",
",",
"cursor",
":",
"Cursor",
",",
"namespace",
":",
"Text",
")",
":",
"fq_name",
"=",
"'::'",
".",
"join",
"(",
"[",
"namespace",
",",
"cursor",
".",
"spelling",
"]",
")",
"is_pure_virtual",
"=",
"cursor",
".",
"is_pure_virtual_method",
"(",
")",
"arguments",
"=",
"[",
"Type",
".",
"from_cindex",
"(",
"x",
")",
"for",
"x",
"in",
"cursor",
".",
"type",
".",
"argument_types",
"(",
")",
"]",
"if",
"cursor",
".",
"type",
"==",
"TypeKind",
".",
"VOID",
":",
"return_type",
"=",
"[",
"Type",
".",
"void",
"(",
")",
"]",
"else",
":",
"return_type",
"=",
"[",
"Type",
".",
"from_cindex",
"(",
"cursor",
".",
"type",
".",
"get_result",
"(",
")",
")",
"]",
"return",
"cls",
"(",
"fq_name",
",",
"is_pure_virtual",
",",
"arguments",
",",
"return_type",
")"
] | https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/pybind11/cindex/extractor.py#L142-L155 | |
deepmodeling/deepmd-kit | 159e45d248b0429844fb6a8cb3b3a201987c8d79 | deepmd/entrypoints/config.py | python | suggest_batch_size | (all_type: List[np.ndarray], min_atom: int) | return bs | Get suggestion for batch size.
Parameters
----------
all_type : List[np.ndarray]
list with arrays specifying elements of structures
min_atom : int
minimal number of atoms in batch
Returns
-------
List[int]
suggested batch sizes for each system | Get suggestion for batch size. | [
"Get",
"suggestion",
"for",
"batch",
"size",
"."
] | def suggest_batch_size(all_type: List[np.ndarray], min_atom: int) -> List[int]:
"""Get suggestion for batch size.
Parameters
----------
all_type : List[np.ndarray]
list with arrays specifying elements of structures
min_atom : int
minimal number of atoms in batch
Returns
-------
List[int]
suggested batch sizes for each system
"""
bs = []
for ii in all_type:
natoms = len(ii)
tbs = min_atom // natoms
if (min_atom // natoms) * natoms != min_atom:
tbs += 1
bs.append(tbs)
return bs | [
"def",
"suggest_batch_size",
"(",
"all_type",
":",
"List",
"[",
"np",
".",
"ndarray",
"]",
",",
"min_atom",
":",
"int",
")",
"->",
"List",
"[",
"int",
"]",
":",
"bs",
"=",
"[",
"]",
"for",
"ii",
"in",
"all_type",
":",
"natoms",
"=",
"len",
"(",
"ii",
")",
"tbs",
"=",
"min_atom",
"//",
"natoms",
"if",
"(",
"min_atom",
"//",
"natoms",
")",
"*",
"natoms",
"!=",
"min_atom",
":",
"tbs",
"+=",
"1",
"bs",
".",
"append",
"(",
"tbs",
")",
"return",
"bs"
] | https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/entrypoints/config.py#L268-L290 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/utils/utils.py | python | get_tr1 | (name) | return tr1 | In libstd++ the tr1 namespace needs special care.
Return either an empty string or tr1::, useful for
appending to search patterns.
Args:
name (str): the name of the declaration
Returns:
str: an empty string or "tr1::" | In libstd++ the tr1 namespace needs special care. | [
"In",
"libstd",
"++",
"the",
"tr1",
"namespace",
"needs",
"special",
"care",
"."
] | def get_tr1(name):
"""In libstd++ the tr1 namespace needs special care.
Return either an empty string or tr1::, useful for
appending to search patterns.
Args:
name (str): the name of the declaration
Returns:
str: an empty string or "tr1::"
"""
tr1 = ""
if "tr1" in name:
tr1 = "tr1::"
return tr1 | [
"def",
"get_tr1",
"(",
"name",
")",
":",
"tr1",
"=",
"\"\"",
"if",
"\"tr1\"",
"in",
"name",
":",
"tr1",
"=",
"\"tr1::\"",
"return",
"tr1"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/utils/utils.py#L259-L274 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/ftplib.py | python | parse229 | (resp, peer) | return host, port | Parse the '229' response for an EPSV request.
Raises error_proto if it does not contain '(|||port|)'
Return ('host.addr.as.numbers', port#) tuple. | Parse the '229' response for an EPSV request.
Raises error_proto if it does not contain '(|||port|)'
Return ('host.addr.as.numbers', port#) tuple. | [
"Parse",
"the",
"229",
"response",
"for",
"an",
"EPSV",
"request",
".",
"Raises",
"error_proto",
"if",
"it",
"does",
"not",
"contain",
"(",
"|||port|",
")",
"Return",
"(",
"host",
".",
"addr",
".",
"as",
".",
"numbers",
"port#",
")",
"tuple",
"."
] | def parse229(resp, peer):
'''Parse the '229' response for an EPSV request.
Raises error_proto if it does not contain '(|||port|)'
Return ('host.addr.as.numbers', port#) tuple.'''
if resp[:3] != '229':
raise error_reply, resp
left = resp.find('(')
if left < 0: raise error_proto, resp
right = resp.find(')', left + 1)
if right < 0:
raise error_proto, resp # should contain '(|||port|)'
if resp[left + 1] != resp[right - 1]:
raise error_proto, resp
parts = resp[left + 1:right].split(resp[left+1])
if len(parts) != 5:
raise error_proto, resp
host = peer[0]
port = int(parts[3])
return host, port | [
"def",
"parse229",
"(",
"resp",
",",
"peer",
")",
":",
"if",
"resp",
"[",
":",
"3",
"]",
"!=",
"'229'",
":",
"raise",
"error_reply",
",",
"resp",
"left",
"=",
"resp",
".",
"find",
"(",
"'('",
")",
"if",
"left",
"<",
"0",
":",
"raise",
"error_proto",
",",
"resp",
"right",
"=",
"resp",
".",
"find",
"(",
"')'",
",",
"left",
"+",
"1",
")",
"if",
"right",
"<",
"0",
":",
"raise",
"error_proto",
",",
"resp",
"# should contain '(|||port|)'",
"if",
"resp",
"[",
"left",
"+",
"1",
"]",
"!=",
"resp",
"[",
"right",
"-",
"1",
"]",
":",
"raise",
"error_proto",
",",
"resp",
"parts",
"=",
"resp",
"[",
"left",
"+",
"1",
":",
"right",
"]",
".",
"split",
"(",
"resp",
"[",
"left",
"+",
"1",
"]",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"5",
":",
"raise",
"error_proto",
",",
"resp",
"host",
"=",
"peer",
"[",
"0",
"]",
"port",
"=",
"int",
"(",
"parts",
"[",
"3",
"]",
")",
"return",
"host",
",",
"port"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ftplib.py#L856-L875 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/applications/workbench/workbench/plotting/propertiesdialog.py | python | PropertiesEditorBase.error_occurred | (self, exc) | Indicates a redraw error occurred. Derived classes should override this
and revert the state of the canvas and display the error | Indicates a redraw error occurred. Derived classes should override this
and revert the state of the canvas and display the error | [
"Indicates",
"a",
"redraw",
"error",
"occurred",
".",
"Derived",
"classes",
"should",
"override",
"this",
"and",
"revert",
"the",
"state",
"of",
"the",
"canvas",
"and",
"display",
"the",
"error"
] | def error_occurred(self, exc):
"""Indicates a redraw error occurred. Derived classes should override this
and revert the state of the canvas and display the error
"""
raise NotImplementedError("Derived classes should override error_occurred") | [
"def",
"error_occurred",
"(",
"self",
",",
"exc",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Derived classes should override error_occurred\"",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/plotting/propertiesdialog.py#L56-L60 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/ceph-volume/ceph_volume/devices/raw/prepare.py | python | Prepare.safe_prepare | (self, args=None) | An intermediate step between `main()` and `prepare()` so that we can
capture the `self.osd_id` in case we need to rollback
:param args: Injected args, usually from `raw create` which compounds
both `prepare` and `create` | An intermediate step between `main()` and `prepare()` so that we can
capture the `self.osd_id` in case we need to rollback | [
"An",
"intermediate",
"step",
"between",
"main",
"()",
"and",
"prepare",
"()",
"so",
"that",
"we",
"can",
"capture",
"the",
"self",
".",
"osd_id",
"in",
"case",
"we",
"need",
"to",
"rollback"
] | def safe_prepare(self, args=None):
"""
An intermediate step between `main()` and `prepare()` so that we can
capture the `self.osd_id` in case we need to rollback
:param args: Injected args, usually from `raw create` which compounds
both `prepare` and `create`
"""
if args is not None:
self.args = args
try:
self.prepare()
except Exception:
logger.exception('raw prepare was unable to complete')
logger.info('will rollback OSD ID creation')
rollback_osd(self.args, self.osd_id)
raise
dmcrypt_log = 'dmcrypt' if args.dmcrypt else 'clear'
terminal.success("ceph-volume raw {} prepare successful for: {}".format(dmcrypt_log, self.args.data)) | [
"def",
"safe_prepare",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"not",
"None",
":",
"self",
".",
"args",
"=",
"args",
"try",
":",
"self",
".",
"prepare",
"(",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"'raw prepare was unable to complete'",
")",
"logger",
".",
"info",
"(",
"'will rollback OSD ID creation'",
")",
"rollback_osd",
"(",
"self",
".",
"args",
",",
"self",
".",
"osd_id",
")",
"raise",
"dmcrypt_log",
"=",
"'dmcrypt'",
"if",
"args",
".",
"dmcrypt",
"else",
"'clear'",
"terminal",
".",
"success",
"(",
"\"ceph-volume raw {} prepare successful for: {}\"",
".",
"format",
"(",
"dmcrypt_log",
",",
"self",
".",
"args",
".",
"data",
")",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/devices/raw/prepare.py#L80-L98 | ||
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/extension_dict.py | python | _ExtensionDict._FindExtensionByNumber | (self, number) | return self._extended_message._extensions_by_number.get(number, None) | Tries to find a known extension with the field number.
Args:
number: Extension field number.
Returns:
Extension field descriptor. | Tries to find a known extension with the field number. | [
"Tries",
"to",
"find",
"a",
"known",
"extension",
"with",
"the",
"field",
"number",
"."
] | def _FindExtensionByNumber(self, number):
"""Tries to find a known extension with the field number.
Args:
number: Extension field number.
Returns:
Extension field descriptor.
"""
return self._extended_message._extensions_by_number.get(number, None) | [
"def",
"_FindExtensionByNumber",
"(",
"self",
",",
"number",
")",
":",
"return",
"self",
".",
"_extended_message",
".",
"_extensions_by_number",
".",
"get",
"(",
"number",
",",
"None",
")"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/extension_dict.py#L183-L192 | |
facebook/bistro | db9eff7e92f5cedcc917a440d5c88064c7980e40 | build/fbcode_builder/shell_quoting.py | python | shell_join | (delim, it) | return ShellQuoted(delim.join(raw_shell(s) for s in it)) | Joins an iterable of ShellQuoted with a delimiter between each two | Joins an iterable of ShellQuoted with a delimiter between each two | [
"Joins",
"an",
"iterable",
"of",
"ShellQuoted",
"with",
"a",
"delimiter",
"between",
"each",
"two"
] | def shell_join(delim, it):
"Joins an iterable of ShellQuoted with a delimiter between each two"
return ShellQuoted(delim.join(raw_shell(s) for s in it)) | [
"def",
"shell_join",
"(",
"delim",
",",
"it",
")",
":",
"return",
"ShellQuoted",
"(",
"delim",
".",
"join",
"(",
"raw_shell",
"(",
"s",
")",
"for",
"s",
"in",
"it",
")",
")"
] | https://github.com/facebook/bistro/blob/db9eff7e92f5cedcc917a440d5c88064c7980e40/build/fbcode_builder/shell_quoting.py#L84-L86 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/context.py | python | BaseContext.can_convert | (self, fromty, toty) | Check whether conversion is possible from *fromty* to *toty*.
If successful, return a numba.typeconv.Conversion instance;
otherwise None is returned. | Check whether conversion is possible from *fromty* to *toty*.
If successful, return a numba.typeconv.Conversion instance;
otherwise None is returned. | [
"Check",
"whether",
"conversion",
"is",
"possible",
"from",
"*",
"fromty",
"*",
"to",
"*",
"toty",
"*",
".",
"If",
"successful",
"return",
"a",
"numba",
".",
"typeconv",
".",
"Conversion",
"instance",
";",
"otherwise",
"None",
"is",
"returned",
"."
] | def can_convert(self, fromty, toty):
"""
Check whether conversion is possible from *fromty* to *toty*.
If successful, return a numba.typeconv.Conversion instance;
otherwise None is returned.
"""
if fromty == toty:
return Conversion.exact
else:
# First check with the type manager (some rules are registered
# at startup there, see numba.typeconv.rules)
conv = self.tm.check_compatible(fromty, toty)
if conv is not None:
return conv
# Fall back on type-specific rules
forward = fromty.can_convert_to(self, toty)
backward = toty.can_convert_from(self, fromty)
if backward is None:
return forward
elif forward is None:
return backward
else:
return min(forward, backward) | [
"def",
"can_convert",
"(",
"self",
",",
"fromty",
",",
"toty",
")",
":",
"if",
"fromty",
"==",
"toty",
":",
"return",
"Conversion",
".",
"exact",
"else",
":",
"# First check with the type manager (some rules are registered",
"# at startup there, see numba.typeconv.rules)",
"conv",
"=",
"self",
".",
"tm",
".",
"check_compatible",
"(",
"fromty",
",",
"toty",
")",
"if",
"conv",
"is",
"not",
"None",
":",
"return",
"conv",
"# Fall back on type-specific rules",
"forward",
"=",
"fromty",
".",
"can_convert_to",
"(",
"self",
",",
"toty",
")",
"backward",
"=",
"toty",
".",
"can_convert_from",
"(",
"self",
",",
"fromty",
")",
"if",
"backward",
"is",
"None",
":",
"return",
"forward",
"elif",
"forward",
"is",
"None",
":",
"return",
"backward",
"else",
":",
"return",
"min",
"(",
"forward",
",",
"backward",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/context.py#L499-L522 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/bindings/python/llvm/object.py | python | Relocation.type_name | (self) | return lib.LLVMGetRelocationTypeName(self) | The relocation type's name, as a str. | The relocation type's name, as a str. | [
"The",
"relocation",
"type",
"s",
"name",
"as",
"a",
"str",
"."
] | def type_name(self):
"""The relocation type's name, as a str."""
if self.expired:
raise Exception('Relocation instance has expired.')
return lib.LLVMGetRelocationTypeName(self) | [
"def",
"type_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Relocation instance has expired.'",
")",
"return",
"lib",
".",
"LLVMGetRelocationTypeName",
"(",
"self",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/bindings/python/llvm/object.py#L399-L404 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/tabart.py | python | AuiSimpleTabArt.GetNormalFont | (self) | return self._normal_font | Returns the normal font for drawing tab labels. | Returns the normal font for drawing tab labels. | [
"Returns",
"the",
"normal",
"font",
"for",
"drawing",
"tab",
"labels",
"."
] | def GetNormalFont(self):
""" Returns the normal font for drawing tab labels. """
return self._normal_font | [
"def",
"GetNormalFont",
"(",
"self",
")",
":",
"return",
"self",
".",
"_normal_font"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/tabart.py#L1576-L1579 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py | python | HTMLDoc.namelink | (self, name, *dicts) | return name | Make a link for an identifier, given name-to-URL mappings. | Make a link for an identifier, given name-to-URL mappings. | [
"Make",
"a",
"link",
"for",
"an",
"identifier",
"given",
"name",
"-",
"to",
"-",
"URL",
"mappings",
"."
] | def namelink(self, name, *dicts):
"""Make a link for an identifier, given name-to-URL mappings."""
for dict in dicts:
if name in dict:
return '<a href="%s">%s</a>' % (dict[name], name)
return name | [
"def",
"namelink",
"(",
"self",
",",
"name",
",",
"*",
"dicts",
")",
":",
"for",
"dict",
"in",
"dicts",
":",
"if",
"name",
"in",
"dict",
":",
"return",
"'<a href=\"%s\">%s</a>'",
"%",
"(",
"dict",
"[",
"name",
"]",
",",
"name",
")",
"return",
"name"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py#L492-L497 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ctypes/_aix.py | python | find_shared | (paths, name) | return (None, None) | paths is a list of directories to search for an archive.
name is the abbreviated name given to find_library().
Process: search "paths" for archive, and if an archive is found
return the result of get_member().
If an archive is not found then return None | paths is a list of directories to search for an archive.
name is the abbreviated name given to find_library().
Process: search "paths" for archive, and if an archive is found
return the result of get_member().
If an archive is not found then return None | [
"paths",
"is",
"a",
"list",
"of",
"directories",
"to",
"search",
"for",
"an",
"archive",
".",
"name",
"is",
"the",
"abbreviated",
"name",
"given",
"to",
"find_library",
"()",
".",
"Process",
":",
"search",
"paths",
"for",
"archive",
"and",
"if",
"an",
"archive",
"is",
"found",
"return",
"the",
"result",
"of",
"get_member",
"()",
".",
"If",
"an",
"archive",
"is",
"not",
"found",
"then",
"return",
"None"
] | def find_shared(paths, name):
"""
paths is a list of directories to search for an archive.
name is the abbreviated name given to find_library().
Process: search "paths" for archive, and if an archive is found
return the result of get_member().
If an archive is not found then return None
"""
for dir in paths:
# /lib is a symbolic link to /usr/lib, skip it
if dir == "/lib":
continue
# "lib" is prefixed to emulate compiler name resolution,
# e.g., -lc to libc
base = f'lib{name}.a'
archive = path.join(dir, base)
if path.exists(archive):
members = get_shared(get_ld_headers(archive))
member = get_member(re.escape(name), members)
if member is not None:
return (base, member)
else:
return (None, None)
return (None, None) | [
"def",
"find_shared",
"(",
"paths",
",",
"name",
")",
":",
"for",
"dir",
"in",
"paths",
":",
"# /lib is a symbolic link to /usr/lib, skip it",
"if",
"dir",
"==",
"\"/lib\"",
":",
"continue",
"# \"lib\" is prefixed to emulate compiler name resolution,",
"# e.g., -lc to libc",
"base",
"=",
"f'lib{name}.a'",
"archive",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"base",
")",
"if",
"path",
".",
"exists",
"(",
"archive",
")",
":",
"members",
"=",
"get_shared",
"(",
"get_ld_headers",
"(",
"archive",
")",
")",
"member",
"=",
"get_member",
"(",
"re",
".",
"escape",
"(",
"name",
")",
",",
"members",
")",
"if",
"member",
"is",
"not",
"None",
":",
"return",
"(",
"base",
",",
"member",
")",
"else",
":",
"return",
"(",
"None",
",",
"None",
")",
"return",
"(",
"None",
",",
"None",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ctypes/_aix.py#L266-L289 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py | python | Message.__bytes__ | (self) | return self.as_bytes() | Return the entire formatted message as a bytes object. | Return the entire formatted message as a bytes object. | [
"Return",
"the",
"entire",
"formatted",
"message",
"as",
"a",
"bytes",
"object",
"."
] | def __bytes__(self):
"""Return the entire formatted message as a bytes object.
"""
return self.as_bytes() | [
"def",
"__bytes__",
"(",
"self",
")",
":",
"return",
"self",
".",
"as_bytes",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py#L161-L164 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/sgraph.py | python | SGraph.get_fields | (self) | return self.get_vertex_fields() + self.get_edge_fields() | Return a list of vertex and edge attribute fields in the SGraph. If a
field is common to both vertex and edge attributes, it will show up
twice in the returned list.
Returns
-------
out : list
Names of fields contained in the vertex or edge data.
See Also
--------
get_vertex_fields, get_edge_fields
Examples
--------
>>> from turicreate import SGraph, Vertex, Edge
>>> g = SGraph()
>>> verts = [Vertex(0, attr={'name': 'alex'}),
Vertex(1, attr={'name': 'barbara'})]
>>> g = g.add_vertices(verts)
>>> g = g.add_edges(Edge(0, 1, attr={'frequency': 6}))
>>> fields = g.get_fields()
['__id', 'name', '__src_id', '__dst_id', 'frequency'] | Return a list of vertex and edge attribute fields in the SGraph. If a
field is common to both vertex and edge attributes, it will show up
twice in the returned list. | [
"Return",
"a",
"list",
"of",
"vertex",
"and",
"edge",
"attribute",
"fields",
"in",
"the",
"SGraph",
".",
"If",
"a",
"field",
"is",
"common",
"to",
"both",
"vertex",
"and",
"edge",
"attributes",
"it",
"will",
"show",
"up",
"twice",
"in",
"the",
"returned",
"list",
"."
] | def get_fields(self):
"""
Return a list of vertex and edge attribute fields in the SGraph. If a
field is common to both vertex and edge attributes, it will show up
twice in the returned list.
Returns
-------
out : list
Names of fields contained in the vertex or edge data.
See Also
--------
get_vertex_fields, get_edge_fields
Examples
--------
>>> from turicreate import SGraph, Vertex, Edge
>>> g = SGraph()
>>> verts = [Vertex(0, attr={'name': 'alex'}),
Vertex(1, attr={'name': 'barbara'})]
>>> g = g.add_vertices(verts)
>>> g = g.add_edges(Edge(0, 1, attr={'frequency': 6}))
>>> fields = g.get_fields()
['__id', 'name', '__src_id', '__dst_id', 'frequency']
"""
return self.get_vertex_fields() + self.get_edge_fields() | [
"def",
"get_fields",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_vertex_fields",
"(",
")",
"+",
"self",
".",
"get_edge_fields",
"(",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sgraph.py#L758-L785 | |
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | dev/archery/archery/benchmark/runner.py | python | CppBenchmarkRunner.suites_binaries | (self) | return {os.path.basename(b): b for b in glob.glob(glob_expr)} | Returns a list of benchmark binaries for this build. | Returns a list of benchmark binaries for this build. | [
"Returns",
"a",
"list",
"of",
"benchmark",
"binaries",
"for",
"this",
"build",
"."
] | def suites_binaries(self):
""" Returns a list of benchmark binaries for this build. """
# Ensure build is up-to-date to run benchmarks
self.build()
# Not the best method, but works for now
glob_expr = os.path.join(self.build.binaries_dir, "*-benchmark")
return {os.path.basename(b): b for b in glob.glob(glob_expr)} | [
"def",
"suites_binaries",
"(",
"self",
")",
":",
"# Ensure build is up-to-date to run benchmarks",
"self",
".",
"build",
"(",
")",
"# Not the best method, but works for now",
"glob_expr",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"build",
".",
"binaries_dir",
",",
"\"*-benchmark\"",
")",
"return",
"{",
"os",
".",
"path",
".",
"basename",
"(",
"b",
")",
":",
"b",
"for",
"b",
"in",
"glob",
".",
"glob",
"(",
"glob_expr",
")",
"}"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/benchmark/runner.py#L135-L141 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/large/metadataset.py | python | MetaDataSet._submodel_path | (self, i) | return os.path.join(self.data_path, template % i) | Path to submodel i folder. | Path to submodel i folder. | [
"Path",
"to",
"submodel",
"i",
"folder",
"."
] | def _submodel_path(self, i):
"""Path to submodel i folder."""
template = self.config['submodel_relpath_template']
return os.path.join(self.data_path, template % i) | [
"def",
"_submodel_path",
"(",
"self",
",",
"i",
")",
":",
"template",
"=",
"self",
".",
"config",
"[",
"'submodel_relpath_template'",
"]",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"template",
"%",
"i",
")"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/large/metadataset.py#L34-L37 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py | python | obj_analysis.is_result_vector | (self) | return (self.result_type == 'vector') | Returns true if this is a vector type. | Returns true if this is a vector type. | [
"Returns",
"true",
"if",
"this",
"is",
"a",
"vector",
"type",
"."
] | def is_result_vector(self):
""" Returns true if this is a vector type. """
return (self.result_type == 'vector') | [
"def",
"is_result_vector",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"result_type",
"==",
"'vector'",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L1877-L1879 | |
dmlc/xgboost | 2775c2a1abd4b5b759ff517617434c8b9aeb4cc0 | python-package/xgboost/training.py | python | CVPack.__init__ | (self, dtrain, dtest, param) | Initialize the CVPack | Initialize the CVPack | [
"Initialize",
"the",
"CVPack"
] | def __init__(self, dtrain, dtest, param):
""""Initialize the CVPack"""
self.dtrain = dtrain
self.dtest = dtest
self.watchlist = [(dtrain, 'train'), (dtest, 'test')]
self.bst = Booster(param, [dtrain, dtest]) | [
"def",
"__init__",
"(",
"self",
",",
"dtrain",
",",
"dtest",
",",
"param",
")",
":",
"self",
".",
"dtrain",
"=",
"dtrain",
"self",
".",
"dtest",
"=",
"dtest",
"self",
".",
"watchlist",
"=",
"[",
"(",
"dtrain",
",",
"'train'",
")",
",",
"(",
"dtest",
",",
"'test'",
")",
"]",
"self",
".",
"bst",
"=",
"Booster",
"(",
"param",
",",
"[",
"dtrain",
",",
"dtest",
"]",
")"
] | https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/xgboost/training.py#L189-L194 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | isBlank | (ch) | return ret | This function is DEPRECATED. Use xmlIsBlank_ch or
xmlIsBlankQ instead | This function is DEPRECATED. Use xmlIsBlank_ch or
xmlIsBlankQ instead | [
"This",
"function",
"is",
"DEPRECATED",
".",
"Use",
"xmlIsBlank_ch",
"or",
"xmlIsBlankQ",
"instead"
] | def isBlank(ch):
"""This function is DEPRECATED. Use xmlIsBlank_ch or
xmlIsBlankQ instead """
ret = libxml2mod.xmlIsBlank(ch)
return ret | [
"def",
"isBlank",
"(",
"ch",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlIsBlank",
"(",
"ch",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L1033-L1037 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/format/policy_templates/writers/reg_writer.py | python | RegWriter.GetPolicySortingKey | (self, policy) | return (is_list, policy['name']) | Extracts a sorting key from a policy. These keys can be used for
list.sort() methods to sort policies.
See TemplateWriter.SortPoliciesGroupsFirst for usage. | Extracts a sorting key from a policy. These keys can be used for
list.sort() methods to sort policies.
See TemplateWriter.SortPoliciesGroupsFirst for usage. | [
"Extracts",
"a",
"sorting",
"key",
"from",
"a",
"policy",
".",
"These",
"keys",
"can",
"be",
"used",
"for",
"list",
".",
"sort",
"()",
"methods",
"to",
"sort",
"policies",
".",
"See",
"TemplateWriter",
".",
"SortPoliciesGroupsFirst",
"for",
"usage",
"."
] | def GetPolicySortingKey(self, policy):
'''Extracts a sorting key from a policy. These keys can be used for
list.sort() methods to sort policies.
See TemplateWriter.SortPoliciesGroupsFirst for usage.
'''
is_list = policy['type'] in ('list', 'string-enum-list')
# Lists come after regular policies.
return (is_list, policy['name']) | [
"def",
"GetPolicySortingKey",
"(",
"self",
",",
"policy",
")",
":",
"is_list",
"=",
"policy",
"[",
"'type'",
"]",
"in",
"(",
"'list'",
",",
"'string-enum-list'",
")",
"# Lists come after regular policies.",
"return",
"(",
"is_list",
",",
"policy",
"[",
"'name'",
"]",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/policy_templates/writers/reg_writer.py#L45-L52 | |
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | bindings/python/rad_util.py | python | round_grid | (value, grid, mode=0) | return result | Round off the given value to the given grid size.
Arguments:
value -- value to be roudne
grid -- result must be a multiple of this
mode -- 0 nearest, 1 up, -1 down
Examples:
>>> round_grid(7.5, 5)
10
>>> round_grid(7.5, 5, mode=-1)
5
>>> round_grid(7.3, 5, mode=1)
10
>>> round_grid(7.3, 5.0, mode=1)
10.0 | Round off the given value to the given grid size. | [
"Round",
"off",
"the",
"given",
"value",
"to",
"the",
"given",
"grid",
"size",
"."
] | def round_grid(value, grid, mode=0):
"""Round off the given value to the given grid size.
Arguments:
value -- value to be roudne
grid -- result must be a multiple of this
mode -- 0 nearest, 1 up, -1 down
Examples:
>>> round_grid(7.5, 5)
10
>>> round_grid(7.5, 5, mode=-1)
5
>>> round_grid(7.3, 5, mode=1)
10
>>> round_grid(7.3, 5.0, mode=1)
10.0
"""
off_grid = value % grid
if mode == 0:
add_one = int(off_grid >= (grid / 2.0))
elif mode == 1 and off_grid:
add_one = 1
elif mode == -1 and off_grid:
add_one = 0
result = ((int(value / grid) + add_one) * grid)
return result | [
"def",
"round_grid",
"(",
"value",
",",
"grid",
",",
"mode",
"=",
"0",
")",
":",
"off_grid",
"=",
"value",
"%",
"grid",
"if",
"mode",
"==",
"0",
":",
"add_one",
"=",
"int",
"(",
"off_grid",
">=",
"(",
"grid",
"/",
"2.0",
")",
")",
"elif",
"mode",
"==",
"1",
"and",
"off_grid",
":",
"add_one",
"=",
"1",
"elif",
"mode",
"==",
"-",
"1",
"and",
"off_grid",
":",
"add_one",
"=",
"0",
"result",
"=",
"(",
"(",
"int",
"(",
"value",
"/",
"grid",
")",
"+",
"add_one",
")",
"*",
"grid",
")",
"return",
"result"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/bindings/python/rad_util.py#L842-L873 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config.py | python | IdleConf.GetExtnNameForEvent | (self, virtualEvent) | return extName | Return the name of the extension binding virtualEvent, or None.
virtualEvent - string, name of the virtual event to test for,
without the enclosing '<< >>' | Return the name of the extension binding virtualEvent, or None. | [
"Return",
"the",
"name",
"of",
"the",
"extension",
"binding",
"virtualEvent",
"or",
"None",
"."
] | def GetExtnNameForEvent(self, virtualEvent):
"""Return the name of the extension binding virtualEvent, or None.
virtualEvent - string, name of the virtual event to test for,
without the enclosing '<< >>'
"""
extName = None
vEvent = '<<' + virtualEvent + '>>'
for extn in self.GetExtensions(active_only=0):
for event in self.GetExtensionKeys(extn):
if event == vEvent:
extName = extn # TODO return here?
return extName | [
"def",
"GetExtnNameForEvent",
"(",
"self",
",",
"virtualEvent",
")",
":",
"extName",
"=",
"None",
"vEvent",
"=",
"'<<'",
"+",
"virtualEvent",
"+",
"'>>'",
"for",
"extn",
"in",
"self",
".",
"GetExtensions",
"(",
"active_only",
"=",
"0",
")",
":",
"for",
"event",
"in",
"self",
".",
"GetExtensionKeys",
"(",
"extn",
")",
":",
"if",
"event",
"==",
"vEvent",
":",
"extName",
"=",
"extn",
"# TODO return here?",
"return",
"extName"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config.py#L457-L469 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/config.py | python | DictConfigurator.configure_filter | (self, config) | return result | Configure a filter from a dictionary. | Configure a filter from a dictionary. | [
"Configure",
"a",
"filter",
"from",
"a",
"dictionary",
"."
] | def configure_filter(self, config):
"""Configure a filter from a dictionary."""
if '()' in config:
result = self.configure_custom(config)
else:
name = config.get('name', '')
result = logging.Filter(name)
return result | [
"def",
"configure_filter",
"(",
"self",
",",
"config",
")",
":",
"if",
"'()'",
"in",
"config",
":",
"result",
"=",
"self",
".",
"configure_custom",
"(",
"config",
")",
"else",
":",
"name",
"=",
"config",
".",
"get",
"(",
"'name'",
",",
"''",
")",
"result",
"=",
"logging",
".",
"Filter",
"(",
"name",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/config.py#L677-L684 | |
isc-projects/kea | c5836c791b63f42173bb604dd5f05d7110f3e716 | hammer.py | python | _install_gtest_sources | () | Install gtest sources. | Install gtest sources. | [
"Install",
"gtest",
"sources",
"."
] | def _install_gtest_sources():
"""Install gtest sources."""
# download gtest sources only if it is not present as native package
if not os.path.exists('/usr/src/googletest-release-1.10.0/googletest'):
cmd = 'wget --no-verbose -O /tmp/gtest.tar.gz '
cmd += 'https://github.com/google/googletest/archive/release-1.10.0.tar.gz'
execute(cmd)
execute('sudo mkdir -p /usr/src')
execute('sudo tar -C /usr/src -zxf /tmp/gtest.tar.gz')
execute('sudo ln -sf /usr/src/googletest-release-1.10.0 /usr/src/googletest')
os.unlink('/tmp/gtest.tar.gz') | [
"def",
"_install_gtest_sources",
"(",
")",
":",
"# download gtest sources only if it is not present as native package",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'/usr/src/googletest-release-1.10.0/googletest'",
")",
":",
"cmd",
"=",
"'wget --no-verbose -O /tmp/gtest.tar.gz '",
"cmd",
"+=",
"'https://github.com/google/googletest/archive/release-1.10.0.tar.gz'",
"execute",
"(",
"cmd",
")",
"execute",
"(",
"'sudo mkdir -p /usr/src'",
")",
"execute",
"(",
"'sudo tar -C /usr/src -zxf /tmp/gtest.tar.gz'",
")",
"execute",
"(",
"'sudo ln -sf /usr/src/googletest-release-1.10.0 /usr/src/googletest'",
")",
"os",
".",
"unlink",
"(",
"'/tmp/gtest.tar.gz'",
")"
] | https://github.com/isc-projects/kea/blob/c5836c791b63f42173bb604dd5f05d7110f3e716/hammer.py#L1020-L1030 | ||
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert-gpu/utils/create_glue_data.py | python | XnliProcessor.get_labels | (self) | return ["contradiction", "entailment", "neutral"] | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_labels(self):
"""See base class."""
return ["contradiction", "entailment", "neutral"] | [
"def",
"get_labels",
"(",
"self",
")",
":",
"return",
"[",
"\"contradiction\"",
",",
"\"entailment\"",
",",
"\"neutral\"",
"]"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/utils/create_glue_data.py#L176-L178 | |
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | shell/ext-py/sqlparse-0.3.1/sqlparse/formatter.py | python | validate_options | (options) | return options | Validates options. | Validates options. | [
"Validates",
"options",
"."
] | def validate_options(options):
"""Validates options."""
kwcase = options.get('keyword_case')
if kwcase not in [None, 'upper', 'lower', 'capitalize']:
raise SQLParseError('Invalid value for keyword_case: '
'{0!r}'.format(kwcase))
idcase = options.get('identifier_case')
if idcase not in [None, 'upper', 'lower', 'capitalize']:
raise SQLParseError('Invalid value for identifier_case: '
'{0!r}'.format(idcase))
ofrmt = options.get('output_format')
if ofrmt not in [None, 'sql', 'python', 'php']:
raise SQLParseError('Unknown output format: '
'{0!r}'.format(ofrmt))
strip_comments = options.get('strip_comments', False)
if strip_comments not in [True, False]:
raise SQLParseError('Invalid value for strip_comments: '
'{0!r}'.format(strip_comments))
space_around_operators = options.get('use_space_around_operators', False)
if space_around_operators not in [True, False]:
raise SQLParseError('Invalid value for use_space_around_operators: '
'{0!r}'.format(space_around_operators))
strip_ws = options.get('strip_whitespace', False)
if strip_ws not in [True, False]:
raise SQLParseError('Invalid value for strip_whitespace: '
'{0!r}'.format(strip_ws))
truncate_strings = options.get('truncate_strings')
if truncate_strings is not None:
try:
truncate_strings = int(truncate_strings)
except (ValueError, TypeError):
raise SQLParseError('Invalid value for truncate_strings: '
'{0!r}'.format(truncate_strings))
if truncate_strings <= 1:
raise SQLParseError('Invalid value for truncate_strings: '
'{0!r}'.format(truncate_strings))
options['truncate_strings'] = truncate_strings
options['truncate_char'] = options.get('truncate_char', '[...]')
indent_columns = options.get('indent_columns', False)
if indent_columns not in [True, False]:
raise SQLParseError('Invalid value for indent_columns: '
'{0!r}'.format(indent_columns))
elif indent_columns:
options['reindent'] = True # enforce reindent
options['indent_columns'] = indent_columns
reindent = options.get('reindent', False)
if reindent not in [True, False]:
raise SQLParseError('Invalid value for reindent: '
'{0!r}'.format(reindent))
elif reindent:
options['strip_whitespace'] = True
reindent_aligned = options.get('reindent_aligned', False)
if reindent_aligned not in [True, False]:
raise SQLParseError('Invalid value for reindent_aligned: '
'{0!r}'.format(reindent))
elif reindent_aligned:
options['strip_whitespace'] = True
indent_after_first = options.get('indent_after_first', False)
if indent_after_first not in [True, False]:
raise SQLParseError('Invalid value for indent_after_first: '
'{0!r}'.format(indent_after_first))
options['indent_after_first'] = indent_after_first
indent_tabs = options.get('indent_tabs', False)
if indent_tabs not in [True, False]:
raise SQLParseError('Invalid value for indent_tabs: '
'{0!r}'.format(indent_tabs))
elif indent_tabs:
options['indent_char'] = '\t'
else:
options['indent_char'] = ' '
indent_width = options.get('indent_width', 2)
try:
indent_width = int(indent_width)
except (TypeError, ValueError):
raise SQLParseError('indent_width requires an integer')
if indent_width < 1:
raise SQLParseError('indent_width requires a positive integer')
options['indent_width'] = indent_width
wrap_after = options.get('wrap_after', 0)
try:
wrap_after = int(wrap_after)
except (TypeError, ValueError):
raise SQLParseError('wrap_after requires an integer')
if wrap_after < 0:
raise SQLParseError('wrap_after requires a positive integer')
options['wrap_after'] = wrap_after
comma_first = options.get('comma_first', False)
if comma_first not in [True, False]:
raise SQLParseError('comma_first requires a boolean value')
options['comma_first'] = comma_first
right_margin = options.get('right_margin')
if right_margin is not None:
try:
right_margin = int(right_margin)
except (TypeError, ValueError):
raise SQLParseError('right_margin requires an integer')
if right_margin < 10:
raise SQLParseError('right_margin requires an integer > 10')
options['right_margin'] = right_margin
return options | [
"def",
"validate_options",
"(",
"options",
")",
":",
"kwcase",
"=",
"options",
".",
"get",
"(",
"'keyword_case'",
")",
"if",
"kwcase",
"not",
"in",
"[",
"None",
",",
"'upper'",
",",
"'lower'",
",",
"'capitalize'",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for keyword_case: '",
"'{0!r}'",
".",
"format",
"(",
"kwcase",
")",
")",
"idcase",
"=",
"options",
".",
"get",
"(",
"'identifier_case'",
")",
"if",
"idcase",
"not",
"in",
"[",
"None",
",",
"'upper'",
",",
"'lower'",
",",
"'capitalize'",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for identifier_case: '",
"'{0!r}'",
".",
"format",
"(",
"idcase",
")",
")",
"ofrmt",
"=",
"options",
".",
"get",
"(",
"'output_format'",
")",
"if",
"ofrmt",
"not",
"in",
"[",
"None",
",",
"'sql'",
",",
"'python'",
",",
"'php'",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Unknown output format: '",
"'{0!r}'",
".",
"format",
"(",
"ofrmt",
")",
")",
"strip_comments",
"=",
"options",
".",
"get",
"(",
"'strip_comments'",
",",
"False",
")",
"if",
"strip_comments",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for strip_comments: '",
"'{0!r}'",
".",
"format",
"(",
"strip_comments",
")",
")",
"space_around_operators",
"=",
"options",
".",
"get",
"(",
"'use_space_around_operators'",
",",
"False",
")",
"if",
"space_around_operators",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for use_space_around_operators: '",
"'{0!r}'",
".",
"format",
"(",
"space_around_operators",
")",
")",
"strip_ws",
"=",
"options",
".",
"get",
"(",
"'strip_whitespace'",
",",
"False",
")",
"if",
"strip_ws",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for strip_whitespace: '",
"'{0!r}'",
".",
"format",
"(",
"strip_ws",
")",
")",
"truncate_strings",
"=",
"options",
".",
"get",
"(",
"'truncate_strings'",
")",
"if",
"truncate_strings",
"is",
"not",
"None",
":",
"try",
":",
"truncate_strings",
"=",
"int",
"(",
"truncate_strings",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for truncate_strings: '",
"'{0!r}'",
".",
"format",
"(",
"truncate_strings",
")",
")",
"if",
"truncate_strings",
"<=",
"1",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for truncate_strings: '",
"'{0!r}'",
".",
"format",
"(",
"truncate_strings",
")",
")",
"options",
"[",
"'truncate_strings'",
"]",
"=",
"truncate_strings",
"options",
"[",
"'truncate_char'",
"]",
"=",
"options",
".",
"get",
"(",
"'truncate_char'",
",",
"'[...]'",
")",
"indent_columns",
"=",
"options",
".",
"get",
"(",
"'indent_columns'",
",",
"False",
")",
"if",
"indent_columns",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for indent_columns: '",
"'{0!r}'",
".",
"format",
"(",
"indent_columns",
")",
")",
"elif",
"indent_columns",
":",
"options",
"[",
"'reindent'",
"]",
"=",
"True",
"# enforce reindent",
"options",
"[",
"'indent_columns'",
"]",
"=",
"indent_columns",
"reindent",
"=",
"options",
".",
"get",
"(",
"'reindent'",
",",
"False",
")",
"if",
"reindent",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for reindent: '",
"'{0!r}'",
".",
"format",
"(",
"reindent",
")",
")",
"elif",
"reindent",
":",
"options",
"[",
"'strip_whitespace'",
"]",
"=",
"True",
"reindent_aligned",
"=",
"options",
".",
"get",
"(",
"'reindent_aligned'",
",",
"False",
")",
"if",
"reindent_aligned",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for reindent_aligned: '",
"'{0!r}'",
".",
"format",
"(",
"reindent",
")",
")",
"elif",
"reindent_aligned",
":",
"options",
"[",
"'strip_whitespace'",
"]",
"=",
"True",
"indent_after_first",
"=",
"options",
".",
"get",
"(",
"'indent_after_first'",
",",
"False",
")",
"if",
"indent_after_first",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for indent_after_first: '",
"'{0!r}'",
".",
"format",
"(",
"indent_after_first",
")",
")",
"options",
"[",
"'indent_after_first'",
"]",
"=",
"indent_after_first",
"indent_tabs",
"=",
"options",
".",
"get",
"(",
"'indent_tabs'",
",",
"False",
")",
"if",
"indent_tabs",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for indent_tabs: '",
"'{0!r}'",
".",
"format",
"(",
"indent_tabs",
")",
")",
"elif",
"indent_tabs",
":",
"options",
"[",
"'indent_char'",
"]",
"=",
"'\\t'",
"else",
":",
"options",
"[",
"'indent_char'",
"]",
"=",
"' '",
"indent_width",
"=",
"options",
".",
"get",
"(",
"'indent_width'",
",",
"2",
")",
"try",
":",
"indent_width",
"=",
"int",
"(",
"indent_width",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"SQLParseError",
"(",
"'indent_width requires an integer'",
")",
"if",
"indent_width",
"<",
"1",
":",
"raise",
"SQLParseError",
"(",
"'indent_width requires a positive integer'",
")",
"options",
"[",
"'indent_width'",
"]",
"=",
"indent_width",
"wrap_after",
"=",
"options",
".",
"get",
"(",
"'wrap_after'",
",",
"0",
")",
"try",
":",
"wrap_after",
"=",
"int",
"(",
"wrap_after",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"SQLParseError",
"(",
"'wrap_after requires an integer'",
")",
"if",
"wrap_after",
"<",
"0",
":",
"raise",
"SQLParseError",
"(",
"'wrap_after requires a positive integer'",
")",
"options",
"[",
"'wrap_after'",
"]",
"=",
"wrap_after",
"comma_first",
"=",
"options",
".",
"get",
"(",
"'comma_first'",
",",
"False",
")",
"if",
"comma_first",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'comma_first requires a boolean value'",
")",
"options",
"[",
"'comma_first'",
"]",
"=",
"comma_first",
"right_margin",
"=",
"options",
".",
"get",
"(",
"'right_margin'",
")",
"if",
"right_margin",
"is",
"not",
"None",
":",
"try",
":",
"right_margin",
"=",
"int",
"(",
"right_margin",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"SQLParseError",
"(",
"'right_margin requires an integer'",
")",
"if",
"right_margin",
"<",
"10",
":",
"raise",
"SQLParseError",
"(",
"'right_margin requires an integer > 10'",
")",
"options",
"[",
"'right_margin'",
"]",
"=",
"right_margin",
"return",
"options"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/ext-py/sqlparse-0.3.1/sqlparse/formatter.py#L15-L130 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/vision/py_transforms_util.py | python | adjust_saturation | (img, saturation_factor) | return img | Adjust saturation of an image.
Args:
img (PIL image): PIL image to be adjusted.
saturation_factor (float): A non negative number indicated the factor by which
the saturation is adjusted. 0 will give a black and white image, 1 will
give the original.
Returns:
img (PIL image), Saturation adjusted image. | Adjust saturation of an image. | [
"Adjust",
"saturation",
"of",
"an",
"image",
"."
] | def adjust_saturation(img, saturation_factor):
"""
Adjust saturation of an image.
Args:
img (PIL image): PIL image to be adjusted.
saturation_factor (float): A non negative number indicated the factor by which
the saturation is adjusted. 0 will give a black and white image, 1 will
give the original.
Returns:
img (PIL image), Saturation adjusted image.
"""
if not is_pil(img):
raise TypeError(augment_error_message.format(type(img)))
enhancer = ImageEnhance.Color(img)
img = enhancer.enhance(saturation_factor)
return img | [
"def",
"adjust_saturation",
"(",
"img",
",",
"saturation_factor",
")",
":",
"if",
"not",
"is_pil",
"(",
"img",
")",
":",
"raise",
"TypeError",
"(",
"augment_error_message",
".",
"format",
"(",
"type",
"(",
"img",
")",
")",
")",
"enhancer",
"=",
"ImageEnhance",
".",
"Color",
"(",
"img",
")",
"img",
"=",
"enhancer",
".",
"enhance",
"(",
"saturation_factor",
")",
"return",
"img"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/vision/py_transforms_util.py#L508-L526 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/jedi/jedi/evaluate/sys_path.py | python | dotted_path_in_sys_path | (sys_path, module_path) | return None | Returns the dotted path inside a sys.path as a list of names. | Returns the dotted path inside a sys.path as a list of names. | [
"Returns",
"the",
"dotted",
"path",
"inside",
"a",
"sys",
".",
"path",
"as",
"a",
"list",
"of",
"names",
"."
] | def dotted_path_in_sys_path(sys_path, module_path):
"""
Returns the dotted path inside a sys.path as a list of names.
"""
# First remove the suffix.
for suffix in all_suffixes():
if module_path.endswith(suffix):
module_path = module_path[:-len(suffix)]
break
else:
# There should always be a suffix in a valid Python file on the path.
return None
if module_path.startswith(os.path.sep):
# The paths in sys.path most of the times don't end with a slash.
module_path = module_path[1:]
for p in sys_path:
if module_path.startswith(p):
rest = module_path[len(p):]
if rest:
split = rest.split(os.path.sep)
for string in split:
if not string or '.' in string:
return None
return split
return None | [
"def",
"dotted_path_in_sys_path",
"(",
"sys_path",
",",
"module_path",
")",
":",
"# First remove the suffix.",
"for",
"suffix",
"in",
"all_suffixes",
"(",
")",
":",
"if",
"module_path",
".",
"endswith",
"(",
"suffix",
")",
":",
"module_path",
"=",
"module_path",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"]",
"break",
"else",
":",
"# There should always be a suffix in a valid Python file on the path.",
"return",
"None",
"if",
"module_path",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
":",
"# The paths in sys.path most of the times don't end with a slash.",
"module_path",
"=",
"module_path",
"[",
"1",
":",
"]",
"for",
"p",
"in",
"sys_path",
":",
"if",
"module_path",
".",
"startswith",
"(",
"p",
")",
":",
"rest",
"=",
"module_path",
"[",
"len",
"(",
"p",
")",
":",
"]",
"if",
"rest",
":",
"split",
"=",
"rest",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"for",
"string",
"in",
"split",
":",
"if",
"not",
"string",
"or",
"'.'",
"in",
"string",
":",
"return",
"None",
"return",
"split",
"return",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/evaluate/sys_path.py#L199-L226 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py | python | _OldAbstractDatastoreInputReader.__init__ | (self,
entity_kind,
key_ranges=None,
ns_range=None,
batch_size=_BATCH_SIZE,
current_key_range=None,
filters=None) | Create new AbstractDatastoreInputReader object.
This is internal constructor. Use split_query in a concrete class instead.
Args:
entity_kind: entity kind as string.
key_ranges: a sequence of key_range.KeyRange instances to process. Only
one of key_ranges or ns_range can be non-None.
ns_range: a namespace_range.NamespaceRange to process. Only one of
key_ranges or ns_range can be non-None.
batch_size: size of read batch as int.
current_key_range: the current key_range.KeyRange being processed.
filters: optional list of filters to apply to the query. Each filter is
a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>).
User filters are applied first. | Create new AbstractDatastoreInputReader object. | [
"Create",
"new",
"AbstractDatastoreInputReader",
"object",
"."
] | def __init__(self,
entity_kind,
key_ranges=None,
ns_range=None,
batch_size=_BATCH_SIZE,
current_key_range=None,
filters=None):
"""Create new AbstractDatastoreInputReader object.
This is internal constructor. Use split_query in a concrete class instead.
Args:
entity_kind: entity kind as string.
key_ranges: a sequence of key_range.KeyRange instances to process. Only
one of key_ranges or ns_range can be non-None.
ns_range: a namespace_range.NamespaceRange to process. Only one of
key_ranges or ns_range can be non-None.
batch_size: size of read batch as int.
current_key_range: the current key_range.KeyRange being processed.
filters: optional list of filters to apply to the query. Each filter is
a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>).
User filters are applied first.
"""
assert key_ranges is not None or ns_range is not None, (
"must specify one of 'key_ranges' or 'ns_range'")
assert key_ranges is None or ns_range is None, (
"can't specify both 'key_ranges ' and 'ns_range'")
self._entity_kind = entity_kind
# Reverse the KeyRanges so they can be processed in order as a stack of
# work items.
self._key_ranges = key_ranges and list(reversed(key_ranges))
self._ns_range = ns_range
self._batch_size = int(batch_size)
self._current_key_range = current_key_range
self._filters = filters | [
"def",
"__init__",
"(",
"self",
",",
"entity_kind",
",",
"key_ranges",
"=",
"None",
",",
"ns_range",
"=",
"None",
",",
"batch_size",
"=",
"_BATCH_SIZE",
",",
"current_key_range",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"assert",
"key_ranges",
"is",
"not",
"None",
"or",
"ns_range",
"is",
"not",
"None",
",",
"(",
"\"must specify one of 'key_ranges' or 'ns_range'\"",
")",
"assert",
"key_ranges",
"is",
"None",
"or",
"ns_range",
"is",
"None",
",",
"(",
"\"can't specify both 'key_ranges ' and 'ns_range'\"",
")",
"self",
".",
"_entity_kind",
"=",
"entity_kind",
"# Reverse the KeyRanges so they can be processed in order as a stack of",
"# work items.",
"self",
".",
"_key_ranges",
"=",
"key_ranges",
"and",
"list",
"(",
"reversed",
"(",
"key_ranges",
")",
")",
"self",
".",
"_ns_range",
"=",
"ns_range",
"self",
".",
"_batch_size",
"=",
"int",
"(",
"batch_size",
")",
"self",
".",
"_current_key_range",
"=",
"current_key_range",
"self",
".",
"_filters",
"=",
"filters"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py#L833-L869 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/variables.py | python | Variable.dtype | (self) | return self._variable.dtype | The `DType` of this variable. | The `DType` of this variable. | [
"The",
"DType",
"of",
"this",
"variable",
"."
] | def dtype(self):
"""The `DType` of this variable."""
return self._variable.dtype | [
"def",
"dtype",
"(",
"self",
")",
":",
"return",
"self",
".",
"_variable",
".",
"dtype"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/variables.py#L677-L679 | |
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/decoder.py | python | _VarintDecoder | (mask) | return DecodeVarint | Return an encoder for a basic varint value (does not include tag).
Decoded values will be bitwise-anded with the given mask before being
returned, e.g. to limit them to 32 bits. The returned decoder does not
take the usual "end" parameter -- the caller is expected to do bounds checking
after the fact (often the caller can defer such checking until later). The
decoder returns a (value, new_pos) pair. | Return an encoder for a basic varint value (does not include tag). | [
"Return",
"an",
"encoder",
"for",
"a",
"basic",
"varint",
"value",
"(",
"does",
"not",
"include",
"tag",
")",
"."
] | def _VarintDecoder(mask):
"""Return an encoder for a basic varint value (does not include tag).
Decoded values will be bitwise-anded with the given mask before being
returned, e.g. to limit them to 32 bits. The returned decoder does not
take the usual "end" parameter -- the caller is expected to do bounds checking
after the fact (often the caller can defer such checking until later). The
decoder returns a (value, new_pos) pair.
"""
local_ord = ord
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
b = local_ord(buffer[pos])
result |= ((b & 0x7f) << shift)
pos += 1
if not (b & 0x80):
result &= mask
return (result, pos)
shift += 7
if shift >= 64:
raise _DecodeError('Too many bytes when decoding varint.')
return DecodeVarint | [
"def",
"_VarintDecoder",
"(",
"mask",
")",
":",
"local_ord",
"=",
"ord",
"def",
"DecodeVarint",
"(",
"buffer",
",",
"pos",
")",
":",
"result",
"=",
"0",
"shift",
"=",
"0",
"while",
"1",
":",
"b",
"=",
"local_ord",
"(",
"buffer",
"[",
"pos",
"]",
")",
"result",
"|=",
"(",
"(",
"b",
"&",
"0x7f",
")",
"<<",
"shift",
")",
"pos",
"+=",
"1",
"if",
"not",
"(",
"b",
"&",
"0x80",
")",
":",
"result",
"&=",
"mask",
"return",
"(",
"result",
",",
"pos",
")",
"shift",
"+=",
"7",
"if",
"shift",
">=",
"64",
":",
"raise",
"_DecodeError",
"(",
"'Too many bytes when decoding varint.'",
")",
"return",
"DecodeVarint"
] | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/decoder.py#L101-L125 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/environment.py | python | load_extensions | (environment, extensions) | return result | Load the extensions from the list and bind it to the environment.
Returns a dict of instantiated environments. | Load the extensions from the list and bind it to the environment.
Returns a dict of instantiated environments. | [
"Load",
"the",
"extensions",
"from",
"the",
"list",
"and",
"bind",
"it",
"to",
"the",
"environment",
".",
"Returns",
"a",
"dict",
"of",
"instantiated",
"environments",
"."
] | def load_extensions(environment, extensions):
"""Load the extensions from the list and bind it to the environment.
Returns a dict of instantiated environments.
"""
result = {}
for extension in extensions:
if isinstance(extension, string_types):
extension = import_string(extension)
result[extension.identifier] = extension(environment)
return result | [
"def",
"load_extensions",
"(",
"environment",
",",
"extensions",
")",
":",
"result",
"=",
"{",
"}",
"for",
"extension",
"in",
"extensions",
":",
"if",
"isinstance",
"(",
"extension",
",",
"string_types",
")",
":",
"extension",
"=",
"import_string",
"(",
"extension",
")",
"result",
"[",
"extension",
".",
"identifier",
"]",
"=",
"extension",
"(",
"environment",
")",
"return",
"result"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/environment.py#L78-L87 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/cr/cr/actions/builder.py | python | Builder.GuessTargets | (self, context, target_name) | return difflib.get_close_matches(target_name, self.GetTargets(context)) | Returns a list of closest matching targets for a named target. | Returns a list of closest matching targets for a named target. | [
"Returns",
"a",
"list",
"of",
"closest",
"matching",
"targets",
"for",
"a",
"named",
"target",
"."
] | def GuessTargets(self, context, target_name):
"""Returns a list of closest matching targets for a named target."""
return difflib.get_close_matches(target_name, self.GetTargets(context)) | [
"def",
"GuessTargets",
"(",
"self",
",",
"context",
",",
"target_name",
")",
":",
"return",
"difflib",
".",
"get_close_matches",
"(",
"target_name",
",",
"self",
".",
"GetTargets",
"(",
"context",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/cr/cr/actions/builder.py#L62-L64 | |
luliyucoordinate/Leetcode | 96afcdc54807d1d184e881a075d1dbf3371e31fb | src/0230-Kth-Smallest-Element-in-a-BST/0230.py | python | Solution.kthSmallest | (self, root, k) | return result[k-1] | :type root: TreeNode
:type k: int
:rtype: int | :type root: TreeNode
:type k: int
:rtype: int | [
":",
"type",
"root",
":",
"TreeNode",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"int"
] | def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
result = list()
stack = list()
while stack or root:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
result.append(root.val)
if len(result) >= k:
break
root = root.right
return result[k-1] | [
"def",
"kthSmallest",
"(",
"self",
",",
"root",
",",
"k",
")",
":",
"result",
"=",
"list",
"(",
")",
"stack",
"=",
"list",
"(",
")",
"while",
"stack",
"or",
"root",
":",
"if",
"root",
":",
"stack",
".",
"append",
"(",
"root",
")",
"root",
"=",
"root",
".",
"left",
"else",
":",
"root",
"=",
"stack",
".",
"pop",
"(",
")",
"result",
".",
"append",
"(",
"root",
".",
"val",
")",
"if",
"len",
"(",
"result",
")",
">=",
"k",
":",
"break",
"root",
"=",
"root",
".",
"right",
"return",
"result",
"[",
"k",
"-",
"1",
"]"
] | https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0230-Kth-Smallest-Element-in-a-BST/0230.py#L8-L27 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Rect.IsEmpty | (*args, **kwargs) | return _core_.Rect_IsEmpty(*args, **kwargs) | IsEmpty(self) -> bool | IsEmpty(self) -> bool | [
"IsEmpty",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsEmpty(*args, **kwargs):
"""IsEmpty(self) -> bool"""
return _core_.Rect_IsEmpty(*args, **kwargs) | [
"def",
"IsEmpty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect_IsEmpty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1317-L1319 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Node.py | python | Node.exists | (self) | return os.path.exists(self.abspath()) | Returns whether the Node is present on the filesystem
:rtype: bool | Returns whether the Node is present on the filesystem | [
"Returns",
"whether",
"the",
"Node",
"is",
"present",
"on",
"the",
"filesystem"
] | def exists(self):
"""
Returns whether the Node is present on the filesystem
:rtype: bool
"""
return os.path.exists(self.abspath()) | [
"def",
"exists",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"abspath",
"(",
")",
")"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Node.py#L266-L272 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextParagraphLayoutBox.GetFloatCollector | (*args, **kwargs) | return _richtext.RichTextParagraphLayoutBox_GetFloatCollector(*args, **kwargs) | GetFloatCollector(self) -> wxRichTextFloatCollector | GetFloatCollector(self) -> wxRichTextFloatCollector | [
"GetFloatCollector",
"(",
"self",
")",
"-",
">",
"wxRichTextFloatCollector"
] | def GetFloatCollector(*args, **kwargs):
"""GetFloatCollector(self) -> wxRichTextFloatCollector"""
return _richtext.RichTextParagraphLayoutBox_GetFloatCollector(*args, **kwargs) | [
"def",
"GetFloatCollector",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraphLayoutBox_GetFloatCollector",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1862-L1864 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/tpu/feature_column.py | python | _is_running_on_cpu | () | return tpu_function.get_tpu_context().number_of_shards is None | Returns True if the current context is CPU model. | Returns True if the current context is CPU model. | [
"Returns",
"True",
"if",
"the",
"current",
"context",
"is",
"CPU",
"model",
"."
] | def _is_running_on_cpu():
"""Returns True if the current context is CPU model."""
return tpu_function.get_tpu_context().number_of_shards is None | [
"def",
"_is_running_on_cpu",
"(",
")",
":",
"return",
"tpu_function",
".",
"get_tpu_context",
"(",
")",
".",
"number_of_shards",
"is",
"None"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/feature_column.py#L670-L672 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/transforms/densify.py | python | Densify._apply_transform | (self, input_tensors, **kwargs) | return self.return_type(sparse_ops.sparse_to_dense(
s.indices, s.shape, s.values, default_value=self.default_value)) | Applies the transformation to the `transform_input`.
Args:
input_tensors: a list of Tensors representing the input to
the Transform.
**kwargs: Additional keyword arguments, unused here.
Returns:
A namedtuple of Tensors representing the transformed output. | Applies the transformation to the `transform_input`. | [
"Applies",
"the",
"transformation",
"to",
"the",
"transform_input",
"."
] | def _apply_transform(self, input_tensors, **kwargs):
"""Applies the transformation to the `transform_input`.
Args:
input_tensors: a list of Tensors representing the input to
the Transform.
**kwargs: Additional keyword arguments, unused here.
Returns:
A namedtuple of Tensors representing the transformed output.
"""
s = input_tensors[0]
# pylint: disable=not-callable
return self.return_type(sparse_ops.sparse_to_dense(
s.indices, s.shape, s.values, default_value=self.default_value)) | [
"def",
"_apply_transform",
"(",
"self",
",",
"input_tensors",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"input_tensors",
"[",
"0",
"]",
"# pylint: disable=not-callable",
"return",
"self",
".",
"return_type",
"(",
"sparse_ops",
".",
"sparse_to_dense",
"(",
"s",
".",
"indices",
",",
"s",
".",
"shape",
",",
"s",
".",
"values",
",",
"default_value",
"=",
"self",
".",
"default_value",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/transforms/densify.py#L50-L65 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | PrintData.SetFilename | (*args, **kwargs) | return _windows_.PrintData_SetFilename(*args, **kwargs) | SetFilename(self, String filename) | SetFilename(self, String filename) | [
"SetFilename",
"(",
"self",
"String",
"filename",
")"
] | def SetFilename(*args, **kwargs):
"""SetFilename(self, String filename)"""
return _windows_.PrintData_SetFilename(*args, **kwargs) | [
"def",
"SetFilename",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintData_SetFilename",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L4823-L4825 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/predictor/predictor_exporter.py | python | get_predictor_exporter_helper | (submodelNetName) | return pred_meta | constracting stub for the PredictorExportMeta
Only used to construct names to subfields,
such as calling to predict_net_name
Args:
submodelNetName - name of the model | constracting stub for the PredictorExportMeta
Only used to construct names to subfields,
such as calling to predict_net_name
Args:
submodelNetName - name of the model | [
"constracting",
"stub",
"for",
"the",
"PredictorExportMeta",
"Only",
"used",
"to",
"construct",
"names",
"to",
"subfields",
"such",
"as",
"calling",
"to",
"predict_net_name",
"Args",
":",
"submodelNetName",
"-",
"name",
"of",
"the",
"model"
] | def get_predictor_exporter_helper(submodelNetName):
""" constracting stub for the PredictorExportMeta
Only used to construct names to subfields,
such as calling to predict_net_name
Args:
submodelNetName - name of the model
"""
stub_net = core.Net(submodelNetName)
pred_meta = PredictorExportMeta(predict_net=stub_net,
parameters=[],
inputs=[],
outputs=[],
shapes=None,
name=submodelNetName,
extra_init_net=None)
return pred_meta | [
"def",
"get_predictor_exporter_helper",
"(",
"submodelNetName",
")",
":",
"stub_net",
"=",
"core",
".",
"Net",
"(",
"submodelNetName",
")",
"pred_meta",
"=",
"PredictorExportMeta",
"(",
"predict_net",
"=",
"stub_net",
",",
"parameters",
"=",
"[",
"]",
",",
"inputs",
"=",
"[",
"]",
",",
"outputs",
"=",
"[",
"]",
",",
"shapes",
"=",
"None",
",",
"name",
"=",
"submodelNetName",
",",
"extra_init_net",
"=",
"None",
")",
"return",
"pred_meta"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/predictor/predictor_exporter.py#L18-L33 | |
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/assembly_graph.py | python | AssemblyGraph.get_component_link_count | (self, component_segs) | return len(links) | Returns the total number of forward links in the component, not counting rev comp
duplicates. This function assumes the given segments make up a connected component - it
doesn't check. | Returns the total number of forward links in the component, not counting rev comp
duplicates. This function assumes the given segments make up a connected component - it
doesn't check. | [
"Returns",
"the",
"total",
"number",
"of",
"forward",
"links",
"in",
"the",
"component",
"not",
"counting",
"rev",
"comp",
"duplicates",
".",
"This",
"function",
"assumes",
"the",
"given",
"segments",
"make",
"up",
"a",
"connected",
"component",
"-",
"it",
"doesn",
"t",
"check",
"."
] | def get_component_link_count(self, component_segs):
"""
Returns the total number of forward links in the component, not counting rev comp
duplicates. This function assumes the given segments make up a connected component - it
doesn't check.
"""
links = set()
component_segs = set(component_segs) # positive segment numbers
for start, ends in self.forward_links.items():
for end in ends:
if abs(start) in component_segs and abs(end) in component_segs and \
(start, end) not in links and (-end, -start) not in links:
links.add((start, end))
return len(links) | [
"def",
"get_component_link_count",
"(",
"self",
",",
"component_segs",
")",
":",
"links",
"=",
"set",
"(",
")",
"component_segs",
"=",
"set",
"(",
"component_segs",
")",
"# positive segment numbers",
"for",
"start",
",",
"ends",
"in",
"self",
".",
"forward_links",
".",
"items",
"(",
")",
":",
"for",
"end",
"in",
"ends",
":",
"if",
"abs",
"(",
"start",
")",
"in",
"component_segs",
"and",
"abs",
"(",
"end",
")",
"in",
"component_segs",
"and",
"(",
"start",
",",
"end",
")",
"not",
"in",
"links",
"and",
"(",
"-",
"end",
",",
"-",
"start",
")",
"not",
"in",
"links",
":",
"links",
".",
"add",
"(",
"(",
"start",
",",
"end",
")",
")",
"return",
"len",
"(",
"links",
")"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph.py#L1725-L1738 | |
libornovax/master_thesis_code | 6eca474ed3cae673afde010caef338cf7349f839 | scripts/data/mitss2bbtxt.py | python | translate_file | (path_file, path_images, outfile, label) | Translates a single XML file with MIT Street Scenes labels and appends its output to the given
BBTXT file.
Input:
path_file: Path to the XML file to be translated
path_images: Path to the "Original" folder, which contains the images
outfile: File handle of the open output BBTXT file
label: Which class label should be extracted from the dataset (default None = all) | Translates a single XML file with MIT Street Scenes labels and appends its output to the given
BBTXT file. | [
"Translates",
"a",
"single",
"XML",
"file",
"with",
"MIT",
"Street",
"Scenes",
"labels",
"and",
"appends",
"its",
"output",
"to",
"the",
"given",
"BBTXT",
"file",
"."
] | def translate_file(path_file, path_images, outfile, label):
"""
Translates a single XML file with MIT Street Scenes labels and appends its output to the given
BBTXT file.
Input:
path_file: Path to the XML file to be translated
path_images: Path to the "Original" folder, which contains the images
outfile: File handle of the open output BBTXT file
label: Which class label should be extracted from the dataset (default None = all)
"""
e = xml.etree.ElementTree.parse(path_file).getroot()
path_image = os.path.join(path_images, e.find('filename').text.rstrip('\n').strip('\n'))
if not os.path.isfile(path_image):
print('WARNING: Image "%s" does not exist!'%(path_image))
# Go through all objects and extract their bounding boxes
for obj in e.findall('object'):
# There are some empty objects
if obj.find('name') is not None:
original_label = obj.find('name').text.rstrip('\n').strip('\n')
# Check label if required
if label is not None and MAPPING[LABELS[original_label]] != label: continue
# This dataset is annotated by polygon segmentations
xmin = 999999
ymin = 999999
xmax = 0
ymax = 0
for pt in obj.find('polygon').findall('pt'):
x = float(pt.find('x').text.rstrip('\n').strip('\n'))
y = float(pt.find('y').text.rstrip('\n').strip('\n'))
if x > xmax: xmax = x
if x < xmin: xmin = x
if y > ymax: ymax = y
if y < ymin: ymin = y
line_out = path_image + ' ' + str(LABELS[original_label]) + ' 1 '
line_out += str(xmin) + ' ' + str(ymin) + ' ' + str(xmax) + ' ' + str(ymax) + '\n'
outfile.write(line_out) | [
"def",
"translate_file",
"(",
"path_file",
",",
"path_images",
",",
"outfile",
",",
"label",
")",
":",
"e",
"=",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"parse",
"(",
"path_file",
")",
".",
"getroot",
"(",
")",
"path_image",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_images",
",",
"e",
".",
"find",
"(",
"'filename'",
")",
".",
"text",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"strip",
"(",
"'\\n'",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path_image",
")",
":",
"print",
"(",
"'WARNING: Image \"%s\" does not exist!'",
"%",
"(",
"path_image",
")",
")",
"# Go through all objects and extract their bounding boxes",
"for",
"obj",
"in",
"e",
".",
"findall",
"(",
"'object'",
")",
":",
"# There are some empty objects",
"if",
"obj",
".",
"find",
"(",
"'name'",
")",
"is",
"not",
"None",
":",
"original_label",
"=",
"obj",
".",
"find",
"(",
"'name'",
")",
".",
"text",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"strip",
"(",
"'\\n'",
")",
"# Check label if required",
"if",
"label",
"is",
"not",
"None",
"and",
"MAPPING",
"[",
"LABELS",
"[",
"original_label",
"]",
"]",
"!=",
"label",
":",
"continue",
"# This dataset is annotated by polygon segmentations",
"xmin",
"=",
"999999",
"ymin",
"=",
"999999",
"xmax",
"=",
"0",
"ymax",
"=",
"0",
"for",
"pt",
"in",
"obj",
".",
"find",
"(",
"'polygon'",
")",
".",
"findall",
"(",
"'pt'",
")",
":",
"x",
"=",
"float",
"(",
"pt",
".",
"find",
"(",
"'x'",
")",
".",
"text",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"strip",
"(",
"'\\n'",
")",
")",
"y",
"=",
"float",
"(",
"pt",
".",
"find",
"(",
"'y'",
")",
".",
"text",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"strip",
"(",
"'\\n'",
")",
")",
"if",
"x",
">",
"xmax",
":",
"xmax",
"=",
"x",
"if",
"x",
"<",
"xmin",
":",
"xmin",
"=",
"x",
"if",
"y",
">",
"ymax",
":",
"ymax",
"=",
"y",
"if",
"y",
"<",
"ymin",
":",
"ymin",
"=",
"y",
"line_out",
"=",
"path_image",
"+",
"' '",
"+",
"str",
"(",
"LABELS",
"[",
"original_label",
"]",
")",
"+",
"' 1 '",
"line_out",
"+=",
"str",
"(",
"xmin",
")",
"+",
"' '",
"+",
"str",
"(",
"ymin",
")",
"+",
"' '",
"+",
"str",
"(",
"xmax",
")",
"+",
"' '",
"+",
"str",
"(",
"ymax",
")",
"+",
"'\\n'",
"outfile",
".",
"write",
"(",
"line_out",
")"
] | https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/data/mitss2bbtxt.py#L54-L98 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextRenderer.EnumerateStandardBulletNames | (*args, **kwargs) | return _richtext.RichTextRenderer_EnumerateStandardBulletNames(*args, **kwargs) | EnumerateStandardBulletNames(self, wxArrayString bulletNames) -> bool | EnumerateStandardBulletNames(self, wxArrayString bulletNames) -> bool | [
"EnumerateStandardBulletNames",
"(",
"self",
"wxArrayString",
"bulletNames",
")",
"-",
">",
"bool"
] | def EnumerateStandardBulletNames(*args, **kwargs):
"""EnumerateStandardBulletNames(self, wxArrayString bulletNames) -> bool"""
return _richtext.RichTextRenderer_EnumerateStandardBulletNames(*args, **kwargs) | [
"def",
"EnumerateStandardBulletNames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextRenderer_EnumerateStandardBulletNames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2876-L2878 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/chardet/enums.py | python | SequenceLikelihood.get_num_categories | (cls) | return 4 | :returns: The number of likelihood categories in the enum. | :returns: The number of likelihood categories in the enum. | [
":",
"returns",
":",
"The",
"number",
"of",
"likelihood",
"categories",
"in",
"the",
"enum",
"."
] | def get_num_categories(cls):
""":returns: The number of likelihood categories in the enum."""
return 4 | [
"def",
"get_num_categories",
"(",
"cls",
")",
":",
"return",
"4"
] | 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/chardet/enums.py#L60-L62 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/util/zipalign.py | python | _SetAlignment | (zip_obj, zip_info, alignment) | Sets a ZipInfo's extra field such that the file will be aligned.
Args:
zip_obj: The ZipFile object that is being written.
zip_info: The ZipInfo object about to be written.
alignment: The amount of alignment (e.g. 4, or 4*1024). | Sets a ZipInfo's extra field such that the file will be aligned. | [
"Sets",
"a",
"ZipInfo",
"s",
"extra",
"field",
"such",
"that",
"the",
"file",
"will",
"be",
"aligned",
"."
] | def _SetAlignment(zip_obj, zip_info, alignment):
"""Sets a ZipInfo's extra field such that the file will be aligned.
Args:
zip_obj: The ZipFile object that is being written.
zip_info: The ZipInfo object about to be written.
alignment: The amount of alignment (e.g. 4, or 4*1024).
"""
cur_offset = zip_obj.fp.tell()
header_size = _FIXED_ZIP_HEADER_LEN + len(zip_info.filename)
padding_needed = (alignment - (
(cur_offset + header_size) % alignment)) % alignment
# Python writes |extra| to both the local file header and the central
# directory's file header. Android's zipalign tool writes only to the
# local file header, so there is more overhead in using python to align.
zip_info.extra = b'\0' * padding_needed | [
"def",
"_SetAlignment",
"(",
"zip_obj",
",",
"zip_info",
",",
"alignment",
")",
":",
"cur_offset",
"=",
"zip_obj",
".",
"fp",
".",
"tell",
"(",
")",
"header_size",
"=",
"_FIXED_ZIP_HEADER_LEN",
"+",
"len",
"(",
"zip_info",
".",
"filename",
")",
"padding_needed",
"=",
"(",
"alignment",
"-",
"(",
"(",
"cur_offset",
"+",
"header_size",
")",
"%",
"alignment",
")",
")",
"%",
"alignment",
"# Python writes |extra| to both the local file header and the central",
"# directory's file header. Android's zipalign tool writes only to the",
"# local file header, so there is more overhead in using python to align.",
"zip_info",
".",
"extra",
"=",
"b'\\0'",
"*",
"padding_needed"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/zipalign.py#L62-L79 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/robots/safety/python/moving_window_filter.py | python | MovingWindowFilter._neumaier_sum | (self, value: float) | Update the moving window sum using Neumaier's algorithm.
For more details please refer to:
https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements
Args:
value: The new value to be added to the window. | Update the moving window sum using Neumaier's algorithm. | [
"Update",
"the",
"moving",
"window",
"sum",
"using",
"Neumaier",
"s",
"algorithm",
"."
] | def _neumaier_sum(self, value: float):
"""Update the moving window sum using Neumaier's algorithm.
For more details please refer to:
https://en.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements
Args:
value: The new value to be added to the window.
"""
new_sum = self._sum + value
if abs(self._sum) >= abs(value):
# If self._sum is bigger, low-order digits of value are lost.
self._correction += (self._sum - new_sum) + value
else:
# low-order digits of sum are lost
self._correction += (value - new_sum) + self._sum
self._sum = new_sum | [
"def",
"_neumaier_sum",
"(",
"self",
",",
"value",
":",
"float",
")",
":",
"new_sum",
"=",
"self",
".",
"_sum",
"+",
"value",
"if",
"abs",
"(",
"self",
".",
"_sum",
")",
">=",
"abs",
"(",
"value",
")",
":",
"# If self._sum is bigger, low-order digits of value are lost.",
"self",
".",
"_correction",
"+=",
"(",
"self",
".",
"_sum",
"-",
"new_sum",
")",
"+",
"value",
"else",
":",
"# low-order digits of sum are lost",
"self",
".",
"_correction",
"+=",
"(",
"value",
"-",
"new_sum",
")",
"+",
"self",
".",
"_sum",
"self",
".",
"_sum",
"=",
"new_sum"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/robots/safety/python/moving_window_filter.py#L28-L46 | ||
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | build-support/iwyu/fix_includes.py | python | _NormalizeNamespaceForwardDeclareLines | (lines) | return retval[:-1] | Normalize' namespace lines in a list of output lines and return new list.
When suggesting new forward-declares to insert, iwyu uses the following
format, putting each class on its own line with all namespaces:
namespace foo { namespace bar { class A; } }
namespace foo { namespace bar { class B; } }
namespace foo { namespace bang { class C; } }
We convert this to 'normalized' form, which puts namespaces on their
own line and collects classes together:
namespace foo {
namespace bar {
class A;
class B;
} // namespace bar
namespace bang {
class C;
} // namespace bang
} // namespace foo
Non-namespace lines are left alone. Only adjacent namespace lines
from the input are merged.
Arguments:
lines: a list of output-lines -- that is, lines that are ready to
be emitted as-is to the output file.
Returns:
A new version of lines, with namespace lines normalized as above. | Normalize' namespace lines in a list of output lines and return new list. | [
"Normalize",
"namespace",
"lines",
"in",
"a",
"list",
"of",
"output",
"lines",
"and",
"return",
"new",
"list",
"."
] | def _NormalizeNamespaceForwardDeclareLines(lines):
"""'Normalize' namespace lines in a list of output lines and return new list.
When suggesting new forward-declares to insert, iwyu uses the following
format, putting each class on its own line with all namespaces:
namespace foo { namespace bar { class A; } }
namespace foo { namespace bar { class B; } }
namespace foo { namespace bang { class C; } }
We convert this to 'normalized' form, which puts namespaces on their
own line and collects classes together:
namespace foo {
namespace bar {
class A;
class B;
} // namespace bar
namespace bang {
class C;
} // namespace bang
} // namespace foo
Non-namespace lines are left alone. Only adjacent namespace lines
from the input are merged.
Arguments:
lines: a list of output-lines -- that is, lines that are ready to
be emitted as-is to the output file.
Returns:
A new version of lines, with namespace lines normalized as above.
"""
# iwyu input is very regular, which is nice.
iwyu_namespace_re = re.compile(r'namespace ([^{]*) { ')
iwyu_classname_re = re.compile(r'{ ([^{}]*) }')
retval = []
current_namespaces = []
# We append a blank line so the final namespace-closing happens "organically".
for line in lines + ['']:
namespaces_in_line = iwyu_namespace_re.findall(line)
differ_pos = _CommonPrefixLength(namespaces_in_line, current_namespaces)
namespaces_to_close = reversed(current_namespaces[differ_pos:])
namespaces_to_open = namespaces_in_line[differ_pos:]
retval.extend('} // namespace %s' % ns for ns in namespaces_to_close)
retval.extend('namespace %s {' % ns for ns in namespaces_to_open)
current_namespaces = namespaces_in_line
# Now add the current line. If we were a namespace line, it's the
# 'class' part of the line (everything but the 'namespace {'s).
if namespaces_in_line:
m = iwyu_classname_re.search(line)
if not m:
raise FixIncludesError('Malformed namespace line from iwyu: %s', line)
retval.append(m.group(1))
else:
retval.append(line)
assert retval and retval[-1] == '', 'What happened to our sentinel line?'
return retval[:-1] | [
"def",
"_NormalizeNamespaceForwardDeclareLines",
"(",
"lines",
")",
":",
"# iwyu input is very regular, which is nice.",
"iwyu_namespace_re",
"=",
"re",
".",
"compile",
"(",
"r'namespace ([^{]*) { '",
")",
"iwyu_classname_re",
"=",
"re",
".",
"compile",
"(",
"r'{ ([^{}]*) }'",
")",
"retval",
"=",
"[",
"]",
"current_namespaces",
"=",
"[",
"]",
"# We append a blank line so the final namespace-closing happens \"organically\".",
"for",
"line",
"in",
"lines",
"+",
"[",
"''",
"]",
":",
"namespaces_in_line",
"=",
"iwyu_namespace_re",
".",
"findall",
"(",
"line",
")",
"differ_pos",
"=",
"_CommonPrefixLength",
"(",
"namespaces_in_line",
",",
"current_namespaces",
")",
"namespaces_to_close",
"=",
"reversed",
"(",
"current_namespaces",
"[",
"differ_pos",
":",
"]",
")",
"namespaces_to_open",
"=",
"namespaces_in_line",
"[",
"differ_pos",
":",
"]",
"retval",
".",
"extend",
"(",
"'} // namespace %s'",
"%",
"ns",
"for",
"ns",
"in",
"namespaces_to_close",
")",
"retval",
".",
"extend",
"(",
"'namespace %s {'",
"%",
"ns",
"for",
"ns",
"in",
"namespaces_to_open",
")",
"current_namespaces",
"=",
"namespaces_in_line",
"# Now add the current line. If we were a namespace line, it's the",
"# 'class' part of the line (everything but the 'namespace {'s).",
"if",
"namespaces_in_line",
":",
"m",
"=",
"iwyu_classname_re",
".",
"search",
"(",
"line",
")",
"if",
"not",
"m",
":",
"raise",
"FixIncludesError",
"(",
"'Malformed namespace line from iwyu: %s'",
",",
"line",
")",
"retval",
".",
"append",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"retval",
".",
"append",
"(",
"line",
")",
"assert",
"retval",
"and",
"retval",
"[",
"-",
"1",
"]",
"==",
"''",
",",
"'What happened to our sentinel line?'",
"return",
"retval",
"[",
":",
"-",
"1",
"]"
] | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/iwyu/fix_includes.py#L1988-L2044 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/scimath.py | python | arccos | (x) | return nx.arccos(x) | Compute the inverse cosine of x.
Return the "principal value" (for a description of this, see
`numpy.arccos`) of the inverse cosine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[0, \\pi]`. Otherwise, the complex principle value is returned.
Parameters
----------
x : array_like or scalar
The value(s) whose arccos is (are) required.
Returns
-------
out : ndarray or scalar
The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so
is `out`, otherwise an array object is returned.
See Also
--------
numpy.arccos
Notes
-----
For an arccos() that returns ``NAN`` when real `x` is not in the
interval ``[-1,1]``, use `numpy.arccos`.
Examples
--------
>>> np.set_printoptions(precision=4)
>>> np.emath.arccos(1) # a scalar is returned
0.0
>>> np.emath.arccos([1,2])
array([0.-0.j , 0.-1.317j]) | Compute the inverse cosine of x. | [
"Compute",
"the",
"inverse",
"cosine",
"of",
"x",
"."
] | def arccos(x):
"""
Compute the inverse cosine of x.
Return the "principal value" (for a description of this, see
`numpy.arccos`) of the inverse cosine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[0, \\pi]`. Otherwise, the complex principle value is returned.
Parameters
----------
x : array_like or scalar
The value(s) whose arccos is (are) required.
Returns
-------
out : ndarray or scalar
The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so
is `out`, otherwise an array object is returned.
See Also
--------
numpy.arccos
Notes
-----
For an arccos() that returns ``NAN`` when real `x` is not in the
interval ``[-1,1]``, use `numpy.arccos`.
Examples
--------
>>> np.set_printoptions(precision=4)
>>> np.emath.arccos(1) # a scalar is returned
0.0
>>> np.emath.arccos([1,2])
array([0.-0.j , 0.-1.317j])
"""
x = _fix_real_abs_gt_1(x)
return nx.arccos(x) | [
"def",
"arccos",
"(",
"x",
")",
":",
"x",
"=",
"_fix_real_abs_gt_1",
"(",
"x",
")",
"return",
"nx",
".",
"arccos",
"(",
"x",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/scimath.py#L479-L520 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py | python | Dir.walk | (self, func, arg) | Walk this directory tree by calling the specified function
for each directory in the tree.
This behaves like the os.path.walk() function, but for in-memory
Node.FS.Dir objects. The function takes the same arguments as
the functions passed to os.path.walk():
func(arg, dirname, fnames)
Except that "dirname" will actually be the directory *Node*,
not the string. The '.' and '..' entries are excluded from
fnames. The fnames list may be modified in-place to filter the
subdirectories visited or otherwise impose a specific order.
The "arg" argument is always passed to func() and may be used
in any way (or ignored, passing None is common). | Walk this directory tree by calling the specified function
for each directory in the tree. | [
"Walk",
"this",
"directory",
"tree",
"by",
"calling",
"the",
"specified",
"function",
"for",
"each",
"directory",
"in",
"the",
"tree",
"."
] | def walk(self, func, arg):
"""
Walk this directory tree by calling the specified function
for each directory in the tree.
This behaves like the os.path.walk() function, but for in-memory
Node.FS.Dir objects. The function takes the same arguments as
the functions passed to os.path.walk():
func(arg, dirname, fnames)
Except that "dirname" will actually be the directory *Node*,
not the string. The '.' and '..' entries are excluded from
fnames. The fnames list may be modified in-place to filter the
subdirectories visited or otherwise impose a specific order.
The "arg" argument is always passed to func() and may be used
in any way (or ignored, passing None is common).
"""
entries = self.entries
names = list(entries.keys())
names.remove('.')
names.remove('..')
func(arg, self, names)
for dirname in [n for n in names if isinstance(entries[n], Dir)]:
entries[dirname].walk(func, arg) | [
"def",
"walk",
"(",
"self",
",",
"func",
",",
"arg",
")",
":",
"entries",
"=",
"self",
".",
"entries",
"names",
"=",
"list",
"(",
"entries",
".",
"keys",
"(",
")",
")",
"names",
".",
"remove",
"(",
"'.'",
")",
"names",
".",
"remove",
"(",
"'..'",
")",
"func",
"(",
"arg",
",",
"self",
",",
"names",
")",
"for",
"dirname",
"in",
"[",
"n",
"for",
"n",
"in",
"names",
"if",
"isinstance",
"(",
"entries",
"[",
"n",
"]",
",",
"Dir",
")",
"]",
":",
"entries",
"[",
"dirname",
"]",
".",
"walk",
"(",
"func",
",",
"arg",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L2107-L2131 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.