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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.copy | (self) | return self.__class__(self) | od.copy() -> a shallow copy of od | od.copy() -> a shallow copy of od | [
"od",
".",
"copy",
"()",
"-",
">",
"a",
"shallow",
"copy",
"of",
"od"
] | def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L249-L251 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMT_SENSITIVE.__init__ | (self, authValue = None, seedValue = None, sensitive = None) | AuthValue shall not be larger than the size of the digest produced
by the nameAlg of the object. seedValue shall be the size of the digest
produced by the nameAlg of the object.
Attributes:
authValue (bytes): User authorization data
The authValue may be a zero-length string.
seedValue (bytes): For a parent object, the optional protection
seed; for other objects, the obfuscation value
sensitive (TPMU_SENSITIVE_COMPOSITE): The type-specific private data
One of: TPM2B_PRIVATE_KEY_RSA, TPM2B_ECC_PARAMETER,
TPM2B_SENSITIVE_DATA, TPM2B_SYM_KEY, TPM2B_PRIVATE_VENDOR_SPECIFIC. | AuthValue shall not be larger than the size of the digest produced
by the nameAlg of the object. seedValue shall be the size of the digest
produced by the nameAlg of the object. | [
"AuthValue",
"shall",
"not",
"be",
"larger",
"than",
"the",
"size",
"of",
"the",
"digest",
"produced",
"by",
"the",
"nameAlg",
"of",
"the",
"object",
".",
"seedValue",
"shall",
"be",
"the",
"size",
"of",
"the",
"digest",
"produced",
"by",
"the",
"nameAlg",... | def __init__(self, authValue = None, seedValue = None, sensitive = None):
""" AuthValue shall not be larger than the size of the digest produced
by the nameAlg of the object. seedValue shall be the size of the digest
produced by the nameAlg of the object.
Attributes:
authValue (bytes): User authorization data
The authValue may be a zero-length string.
seedValue (bytes): For a parent object, the optional protection
seed; for other objects, the obfuscation value
sensitive (TPMU_SENSITIVE_COMPOSITE): The type-specific private data
One of: TPM2B_PRIVATE_KEY_RSA, TPM2B_ECC_PARAMETER,
TPM2B_SENSITIVE_DATA, TPM2B_SYM_KEY, TPM2B_PRIVATE_VENDOR_SPECIFIC.
"""
self.authValue = authValue
self.seedValue = seedValue
self.sensitive = sensitive | [
"def",
"__init__",
"(",
"self",
",",
"authValue",
"=",
"None",
",",
"seedValue",
"=",
"None",
",",
"sensitive",
"=",
"None",
")",
":",
"self",
".",
"authValue",
"=",
"authValue",
"self",
".",
"seedValue",
"=",
"seedValue",
"self",
".",
"sensitive",
"=",
... | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L8355-L8371 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/_multivariate.py | python | _lnB | (alpha) | return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha)) | r"""
Internal helper function to compute the log of the useful quotient
.. math::
B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}{\Gamma\left(\sum_{i=1}^{K}\alpha_i\right)}
Parameters
----------
%(_dirichlet_doc_default_callparams)s
Returns
-------
B : scalar
Helper quotient, internal use only | r"""
Internal helper function to compute the log of the useful quotient | [
"r",
"Internal",
"helper",
"function",
"to",
"compute",
"the",
"log",
"of",
"the",
"useful",
"quotient"
] | def _lnB(alpha):
r"""
Internal helper function to compute the log of the useful quotient
.. math::
B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}{\Gamma\left(\sum_{i=1}^{K}\alpha_i\right)}
Parameters
----------
%(_dirichlet_doc_default_callparams)s
Returns
-------
B : scalar
Helper quotient, internal use only
"""
return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha)) | [
"def",
"_lnB",
"(",
"alpha",
")",
":",
"return",
"np",
".",
"sum",
"(",
"gammaln",
"(",
"alpha",
")",
")",
"-",
"gammaln",
"(",
"np",
".",
"sum",
"(",
"alpha",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L1111-L1129 | |
synfig/synfig | a5ec91db5b751dc12e4400ccfb5c063fd6d2d928 | synfig-studio/plugins/lottie-exporter/common/Bline.py | python | Bline.get_loop | (self) | return loop | Returns whether the bline is looped or not | Returns whether the bline is looped or not | [
"Returns",
"whether",
"the",
"bline",
"is",
"looped",
"or",
"not"
] | def get_loop(self):
"""
Returns whether the bline is looped or not
"""
loop = False
if "loop" in self.bline.keys():
v = self.bline.attrib["loop"]
if v == "true":
loop = True
return loop | [
"def",
"get_loop",
"(",
"self",
")",
":",
"loop",
"=",
"False",
"if",
"\"loop\"",
"in",
"self",
".",
"bline",
".",
"keys",
"(",
")",
":",
"v",
"=",
"self",
".",
"bline",
".",
"attrib",
"[",
"\"loop\"",
"]",
"if",
"v",
"==",
"\"true\"",
":",
"loop... | https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Bline.py#L74-L83 | |
LLNL/Umpire | 46eb4210d9556f71dc085e8cb03e2ff58e67ae37 | scripts/gitlab/generate_host_configs.py | python | parse_args | () | return opts, extras | Parses args from command line | Parses args from command line | [
"Parses",
"args",
"from",
"command",
"line"
] | def parse_args():
"""
Parses args from command line
"""
parser = OptionParser()
parser.add_option("--spec-filter",
dest="spec-filter",
default=None,
help="Partial spec to match")
parser.add_option("--forced-spec",
dest="forced-spec",
default=False,
help="Force the use of this spec without checking spec list")
parser.add_option("--shm",
dest="use_shm",
default=False,
help="Use Spack in shared memory")
opts, extras = parser.parse_args()
opts = vars(opts)
return opts, extras | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"\"--spec-filter\"",
",",
"dest",
"=",
"\"spec-filter\"",
",",
"default",
"=",
"None",
",",
"help",
"=",
"\"Partial spec to match\"",
")",
"parser",
... | https://github.com/LLNL/Umpire/blob/46eb4210d9556f71dc085e8cb03e2ff58e67ae37/scripts/gitlab/generate_host_configs.py#L63-L86 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py | python | Styler.export | (self) | return self._todo | Export the styles to applied to the current Styler.
Can be applied to a second style with ``Styler.use``.
Returns
-------
styles : list
See Also
--------
Styler.use | Export the styles to applied to the current Styler. | [
"Export",
"the",
"styles",
"to",
"applied",
"to",
"the",
"current",
"Styler",
"."
] | def export(self):
"""
Export the styles to applied to the current Styler.
Can be applied to a second style with ``Styler.use``.
Returns
-------
styles : list
See Also
--------
Styler.use
"""
return self._todo | [
"def",
"export",
"(",
"self",
")",
":",
"return",
"self",
".",
"_todo"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py#L815-L829 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntIntVV.DelLast | (self) | return _snap.TIntIntVV_DelLast(self) | DelLast(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > * | DelLast(TIntIntVV self) | [
"DelLast",
"(",
"TIntIntVV",
"self",
")"
] | def DelLast(self):
"""
DelLast(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_DelLast(self) | [
"def",
"DelLast",
"(",
"self",
")",
":",
"return",
"_snap",
".",
"TIntIntVV_DelLast",
"(",
"self",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L16972-L16980 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py | python | Set.__iand__ | (self, other) | return self | Update a set with the intersection of itself and another. | Update a set with the intersection of itself and another. | [
"Update",
"a",
"set",
"with",
"the",
"intersection",
"of",
"itself",
"and",
"another",
"."
] | def __iand__(self, other):
"""Update a set with the intersection of itself and another."""
self._binary_sanity_check(other)
self._data = (self & other)._data
return self | [
"def",
"__iand__",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_binary_sanity_check",
"(",
"other",
")",
"self",
".",
"_data",
"=",
"(",
"self",
"&",
"other",
")",
".",
"_data",
"return",
"self"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py#L438-L442 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/layers/feature_column.py | python | _reshape_real_valued_tensor | (input_tensor, output_rank, column_name=None) | return layers._inner_flatten(input_tensor, output_rank) | Reshaping logic for dense, numeric `Tensors`.
Follows the following rules:
1. If `output_rank > input_rank + 1` raise a `ValueError`.
2. If `output_rank == input_rank + 1`, expand `input_tensor` by one
dimension and return
3. If `output_rank == input_rank`, return `input_tensor`.
4. If `output_rank < input_rank`, flatten the inner dimensions of
`input_tensor` and return a `Tensor` with `output_rank`
Args:
input_tensor: a dense `Tensor` to be reshaped.
output_rank: the desired rank of the reshaped `Tensor`.
column_name: (optional) the name of the associated column. Used for error
messages.
Returns:
A `Tensor` with the same entries as `input_tensor` and rank `output_rank`.
Raises:
ValueError: if `output_rank > input_rank + 1`. | Reshaping logic for dense, numeric `Tensors`. | [
"Reshaping",
"logic",
"for",
"dense",
"numeric",
"Tensors",
"."
] | def _reshape_real_valued_tensor(input_tensor, output_rank, column_name=None):
"""Reshaping logic for dense, numeric `Tensors`.
Follows the following rules:
1. If `output_rank > input_rank + 1` raise a `ValueError`.
2. If `output_rank == input_rank + 1`, expand `input_tensor` by one
dimension and return
3. If `output_rank == input_rank`, return `input_tensor`.
4. If `output_rank < input_rank`, flatten the inner dimensions of
`input_tensor` and return a `Tensor` with `output_rank`
Args:
input_tensor: a dense `Tensor` to be reshaped.
output_rank: the desired rank of the reshaped `Tensor`.
column_name: (optional) the name of the associated column. Used for error
messages.
Returns:
A `Tensor` with the same entries as `input_tensor` and rank `output_rank`.
Raises:
ValueError: if `output_rank > input_rank + 1`.
"""
input_rank = input_tensor.get_shape().ndims
if input_rank is not None:
if output_rank > input_rank + 1:
error_string = ("Rank of input Tensor ({}) should be the same as "
"output_rank ({}). For example, sequence data should "
"typically be 3 dimensional (rank 3) while non-sequence "
"data is typically 2 dimensional (rank 2).".format(
input_rank, output_rank))
if column_name is not None:
error_string = ("Error while processing column {}.".format(column_name)
+ error_string)
raise ValueError(error_string)
if output_rank == input_rank + 1:
logging.warning(
"Rank of input Tensor ({}) should be the same as output_rank ({}) "
"for column. Will attempt to expand dims. It is highly recommended "
"that you resize your input, as this behavior may change.".format(
input_rank, output_rank))
return array_ops.expand_dims(input_tensor, -1, name="expand_dims")
if output_rank == input_rank:
return input_tensor
# Here, either `input_rank` is unknown or it is greater than `output_rank`.
return layers._inner_flatten(input_tensor, output_rank) | [
"def",
"_reshape_real_valued_tensor",
"(",
"input_tensor",
",",
"output_rank",
",",
"column_name",
"=",
"None",
")",
":",
"input_rank",
"=",
"input_tensor",
".",
"get_shape",
"(",
")",
".",
"ndims",
"if",
"input_rank",
"is",
"not",
"None",
":",
"if",
"output_r... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/feature_column.py#L1547-L1590 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/sgmllib.py | python | SGMLParser.convert_entityref | (self, name) | Convert entity references.
As an alternative to overriding this method; one can tailor the
results by setting up the self.entitydefs mapping appropriately. | Convert entity references. | [
"Convert",
"entity",
"references",
"."
] | def convert_entityref(self, name):
"""Convert entity references.
As an alternative to overriding this method; one can tailor the
results by setting up the self.entitydefs mapping appropriately.
"""
table = self.entitydefs
if name in table:
return table[name]
else:
return | [
"def",
"convert_entityref",
"(",
"self",
",",
"name",
")",
":",
"table",
"=",
"self",
".",
"entitydefs",
"if",
"name",
"in",
"table",
":",
"return",
"table",
"[",
"name",
"]",
"else",
":",
"return"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/sgmllib.py#L418-L428 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/integer.py | python | IntegerArray._values_for_argsort | (self) | return data | Return values for sorting.
Returns
-------
ndarray
The transformed values should maintain the ordering between values
within the array.
See Also
--------
ExtensionArray.argsort | Return values for sorting. | [
"Return",
"values",
"for",
"sorting",
"."
] | def _values_for_argsort(self) -> np.ndarray:
"""Return values for sorting.
Returns
-------
ndarray
The transformed values should maintain the ordering between values
within the array.
See Also
--------
ExtensionArray.argsort
"""
data = self._data.copy()
data[self._mask] = data.min() - 1
return data | [
"def",
"_values_for_argsort",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"data",
"=",
"self",
".",
"_data",
".",
"copy",
"(",
")",
"data",
"[",
"self",
".",
"_mask",
"]",
"=",
"data",
".",
"min",
"(",
")",
"-",
"1",
"return",
"data"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/integer.py#L488-L503 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Tools/c_config.py | python | undefine | (self, key, comment='') | Removes a global define from ``conf.env.DEFINES``
:param key: define name
:type key: string | Removes a global define from ``conf.env.DEFINES`` | [
"Removes",
"a",
"global",
"define",
"from",
"conf",
".",
"env",
".",
"DEFINES"
] | def undefine(self, key, comment=''):
"""
Removes a global define from ``conf.env.DEFINES``
:param key: define name
:type key: string
"""
assert isinstance(key, str)
if not key:
return
ban = key + '='
lst = [x for x in self.env.DEFINES if not x.startswith(ban)]
self.env.DEFINES = lst
self.env.append_unique(DEFKEYS, key)
self.set_define_comment(key, comment) | [
"def",
"undefine",
"(",
"self",
",",
"key",
",",
"comment",
"=",
"''",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"if",
"not",
"key",
":",
"return",
"ban",
"=",
"key",
"+",
"'='",
"lst",
"=",
"[",
"x",
"for",
"x",
"in",
"sel... | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/c_config.py#L773-L787 | ||
WenmuZhou/PSENet.pytorch | f760c2f4938726a2d00efaf5e5b28218323c44ca | cal_recall/rrc_evaluation_funcs.py | python | validate_tl_line | (line,LTRB=True,withTranscription=True,withConfidence=True,imWidth=0,imHeight=0) | Validate the format of the line. If the line is not valid an exception will be raised.
If maxWidth and maxHeight are specified, all points must be inside the imgage bounds.
Posible values are:
LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription]
LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription] | Validate the format of the line. If the line is not valid an exception will be raised.
If maxWidth and maxHeight are specified, all points must be inside the imgage bounds.
Posible values are:
LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription]
LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription] | [
"Validate",
"the",
"format",
"of",
"the",
"line",
".",
"If",
"the",
"line",
"is",
"not",
"valid",
"an",
"exception",
"will",
"be",
"raised",
".",
"If",
"maxWidth",
"and",
"maxHeight",
"are",
"specified",
"all",
"points",
"must",
"be",
"inside",
"the",
"i... | def validate_tl_line(line,LTRB=True,withTranscription=True,withConfidence=True,imWidth=0,imHeight=0):
"""
Validate the format of the line. If the line is not valid an exception will be raised.
If maxWidth and maxHeight are specified, all points must be inside the imgage bounds.
Posible values are:
LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription]
LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription]
"""
get_tl_line_values(line,LTRB,withTranscription,withConfidence,imWidth,imHeight) | [
"def",
"validate_tl_line",
"(",
"line",
",",
"LTRB",
"=",
"True",
",",
"withTranscription",
"=",
"True",
",",
"withConfidence",
"=",
"True",
",",
"imWidth",
"=",
"0",
",",
"imHeight",
"=",
"0",
")",
":",
"get_tl_line_values",
"(",
"line",
",",
"LTRB",
",... | https://github.com/WenmuZhou/PSENet.pytorch/blob/f760c2f4938726a2d00efaf5e5b28218323c44ca/cal_recall/rrc_evaluation_funcs.py#L140-L148 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/environment.py | python | Environment._tokenize | (self, source, name, filename=None, state=None) | return stream | Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. | Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. | [
"Called",
"by",
"the",
"parser",
"to",
"do",
"the",
"preprocessing",
"and",
"filtering",
"for",
"all",
"the",
"extensions",
".",
"Returns",
"a",
":",
"class",
":",
"~jinja2",
".",
"lexer",
".",
"TokenStream",
"."
] | def _tokenize(self, source, name, filename=None, state=None):
"""Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
"""
source = self.preprocess(source, name, filename)
stream = self.lexer.tokenize(source, name, filename, state)
for ext in self.iter_extensions():
stream = ext.filter_stream(stream)
if not isinstance(stream, TokenStream):
stream = TokenStream(stream, name, filename)
return stream | [
"def",
"_tokenize",
"(",
"self",
",",
"source",
",",
"name",
",",
"filename",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"source",
"=",
"self",
".",
"preprocess",
"(",
"source",
",",
"name",
",",
"filename",
")",
"stream",
"=",
"self",
".",
... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/environment.py#L524-L534 | |
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/pypack/modulegraph/pkg_resources.py | python | WorkingSet.add | (self, dist, entry=None, insert=True) | Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set's ``.entries`` (if it wasn't already present).
`dist` is only added to the working set if it's for a project that
doesn't already have a distribution in the set. If it's added, any
callbacks registered with the ``subscribe()`` method will be called. | Add `dist` to working set, associated with `entry` | [
"Add",
"dist",
"to",
"working",
"set",
"associated",
"with",
"entry"
] | def add(self, dist, entry=None, insert=True):
"""Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set's ``.entries`` (if it wasn't already present).
`dist` is only added to the working set if it's for a project that
doesn't already have a distribution in the set. If it's added, any
callbacks registered with the ``subscribe()`` method will be called.
"""
if insert:
dist.insert_on(self.entries, entry)
if entry is None:
entry = dist.location
keys = self.entry_keys.setdefault(entry,[])
keys2 = self.entry_keys.setdefault(dist.location,[])
if dist.key in self.by_key:
return # ignore hidden distros
self.by_key[dist.key] = dist
if dist.key not in keys:
keys.append(dist.key)
if dist.key not in keys2:
keys2.append(dist.key)
self._added_new(dist) | [
"def",
"add",
"(",
"self",
",",
"dist",
",",
"entry",
"=",
"None",
",",
"insert",
"=",
"True",
")",
":",
"if",
"insert",
":",
"dist",
".",
"insert_on",
"(",
"self",
".",
"entries",
",",
"entry",
")",
"if",
"entry",
"is",
"None",
":",
"entry",
"="... | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/modulegraph/pkg_resources.py#L386-L412 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/graph_editor/util.py | python | get_generating_ops | (ts) | return [t.op for t in ts] | Return all the generating ops of the tensors in ts.
Args:
ts: a list of tf.Tensor
Returns:
A list of all the generating tf.Operation of the tensors in ts.
Raises:
TypeError: if ts cannot be converted to a list of tf.Tensor. | Return all the generating ops of the tensors in ts. | [
"Return",
"all",
"the",
"generating",
"ops",
"of",
"the",
"tensors",
"in",
"ts",
"."
] | def get_generating_ops(ts):
"""Return all the generating ops of the tensors in ts.
Args:
ts: a list of tf.Tensor
Returns:
A list of all the generating tf.Operation of the tensors in ts.
Raises:
TypeError: if ts cannot be converted to a list of tf.Tensor.
"""
ts = make_list_of_t(ts, allow_graph=False)
return [t.op for t in ts] | [
"def",
"get_generating_ops",
"(",
"ts",
")",
":",
"ts",
"=",
"make_list_of_t",
"(",
"ts",
",",
"allow_graph",
"=",
"False",
")",
"return",
"[",
"t",
".",
"op",
"for",
"t",
"in",
"ts",
"]"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/graph_editor/util.py#L199-L210 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/operator.py | python | ior | (a, b) | return a | Same as a |= b. | Same as a |= b. | [
"Same",
"as",
"a",
"|",
"=",
"b",
"."
] | def ior(a, b):
"Same as a |= b."
a |= b
return a | [
"def",
"ior",
"(",
"a",
",",
"b",
")",
":",
"a",
"|=",
"b",
"return",
"a"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/operator.py#L380-L383 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/installer/util/prebuild/create_string_rc.py | python | GrdHandler.__OnCloseMessage | (self) | Invoked at the end of a message. | Invoked at the end of a message. | [
"Invoked",
"at",
"the",
"end",
"of",
"a",
"message",
"."
] | def __OnCloseMessage(self):
"""Invoked at the end of a message."""
if self.__IsExtractingMessage():
self.messages[self.__message_name] = ''.join(self.__text_scraps).strip()
self.__message_name = None
self.__text_scraps = []
self.__characters_callback = None | [
"def",
"__OnCloseMessage",
"(",
"self",
")",
":",
"if",
"self",
".",
"__IsExtractingMessage",
"(",
")",
":",
"self",
".",
"messages",
"[",
"self",
".",
"__message_name",
"]",
"=",
"''",
".",
"join",
"(",
"self",
".",
"__text_scraps",
")",
".",
"strip",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/installer/util/prebuild/create_string_rc.py#L142-L148 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | Dialog.SetEscapeId | (*args, **kwargs) | return _windows_.Dialog_SetEscapeId(*args, **kwargs) | SetEscapeId(self, int escapeId) | SetEscapeId(self, int escapeId) | [
"SetEscapeId",
"(",
"self",
"int",
"escapeId",
")"
] | def SetEscapeId(*args, **kwargs):
"""SetEscapeId(self, int escapeId)"""
return _windows_.Dialog_SetEscapeId(*args, **kwargs) | [
"def",
"SetEscapeId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Dialog_SetEscapeId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L761-L763 | |
zhaoweicai/mscnn | 534bcac5710a579d60827f192035f7eef6d8c585 | scripts/cpp_lint.py | python | Match | (pattern, s) | return _regexp_compile_cache[pattern].match(s) | Matches the string with the pattern, caching the compiled regexp. | Matches the string with the pattern, caching the compiled regexp. | [
"Matches",
"the",
"string",
"with",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | def Match(pattern, s):
"""Matches the string with the pattern, caching the compiled regexp."""
# The regexp compilation caching is inlined in both Match and Search for
# performance reasons; factoring it out into a separate function turns out
# to be noticeably expensive.
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].match(s) | [
"def",
"Match",
"(",
"pattern",
",",
"s",
")",
":",
"# The regexp compilation caching is inlined in both Match and Search for",
"# performance reasons; factoring it out into a separate function turns out",
"# to be noticeably expensive.",
"if",
"pattern",
"not",
"in",
"_regexp_compile_... | https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/scripts/cpp_lint.py#L515-L522 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/frame.py | python | Frame.ceil | (self) | return self._unaryop("ceil") | Rounds each value upward to the smallest integral value not less
than the original.
Returns
-------
DataFrame or Series
Ceiling value of each element.
Examples
--------
>>> import cudf
>>> series = cudf.Series([1.1, 2.8, 3.5, 4.5])
>>> series
0 1.1
1 2.8
2 3.5
3 4.5
dtype: float64
>>> series.ceil()
0 2.0
1 3.0
2 4.0
3 5.0
dtype: float64 | Rounds each value upward to the smallest integral value not less
than the original. | [
"Rounds",
"each",
"value",
"upward",
"to",
"the",
"smallest",
"integral",
"value",
"not",
"less",
"than",
"the",
"original",
"."
] | def ceil(self):
"""
Rounds each value upward to the smallest integral value not less
than the original.
Returns
-------
DataFrame or Series
Ceiling value of each element.
Examples
--------
>>> import cudf
>>> series = cudf.Series([1.1, 2.8, 3.5, 4.5])
>>> series
0 1.1
1 2.8
2 3.5
3 4.5
dtype: float64
>>> series.ceil()
0 2.0
1 3.0
2 4.0
3 5.0
dtype: float64
"""
warnings.warn(
"Series.ceil and DataFrame.ceil are deprecated and will be "
"removed in the future",
FutureWarning,
)
return self._unaryop("ceil") | [
"def",
"ceil",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Series.ceil and DataFrame.ceil are deprecated and will be \"",
"\"removed in the future\"",
",",
"FutureWarning",
",",
")",
"return",
"self",
".",
"_unaryop",
"(",
"\"ceil\"",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/frame.py#L3212-L3246 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/calendar.py | python | Calendar.iterweekdays | (self) | Return an iterator for one week of weekday numbers starting with the
configured first one. | Return an iterator for one week of weekday numbers starting with the
configured first one. | [
"Return",
"an",
"iterator",
"for",
"one",
"week",
"of",
"weekday",
"numbers",
"starting",
"with",
"the",
"configured",
"first",
"one",
"."
] | def iterweekdays(self):
"""
Return an iterator for one week of weekday numbers starting with the
configured first one.
"""
for i in range(self.firstweekday, self.firstweekday + 7):
yield i%7 | [
"def",
"iterweekdays",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"firstweekday",
",",
"self",
".",
"firstweekday",
"+",
"7",
")",
":",
"yield",
"i",
"%",
"7"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/calendar.py#L165-L171 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/locators.py | python | SimpleScrapingLocator.get_page | (self, url) | return result | Get the HTML for an URL, possibly from an in-memory cache.
XXX TODO Note: this cache is never actually cleared. It's assumed that
the data won't get stale over the lifetime of a locator instance (not
necessarily true for the default_locator). | Get the HTML for an URL, possibly from an in-memory cache. | [
"Get",
"the",
"HTML",
"for",
"an",
"URL",
"possibly",
"from",
"an",
"in",
"-",
"memory",
"cache",
"."
] | def get_page(self, url):
"""
Get the HTML for an URL, possibly from an in-memory cache.
XXX TODO Note: this cache is never actually cleared. It's assumed that
the data won't get stale over the lifetime of a locator instance (not
necessarily true for the default_locator).
"""
# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
scheme, netloc, path, _, _, _ = urlparse(url)
if scheme == 'file' and os.path.isdir(url2pathname(path)):
url = urljoin(ensure_slash(url), 'index.html')
if url in self._page_cache:
result = self._page_cache[url]
logger.debug('Returning %s from cache: %s', url, result)
else:
host = netloc.split(':', 1)[0]
result = None
if host in self._bad_hosts:
logger.debug('Skipping %s due to bad host %s', url, host)
else:
req = Request(url, headers={'Accept-encoding': 'identity'})
try:
logger.debug('Fetching %s', url)
resp = self.opener.open(req, timeout=self.timeout)
logger.debug('Fetched %s', url)
headers = resp.info()
content_type = headers.get('Content-Type', '')
if HTML_CONTENT_TYPE.match(content_type):
final_url = resp.geturl()
data = resp.read()
encoding = headers.get('Content-Encoding')
if encoding:
decoder = self.decoders[encoding] # fail if not found
data = decoder(data)
encoding = 'utf-8'
m = CHARSET.search(content_type)
if m:
encoding = m.group(1)
try:
data = data.decode(encoding)
except UnicodeError: # pragma: no cover
data = data.decode('latin-1') # fallback
result = Page(data, final_url)
self._page_cache[final_url] = result
except HTTPError as e:
if e.code != 404:
logger.exception('Fetch failed: %s: %s', url, e)
except URLError as e: # pragma: no cover
logger.exception('Fetch failed: %s: %s', url, e)
with self._lock:
self._bad_hosts.add(host)
except Exception as e: # pragma: no cover
logger.exception('Fetch failed: %s: %s', url, e)
finally:
self._page_cache[url] = result # even if None (failure)
return result | [
"def",
"get_page",
"(",
"self",
",",
"url",
")",
":",
"# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api",
"scheme",
",",
"netloc",
",",
"path",
",",
"_",
",",
"_",
",",
"_",
"=",
"urlparse",
"(",
"url",
")",
"if",
"scheme",
"==",
"'file'... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/locators.py#L762-L819 | |
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/custom/custom_operation.py | python | CustomOperation.__getattr__ | (self, attr) | Pass through attributes/methods of the wrapped object. | Pass through attributes/methods of the wrapped object. | [
"Pass",
"through",
"attributes",
"/",
"methods",
"of",
"the",
"wrapped",
"object",
"."
] | def __getattr__(self, attr):
"""Pass through attributes/methods of the wrapped object."""
try:
return super().__getattr__(attr)
except AttributeError:
try:
return getattr(self._action, attr)
except AttributeError:
raise AttributeError("{} object has no attribute {}".format(
type(self), attr)) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"try",
":",
"return",
"super",
"(",
")",
".",
"__getattr__",
"(",
"attr",
")",
"except",
"AttributeError",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"_action",
",",
"attr",
")",
... | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/custom/custom_operation.py#L59-L68 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py | python | conv_1d | (
I=TensorDef(T1, S.OW + S.KW),
K=TensorDef(T2, S.KW),
O=TensorDef(U, S.OW, output=True)) | Performs 1-D convolution with no channels.
Numeric casting is performed on the operands to the inner multiply, promoting
them to the same data type as the accumulator/output. | Performs 1-D convolution with no channels. | [
"Performs",
"1",
"-",
"D",
"convolution",
"with",
"no",
"channels",
"."
] | def conv_1d(
I=TensorDef(T1, S.OW + S.KW),
K=TensorDef(T2, S.KW),
O=TensorDef(U, S.OW, output=True)):
"""Performs 1-D convolution with no channels.
Numeric casting is performed on the operands to the inner multiply, promoting
them to the same data type as the accumulator/output.
"""
implements(ConvolutionOpInterface)
domain(D.ow, D.kw)
O[D.ow] += TypeFn.cast(U, I[D.ow + D.kw]) * TypeFn.cast(U, K[D.kw]) | [
"def",
"conv_1d",
"(",
"I",
"=",
"TensorDef",
"(",
"T1",
",",
"S",
".",
"OW",
"+",
"S",
".",
"KW",
")",
",",
"K",
"=",
"TensorDef",
"(",
"T2",
",",
"S",
".",
"KW",
")",
",",
"O",
"=",
"TensorDef",
"(",
"U",
",",
"S",
".",
"OW",
",",
"outp... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L175-L186 | ||
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | examples/onnx/bert/tokenization.py | python | load_vocab | (vocab_file) | return vocab | Loads a vocabulary file into a dictionary. | Loads a vocabulary file into a dictionary. | [
"Loads",
"a",
"vocabulary",
"file",
"into",
"a",
"dictionary",
"."
] | def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with open(vocab_file, "rb") as reader:
while True:
token = reader.readline()
token = token.decode("utf-8", "ignore")
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab | [
"def",
"load_vocab",
"(",
"vocab_file",
")",
":",
"vocab",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"index",
"=",
"0",
"with",
"open",
"(",
"vocab_file",
",",
"\"rb\"",
")",
"as",
"reader",
":",
"while",
"True",
":",
"token",
"=",
"reader",
".... | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/examples/onnx/bert/tokenization.py#L116-L129 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/elistmix.py | python | ListRowHighlighter.SetHighlightColor | (self, color) | Set the color used to highlight the rows. Call L{RefreshRows} after
this if you wish to update all the rows highlight colors.
@param color: wx.Colour or None to set default | Set the color used to highlight the rows. Call L{RefreshRows} after
this if you wish to update all the rows highlight colors.
@param color: wx.Colour or None to set default | [
"Set",
"the",
"color",
"used",
"to",
"highlight",
"the",
"rows",
".",
"Call",
"L",
"{",
"RefreshRows",
"}",
"after",
"this",
"if",
"you",
"wish",
"to",
"update",
"all",
"the",
"rows",
"highlight",
"colors",
".",
"@param",
"color",
":",
"wx",
".",
"Colo... | def SetHighlightColor(self, color):
"""Set the color used to highlight the rows. Call L{RefreshRows} after
this if you wish to update all the rows highlight colors.
@param color: wx.Colour or None to set default
"""
self._color = color | [
"def",
"SetHighlightColor",
"(",
"self",
",",
"color",
")",
":",
"self",
".",
"_color",
"=",
"color"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/elistmix.py#L88-L94 | ||
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | ctpn_crnn_ocr/CTPN/caffe/scripts/cpp_lint.py | python | _IncludeState.CanonicalizeAlphabeticalOrder | (self, header_path) | return header_path.replace('-inl.h', '.h').replace('-', '_').lower() | Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path. | Returns a path canonicalized for alphabetical comparison. | [
"Returns",
"a",
"path",
"canonicalized",
"for",
"alphabetical",
"comparison",
"."
] | def CanonicalizeAlphabeticalOrder(self, header_path):
"""Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path.
"""
return header_path.replace('-inl.h', '.h').replace('-', '_').lower() | [
"def",
"CanonicalizeAlphabeticalOrder",
"(",
"self",
",",
"header_path",
")",
":",
"return",
"header_path",
".",
"replace",
"(",
"'-inl.h'",
",",
"'.h'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"lower",
"(",
")"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/ctpn_crnn_ocr/CTPN/caffe/scripts/cpp_lint.py#L597-L610 | |
LLNL/lbann | 26083e6c86050302ce33148aea70f62e61cacb92 | applications/nlp/utils/paths.py | python | system | () | return re.sub(r'\d+', '', socket.gethostname()) | Name of current compute system.
Primarily used to detect LLNL LC systems. | Name of current compute system. | [
"Name",
"of",
"current",
"compute",
"system",
"."
] | def system():
"""Name of current compute system.
Primarily used to detect LLNL LC systems.
"""
return re.sub(r'\d+', '', socket.gethostname()) | [
"def",
"system",
"(",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\\d+'",
",",
"''",
",",
"socket",
".",
"gethostname",
"(",
")",
")"
] | https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/applications/nlp/utils/paths.py#L8-L14 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/OpenSCAD/importCSG.py | python | p_sphere_action | (p) | sphere_action : sphere LPAREN keywordargument_list RPAREN SEMICOL | sphere_action : sphere LPAREN keywordargument_list RPAREN SEMICOL | [
"sphere_action",
":",
"sphere",
"LPAREN",
"keywordargument_list",
"RPAREN",
"SEMICOL"
] | def p_sphere_action(p):
'sphere_action : sphere LPAREN keywordargument_list RPAREN SEMICOL'
if printverbose: print("Sphere : ",p[3])
r = float(p[3]['r'])
mysphere = doc.addObject("Part::Sphere",p[1])
mysphere.Radius = r
if printverbose: print("Push Sphere")
p[0] = [mysphere]
if printverbose: print("End Sphere") | [
"def",
"p_sphere_action",
"(",
"p",
")",
":",
"if",
"printverbose",
":",
"print",
"(",
"\"Sphere : \"",
",",
"p",
"[",
"3",
"]",
")",
"r",
"=",
"float",
"(",
"p",
"[",
"3",
"]",
"[",
"'r'",
"]",
")",
"mysphere",
"=",
"doc",
".",
"addObject",
"(",... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/OpenSCAD/importCSG.py#L1049-L1057 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/coverage/coverage/collector.py | python | Collector.resume | (self) | Resume tracing after a `pause`. | Resume tracing after a `pause`. | [
"Resume",
"tracing",
"after",
"a",
"pause",
"."
] | def resume(self):
"""Resume tracing after a `pause`."""
for tracer in self.tracers:
tracer.start()
if self.threading:
self.threading.settrace(self._installation_trace)
else:
self._start_tracer() | [
"def",
"resume",
"(",
"self",
")",
":",
"for",
"tracer",
"in",
"self",
".",
"tracers",
":",
"tracer",
".",
"start",
"(",
")",
"if",
"self",
".",
"threading",
":",
"self",
".",
"threading",
".",
"settrace",
"(",
"self",
".",
"_installation_trace",
")",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/collector.py#L301-L308 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/serial/serialcli.py | python | Serial._reconfigure_port | (self) | Set communication parameters on opened port. | Set communication parameters on opened port. | [
"Set",
"communication",
"parameters",
"on",
"opened",
"port",
"."
] | def _reconfigure_port(self):
"""Set communication parameters on opened port."""
if not self._port_handle:
raise SerialException("Can only operate on a valid port handle")
#~ self._port_handle.ReceivedBytesThreshold = 1
if self._timeout is None:
self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
else:
self._port_handle.ReadTimeout = int(self._timeout * 1000)
# if self._timeout != 0 and self._interCharTimeout is not None:
# timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
if self._write_timeout is None:
self._port_handle.WriteTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
else:
self._port_handle.WriteTimeout = int(self._write_timeout * 1000)
# Setup the connection info.
try:
self._port_handle.BaudRate = self._baudrate
except IOError as e:
# catch errors from illegal baudrate settings
raise ValueError(str(e))
if self._bytesize == FIVEBITS:
self._port_handle.DataBits = 5
elif self._bytesize == SIXBITS:
self._port_handle.DataBits = 6
elif self._bytesize == SEVENBITS:
self._port_handle.DataBits = 7
elif self._bytesize == EIGHTBITS:
self._port_handle.DataBits = 8
else:
raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
if self._parity == PARITY_NONE:
self._port_handle.Parity = getattr(System.IO.Ports.Parity, 'None') # reserved keyword in Py3k
elif self._parity == PARITY_EVEN:
self._port_handle.Parity = System.IO.Ports.Parity.Even
elif self._parity == PARITY_ODD:
self._port_handle.Parity = System.IO.Ports.Parity.Odd
elif self._parity == PARITY_MARK:
self._port_handle.Parity = System.IO.Ports.Parity.Mark
elif self._parity == PARITY_SPACE:
self._port_handle.Parity = System.IO.Ports.Parity.Space
else:
raise ValueError("Unsupported parity mode: %r" % self._parity)
if self._stopbits == STOPBITS_ONE:
self._port_handle.StopBits = System.IO.Ports.StopBits.One
elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
self._port_handle.StopBits = System.IO.Ports.StopBits.OnePointFive
elif self._stopbits == STOPBITS_TWO:
self._port_handle.StopBits = System.IO.Ports.StopBits.Two
else:
raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
if self._rtscts and self._xonxoff:
self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff
elif self._rtscts:
self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend
elif self._xonxoff:
self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff
else:
self._port_handle.Handshake = getattr(System.IO.Ports.Handshake, 'None') | [
"def",
"_reconfigure_port",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_port_handle",
":",
"raise",
"SerialException",
"(",
"\"Can only operate on a valid port handle\"",
")",
"#~ self._port_handle.ReceivedBytesThreshold = 1",
"if",
"self",
".",
"_timeout",
"is",
... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialcli.py#L59-L126 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/23.merge-k-sorted-lists.py | python | Solution.mergeKLists | (self, lists) | return head.next | :type lists: List[ListNode]
:rtype: ListNode | :type lists: List[ListNode]
:rtype: ListNode | [
":",
"type",
"lists",
":",
"List",
"[",
"ListNode",
"]",
":",
"rtype",
":",
"ListNode"
] | def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
heap = []
for node in lists:
if node is not None:
heapq.heappush(heap, (node.val, node))
head = ListNode(0)
cur = head
while(len(heap) > 0):
val, neighbor = heapq.heappop(heap)
cur.next = neighbor
cur = cur.next
if neighbor.next is not None:
heapq.heappush(heap, (neighbor.next.val, neighbor.next))
return head.next | [
"def",
"mergeKLists",
"(",
"self",
",",
"lists",
")",
":",
"heap",
"=",
"[",
"]",
"for",
"node",
"in",
"lists",
":",
"if",
"node",
"is",
"not",
"None",
":",
"heapq",
".",
"heappush",
"(",
"heap",
",",
"(",
"node",
".",
"val",
",",
"node",
")",
... | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/23.merge-k-sorted-lists.py#L9-L31 | |
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/3rdparty/jinja2/compiler.py | python | CodeGenerator.pull_locals | (self, frame) | Pull all the references identifiers into the local scope. | Pull all the references identifiers into the local scope. | [
"Pull",
"all",
"the",
"references",
"identifiers",
"into",
"the",
"local",
"scope",
"."
] | def pull_locals(self, frame):
"""Pull all the references identifiers into the local scope."""
for name in frame.identifiers.undeclared:
self.writeline('l_%s = context.resolve(%r)' % (name, name)) | [
"def",
"pull_locals",
"(",
"self",
",",
"frame",
")",
":",
"for",
"name",
"in",
"frame",
".",
"identifiers",
".",
"undeclared",
":",
"self",
".",
"writeline",
"(",
"'l_%s = context.resolve(%r)'",
"%",
"(",
"name",
",",
"name",
")",
")"
] | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/compiler.py#L572-L575 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/dataclasses.py | python | dataclass | (_cls=None, *, init=True, repr=True, eq=True, order=False,
unsafe_hash=False, frozen=False) | return wrap(_cls) | Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If
repr is true, a __repr__() method is added. If order is true, rich
comparison dunder methods are added. If unsafe_hash is true, a
__hash__() method function is added. If frozen is true, fields may
not be assigned to after instance creation. | Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class. | [
"Returns",
"the",
"same",
"class",
"as",
"was",
"passed",
"in",
"with",
"dunder",
"methods",
"added",
"based",
"on",
"the",
"fields",
"defined",
"in",
"the",
"class",
"."
] | def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
unsafe_hash=False, frozen=False):
"""Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If
repr is true, a __repr__() method is added. If order is true, rich
comparison dunder methods are added. If unsafe_hash is true, a
__hash__() method function is added. If frozen is true, fields may
not be assigned to after instance creation.
"""
def wrap(cls):
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
# See if we're being called as @dataclass or @dataclass().
if _cls is None:
# We're called with parens.
return wrap
# We're called as @dataclass without parens.
return wrap(_cls) | [
"def",
"dataclass",
"(",
"_cls",
"=",
"None",
",",
"*",
",",
"init",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"eq",
"=",
"True",
",",
"order",
"=",
"False",
",",
"unsafe_hash",
"=",
"False",
",",
"frozen",
"=",
"False",
")",
":",
"def",
"wrap"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/dataclasses.py#L987-L1010 | |
ziquan111/RobustPCLReconstruction | 35b9518dbf9ad3f06109cc0e3aaacafdb5c86e36 | py/sophus/dual_quaternion.py | python | DualQuaternion.conj | (self) | return DualQuaternion(self.real_q.conj(), self.inf_q.conj()) | dual quaternion conjugate | dual quaternion conjugate | [
"dual",
"quaternion",
"conjugate"
] | def conj(self):
""" dual quaternion conjugate """
return DualQuaternion(self.real_q.conj(), self.inf_q.conj()) | [
"def",
"conj",
"(",
"self",
")",
":",
"return",
"DualQuaternion",
"(",
"self",
".",
"real_q",
".",
"conj",
"(",
")",
",",
"self",
".",
"inf_q",
".",
"conj",
"(",
")",
")"
] | https://github.com/ziquan111/RobustPCLReconstruction/blob/35b9518dbf9ad3f06109cc0e3aaacafdb5c86e36/py/sophus/dual_quaternion.py#L41-L43 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py | python | WebSocketRequestHandler.log_request | (self, code='-', size='-') | Override BaseHTTPServer.log_request. | Override BaseHTTPServer.log_request. | [
"Override",
"BaseHTTPServer",
".",
"log_request",
"."
] | def log_request(self, code='-', size='-'):
"""Override BaseHTTPServer.log_request."""
self._logger.info('"%s" %s %s',
self.requestline, str(code), str(size)) | [
"def",
"log_request",
"(",
"self",
",",
"code",
"=",
"'-'",
",",
"size",
"=",
"'-'",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'\"%s\" %s %s'",
",",
"self",
".",
"requestline",
",",
"str",
"(",
"code",
")",
",",
"str",
"(",
"size",
")",
... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py#L810-L814 | ||
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/servermanager.py | python | FieldDataInformation.__contains__ | (self, key) | return False | Implementation of the dictionary API | Implementation of the dictionary API | [
"Implementation",
"of",
"the",
"dictionary",
"API"
] | def __contains__(self, key):
"""Implementation of the dictionary API"""
if self.GetArray(key):
return True
return False | [
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"GetArray",
"(",
"key",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/servermanager.py#L1701-L1705 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/saved_model/function_deserialization.py | python | fix_node_def | (node_def, functions, shared_name_suffix) | Replace functions calls and shared names in `node_def`. | Replace functions calls and shared names in `node_def`. | [
"Replace",
"functions",
"calls",
"and",
"shared",
"names",
"in",
"node_def",
"."
] | def fix_node_def(node_def, functions, shared_name_suffix):
"""Replace functions calls and shared names in `node_def`."""
if node_def.op in functions:
node_def.op = functions[node_def.op].name
for _, attr_value in node_def.attr.items():
if attr_value.WhichOneof("value") == "func":
attr_value.func.name = functions[attr_value.func.name].name
elif attr_value.WhichOneof("value") == "list":
for fn in attr_value.list.func:
fn.name = functions[fn.name].name
# Fix old table creation bug.
if node_def.op == "HashTableV2":
if ("use_node_name_sharing" not in node_def.attr or
not node_def.attr["use_node_name_sharing"].b):
node_def.attr["use_node_name_sharing"].b = True
# We are turning on node mame sharing, so have to make sure we don't
# accidentally share a table resource.
shared_name_suffix += "_{}".format(ops.uid())
# TODO(b/124205571): Avoid accidental sharing and destruction of restored
# resources. For now uniquify "shared_name" when loading functions to avoid
# sharing.
# TODO: Add regression test for b/150826922.
op_def = op_def_registry.get(node_def.op)
if op_def:
attr = next((a for a in op_def.attr if a.name == "shared_name"), None)
if attr:
shared_name = None
if "shared_name" in node_def.attr and node_def.attr["shared_name"].s:
shared_name = node_def.attr["shared_name"].s
elif attr.default_value.s:
shared_name = compat.as_bytes(attr.default_value.s)
if not shared_name:
shared_name = compat.as_bytes(node_def.name)
node_def.attr["shared_name"].s = (
shared_name + compat.as_bytes(shared_name_suffix)) | [
"def",
"fix_node_def",
"(",
"node_def",
",",
"functions",
",",
"shared_name_suffix",
")",
":",
"if",
"node_def",
".",
"op",
"in",
"functions",
":",
"node_def",
".",
"op",
"=",
"functions",
"[",
"node_def",
".",
"op",
"]",
".",
"name",
"for",
"_",
",",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/function_deserialization.py#L528-L565 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/inputparser.py | python | quotify | (string, isbasis=False) | return string | Function to wrap anything that looks like a string in quotes
and to remove leading dollar signs from python variables. When *basis*
is True, allows commas, since basis sets may have commas and are assured to
not involve arrays. | Function to wrap anything that looks like a string in quotes
and to remove leading dollar signs from python variables. When *basis*
is True, allows commas, since basis sets may have commas and are assured to
not involve arrays. | [
"Function",
"to",
"wrap",
"anything",
"that",
"looks",
"like",
"a",
"string",
"in",
"quotes",
"and",
"to",
"remove",
"leading",
"dollar",
"signs",
"from",
"python",
"variables",
".",
"When",
"*",
"basis",
"*",
"is",
"True",
"allows",
"commas",
"since",
"ba... | def quotify(string, isbasis=False):
"""Function to wrap anything that looks like a string in quotes
and to remove leading dollar signs from python variables. When *basis*
is True, allows commas, since basis sets may have commas and are assured to
not involve arrays.
"""
# This wraps anything that looks like a string in quotes, and removes leading
# dollar signs from python variables
if isbasis:
wordre = re.compile(r'(([$]?)([-+()*.,\w\"\'/\\]+))')
else:
wordre = re.compile(r'(([$]?)([-+()*.\w\"\'/\\]+))')
string = wordre.sub(process_word_quotes, string)
return string | [
"def",
"quotify",
"(",
"string",
",",
"isbasis",
"=",
"False",
")",
":",
"# This wraps anything that looks like a string in quotes, and removes leading",
"# dollar signs from python variables",
"if",
"isbasis",
":",
"wordre",
"=",
"re",
".",
"compile",
"(",
"r'(([$]?)([-+()... | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/inputparser.py#L79-L93 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/vis/glprogram.py | python | GLProgram.closefunc | (self) | return True | Called by the window when it is closed | Called by the window when it is closed | [
"Called",
"by",
"the",
"window",
"when",
"it",
"is",
"closed"
] | def closefunc(self):
"""Called by the window when it is closed"""
return True | [
"def",
"closefunc",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/vis/glprogram.py#L341-L343 | |
microsoft/CCF | 14801dc01f3f225fc85772eeb1c066d1b1b10a47 | python/ccf/receipt.py | python | check_endorsement | (endorsee: Certificate, endorser: Certificate) | Check endorser has endorsed endorsee | Check endorser has endorsed endorsee | [
"Check",
"endorser",
"has",
"endorsed",
"endorsee"
] | def check_endorsement(endorsee: Certificate, endorser: Certificate):
"""
Check endorser has endorsed endorsee
"""
digest_algo = endorsee.signature_hash_algorithm
assert digest_algo
digester = hashes.Hash(digest_algo)
digester.update(endorsee.tbs_certificate_bytes)
digest = digester.finalize()
endorser_pk = endorser.public_key()
assert isinstance(endorser_pk, ec.EllipticCurvePublicKey)
endorser_pk.verify(
endorsee.signature, digest, ec.ECDSA(utils.Prehashed(digest_algo))
) | [
"def",
"check_endorsement",
"(",
"endorsee",
":",
"Certificate",
",",
"endorser",
":",
"Certificate",
")",
":",
"digest_algo",
"=",
"endorsee",
".",
"signature_hash_algorithm",
"assert",
"digest_algo",
"digester",
"=",
"hashes",
".",
"Hash",
"(",
"digest_algo",
")... | https://github.com/microsoft/CCF/blob/14801dc01f3f225fc85772eeb1c066d1b1b10a47/python/ccf/receipt.py#L40-L53 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/headers.py | python | Headers.keys | (self) | return [k for k, v in self._headers] | Return a list of all the header field names.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list. | Return a list of all the header field names. | [
"Return",
"a",
"list",
"of",
"all",
"the",
"header",
"field",
"names",
"."
] | def keys(self):
"""Return a list of all the header field names.
These will be sorted in the order they appeared in the original header
list, or were added to this instance, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [k for k, v in self._headers] | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_headers",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/headers.py#L103-L111 | |
nileshkulkarni/csm | 0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc | csm/utils/transformations.py | python | Arcball.drag | (self, point) | Update current cursor window coordinates. | Update current cursor window coordinates. | [
"Update",
"current",
"cursor",
"window",
"coordinates",
"."
] | def drag(self, point):
"""Update current cursor window coordinates."""
vnow = arcball_map_to_sphere(point, self._center, self._radius)
if self._axis is not None:
vnow = arcball_constrain_to_axis(vnow, self._axis)
self._qpre = self._qnow
t = numpy.cross(self._vdown, vnow)
if numpy.dot(t, t) < _EPS:
self._qnow = self._qdown
else:
q = [numpy.dot(self._vdown, vnow), t[0], t[1], t[2]]
self._qnow = quaternion_multiply(q, self._qdown) | [
"def",
"drag",
"(",
"self",
",",
"point",
")",
":",
"vnow",
"=",
"arcball_map_to_sphere",
"(",
"point",
",",
"self",
".",
"_center",
",",
"self",
".",
"_radius",
")",
"if",
"self",
".",
"_axis",
"is",
"not",
"None",
":",
"vnow",
"=",
"arcball_constrain... | https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/utils/transformations.py#L1603-L1614 | ||
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | restapi/bareos_restapi/__init__.py | python | cancelJob | (
*,
job_id: int = Path(..., title="The ID of job to cancel", ge=1),
response: Response,
current_user: User = Depends(get_current_user),
) | return result | Cancel a specific job given bei jobid | Cancel a specific job given bei jobid | [
"Cancel",
"a",
"specific",
"job",
"given",
"bei",
"jobid"
] | def cancelJob(
*,
job_id: int = Path(..., title="The ID of job to cancel", ge=1),
response: Response,
current_user: User = Depends(get_current_user),
):
"""
Cancel a specific job given bei jobid
"""
# cancel a specific job given bei jobid
cancelCommand = "cancel jobid=%d" % job_id
result = None
try:
result = current_user.jsonDirector.call(cancelCommand)
except Exception as e:
response.status_code = 500
return {
"message": "Could not cancel jobid %d on director %s. Message: '%s'"
% (job_id, current_user.directorName, e)
}
return result | [
"def",
"cancelJob",
"(",
"*",
",",
"job_id",
":",
"int",
"=",
"Path",
"(",
"...",
",",
"title",
"=",
"\"The ID of job to cancel\"",
",",
"ge",
"=",
"1",
")",
",",
"response",
":",
"Response",
",",
"current_user",
":",
"User",
"=",
"Depends",
"(",
"get_... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/restapi/bareos_restapi/__init__.py#L779-L799 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Variables/PathVariable.py | python | _PathVariableClass.PathExists | (key, val, env) | Validator to check if Path exists | Validator to check if Path exists | [
"Validator",
"to",
"check",
"if",
"Path",
"exists"
] | def PathExists(key, val, env):
"""Validator to check if Path exists"""
if not os.path.exists(val):
m = 'Path for option %s does not exist: %s'
raise SCons.Errors.UserError(m % (key, val)) | [
"def",
"PathExists",
"(",
"key",
",",
"val",
",",
"env",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"val",
")",
":",
"m",
"=",
"'Path for option %s does not exist: %s'",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"m",
"%... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Variables/PathVariable.py#L111-L115 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/results.py | python | Analysis.arcs_missing | (self) | return sorted(missing) | Returns a sorted list of the arcs in the code not executed. | Returns a sorted list of the arcs in the code not executed. | [
"Returns",
"a",
"sorted",
"list",
"of",
"the",
"arcs",
"in",
"the",
"code",
"not",
"executed",
"."
] | def arcs_missing(self):
"""Returns a sorted list of the arcs in the code not executed."""
possible = self.arc_possibilities()
executed = self.arcs_executed()
missing = [
p for p in possible
if p not in executed
and p[0] not in self.no_branch
]
return sorted(missing) | [
"def",
"arcs_missing",
"(",
"self",
")",
":",
"possible",
"=",
"self",
".",
"arc_possibilities",
"(",
")",
"executed",
"=",
"self",
".",
"arcs_executed",
"(",
")",
"missing",
"=",
"[",
"p",
"for",
"p",
"in",
"possible",
"if",
"p",
"not",
"in",
"execute... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/results.py#L84-L93 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/tools/list_ports_linux.py | python | usb_sysfs_hw_string | (sysfs_path) | return 'USB VID:PID=%s:%s%s' % (
read_line(sysfs_path+'/idVendor'),
read_line(sysfs_path+'/idProduct'),
snr_txt
) | given a path to a usb device in sysfs, return a string describing it | given a path to a usb device in sysfs, return a string describing it | [
"given",
"a",
"path",
"to",
"a",
"usb",
"device",
"in",
"sysfs",
"return",
"a",
"string",
"describing",
"it"
] | def usb_sysfs_hw_string(sysfs_path):
"""given a path to a usb device in sysfs, return a string describing it"""
bus, dev = os.path.basename(os.path.realpath(sysfs_path)).split('-')
snr = read_line(sysfs_path+'/serial')
if snr:
snr_txt = ' SNR=%s' % (snr,)
else:
snr_txt = ''
return 'USB VID:PID=%s:%s%s' % (
read_line(sysfs_path+'/idVendor'),
read_line(sysfs_path+'/idProduct'),
snr_txt
) | [
"def",
"usb_sysfs_hw_string",
"(",
"sysfs_path",
")",
":",
"bus",
",",
"dev",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"sysfs_path",
")",
")",
".",
"split",
"(",
"'-'",
")",
"snr",
"=",
"read_line",
"(",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/tools/list_ports_linux.py#L65-L77 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridTableMessage.GetCommandInt2 | (*args, **kwargs) | return _grid.GridTableMessage_GetCommandInt2(*args, **kwargs) | GetCommandInt2(self) -> int | GetCommandInt2(self) -> int | [
"GetCommandInt2",
"(",
"self",
")",
"-",
">",
"int"
] | def GetCommandInt2(*args, **kwargs):
"""GetCommandInt2(self) -> int"""
return _grid.GridTableMessage_GetCommandInt2(*args, **kwargs) | [
"def",
"GetCommandInt2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableMessage_GetCommandInt2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L1103-L1105 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py | python | ConfigDialog.set_extension_value | (self, section, opt) | return self.ext_userCfg.SetOption(section, name, value) | Return True if the configuration was added or changed.
If the value is the same as the default, then remove it
from user config file. | Return True if the configuration was added or changed. | [
"Return",
"True",
"if",
"the",
"configuration",
"was",
"added",
"or",
"changed",
"."
] | def set_extension_value(self, section, opt):
"""Return True if the configuration was added or changed.
If the value is the same as the default, then remove it
from user config file.
"""
name = opt['name']
default = opt['default']
value = opt['var'].get().strip() or default
opt['var'].set(value)
# if self.defaultCfg.has_section(section):
# Currently, always true; if not, indent to return.
if (value == default):
return self.ext_userCfg.RemoveOption(section, name)
# Set the option.
return self.ext_userCfg.SetOption(section, name, value) | [
"def",
"set_extension_value",
"(",
"self",
",",
"section",
",",
"opt",
")",
":",
"name",
"=",
"opt",
"[",
"'name'",
"]",
"default",
"=",
"opt",
"[",
"'default'",
"]",
"value",
"=",
"opt",
"[",
"'var'",
"]",
".",
"get",
"(",
")",
".",
"strip",
"(",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py#L394-L409 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/tpu/python/tpu/tpu_optimizer.py | python | CrossShardOptimizer.compute_gradients | (self, *args, **kwargs) | return self._opt.compute_gradients(*args, **kwargs) | Compute gradients of "loss" for the variables in "var_list".
This simply wraps the compute_gradients() from the real optimizer. The
gradients will be aggregated in the apply_gradients() so that user can
modify the gradients like clipping with per replica global norm if needed.
The global norm with aggregated gradients can be bad as one replica's huge
gradients can hurt the gradients from other replicas.
Args:
*args: Arguments for compute_gradients().
**kwargs: Keyword arguments for compute_gradients().
Returns:
A list of (gradient, variable) pairs. | Compute gradients of "loss" for the variables in "var_list". | [
"Compute",
"gradients",
"of",
"loss",
"for",
"the",
"variables",
"in",
"var_list",
"."
] | def compute_gradients(self, *args, **kwargs):
"""Compute gradients of "loss" for the variables in "var_list".
This simply wraps the compute_gradients() from the real optimizer. The
gradients will be aggregated in the apply_gradients() so that user can
modify the gradients like clipping with per replica global norm if needed.
The global norm with aggregated gradients can be bad as one replica's huge
gradients can hurt the gradients from other replicas.
Args:
*args: Arguments for compute_gradients().
**kwargs: Keyword arguments for compute_gradients().
Returns:
A list of (gradient, variable) pairs.
"""
return self._opt.compute_gradients(*args, **kwargs) | [
"def",
"compute_gradients",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_opt",
".",
"compute_gradients",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/tpu/python/tpu/tpu_optimizer.py#L33-L49 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/tools/clang/tools/scan-build-py/libscanbuild/clang.py | python | get_version | (clang) | return output.decode('utf-8').splitlines()[0] | Returns the compiler version as string.
:param clang: the compiler we are using
:return: the version string printed to stderr | Returns the compiler version as string. | [
"Returns",
"the",
"compiler",
"version",
"as",
"string",
"."
] | def get_version(clang):
""" Returns the compiler version as string.
:param clang: the compiler we are using
:return: the version string printed to stderr """
output = subprocess.check_output([clang, '-v'], stderr=subprocess.STDOUT)
return output.decode('utf-8').splitlines()[0] | [
"def",
"get_version",
"(",
"clang",
")",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"clang",
",",
"'-v'",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"return",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"spl... | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/tools/scan-build-py/libscanbuild/clang.py#L22-L29 | |
paranoidninja/Pandoras-Box | 91316052a337c3a91da0c6e69f3ba0076436a037 | python/impacket-scripts/split.py | python | Connection.getFilename | (self) | return '%s.%d-%s.%d.pcap'%(self.p1[0],self.p1[1],self.p2[0],self.p2[1]) | Utility function that returns a filename composed by the IP
addresses and ports of both peers. | Utility function that returns a filename composed by the IP
addresses and ports of both peers. | [
"Utility",
"function",
"that",
"returns",
"a",
"filename",
"composed",
"by",
"the",
"IP",
"addresses",
"and",
"ports",
"of",
"both",
"peers",
"."
] | def getFilename(self):
"""Utility function that returns a filename composed by the IP
addresses and ports of both peers.
"""
return '%s.%d-%s.%d.pcap'%(self.p1[0],self.p1[1],self.p2[0],self.p2[1]) | [
"def",
"getFilename",
"(",
"self",
")",
":",
"return",
"'%s.%d-%s.%d.pcap'",
"%",
"(",
"self",
".",
"p1",
"[",
"0",
"]",
",",
"self",
".",
"p1",
"[",
"1",
"]",
",",
"self",
".",
"p2",
"[",
"0",
"]",
",",
"self",
".",
"p2",
"[",
"1",
"]",
")"
... | https://github.com/paranoidninja/Pandoras-Box/blob/91316052a337c3a91da0c6e69f3ba0076436a037/python/impacket-scripts/split.py#L45-L49 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/sparse.py | python | SparseArray.mean | (self, axis=0, *args, **kwargs) | Mean of non-NA/null values
Returns
-------
mean : float | Mean of non-NA/null values | [
"Mean",
"of",
"non",
"-",
"NA",
"/",
"null",
"values"
] | def mean(self, axis=0, *args, **kwargs):
"""
Mean of non-NA/null values
Returns
-------
mean : float
"""
nv.validate_mean(args, kwargs)
valid_vals = self._valid_sp_values
sp_sum = valid_vals.sum()
ct = len(valid_vals)
if self._null_fill_value:
return sp_sum / ct
else:
nsparse = self.sp_index.ngaps
return (sp_sum + self.fill_value * nsparse) / (ct + nsparse) | [
"def",
"mean",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_mean",
"(",
"args",
",",
"kwargs",
")",
"valid_vals",
"=",
"self",
".",
"_valid_sp_values",
"sp_sum",
"=",
"valid_vals",
".",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/sparse.py#L1531-L1548 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/autograph/pyct/static_analysis/type_inference.py | python | resolve | (node, source_info, graphs, resolver) | return node | Performs type inference.
Args:
node: ast.AST
source_info: transformer.SourceInfo
graphs: Dict[ast.FunctionDef, cfg.Graph]
resolver: Resolver
Returns:
ast.AST | Performs type inference. | [
"Performs",
"type",
"inference",
"."
] | def resolve(node, source_info, graphs, resolver):
"""Performs type inference.
Args:
node: ast.AST
source_info: transformer.SourceInfo
graphs: Dict[ast.FunctionDef, cfg.Graph]
resolver: Resolver
Returns:
ast.AST
"""
visitor = FunctionVisitor(source_info, graphs, resolver)
node = visitor.visit(node)
return node | [
"def",
"resolve",
"(",
"node",
",",
"source_info",
",",
"graphs",
",",
"resolver",
")",
":",
"visitor",
"=",
"FunctionVisitor",
"(",
"source_info",
",",
"graphs",
",",
"resolver",
")",
"node",
"=",
"visitor",
".",
"visit",
"(",
"node",
")",
"return",
"no... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/pyct/static_analysis/type_inference.py#L610-L624 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | examples/python/gdbremote.py | python | RegisterInfo.byte_size | (self) | return self.bit_size() / 8 | Get the size in bytes of the register. | Get the size in bytes of the register. | [
"Get",
"the",
"size",
"in",
"bytes",
"of",
"the",
"register",
"."
] | def byte_size(self):
'''Get the size in bytes of the register.'''
return self.bit_size() / 8 | [
"def",
"byte_size",
"(",
"self",
")",
":",
"return",
"self",
".",
"bit_size",
"(",
")",
"/",
"8"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/examples/python/gdbremote.py#L361-L363 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/fusion/portableglobe/tools/check_crc.py | python | CalculateCrc | (fname) | return crc | Returns calculated crc for the globe. | Returns calculated crc for the globe. | [
"Returns",
"calculated",
"crc",
"for",
"the",
"globe",
"."
] | def CalculateCrc(fname):
"""Returns calculated crc for the globe."""
size = os.path.getsize(fname) / CRC_SIZE
fp = open(fname, "rb")
crc = [0, 0, 0, 0]
step = size / 100.0 * PERCENT_PROGRESS_STEP
percent = 0
next_progress_indication = 0.0
for i in xrange(size):
word = fp.read(CRC_SIZE)
for j in xrange(CRC_SIZE):
crc[j] ^= ord(word[j])
if i >= next_progress_indication:
print "%d%%" % percent
next_progress_indication += step
percent += PERCENT_PROGRESS_STEP
fp.close()
return crc | [
"def",
"CalculateCrc",
"(",
"fname",
")",
":",
"size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"fname",
")",
"/",
"CRC_SIZE",
"fp",
"=",
"open",
"(",
"fname",
",",
"\"rb\"",
")",
"crc",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/tools/check_crc.py#L40-L58 | |
RobotLocomotion/drake | 0e18a34604c45ed65bc9018a54f7610f91cdad5b | doc/pydrake/pydrake_sphinx_extension.py | python | autodoc_member_order_function | (app, documenter) | return fullname.lower() | Let's sort the member full-names (`Class.member_name`) by lower-case. | Let's sort the member full-names (`Class.member_name`) by lower-case. | [
"Let",
"s",
"sort",
"the",
"member",
"full",
"-",
"names",
"(",
"Class",
".",
"member_name",
")",
"by",
"lower",
"-",
"case",
"."
] | def autodoc_member_order_function(app, documenter):
"""Let's sort the member full-names (`Class.member_name`) by lower-case."""
# N.B. This follows suite with the following 3.x code: https://git.io/Jv1CH
fullname = documenter.name.split('::')[1]
return fullname.lower() | [
"def",
"autodoc_member_order_function",
"(",
"app",
",",
"documenter",
")",
":",
"# N.B. This follows suite with the following 3.x code: https://git.io/Jv1CH",
"fullname",
"=",
"documenter",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"1",
"]",
"return",
"fullname... | https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/doc/pydrake/pydrake_sphinx_extension.py#L365-L369 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | mojo/public/bindings/pylib/parse/mojo_parser.py | python | Parser.p_struct_body | (self, p) | struct_body : field struct_body
| enum struct_body
| | struct_body : field struct_body
| enum struct_body
| | [
"struct_body",
":",
"field",
"struct_body",
"|",
"enum",
"struct_body",
"|"
] | def p_struct_body(self, p):
"""struct_body : field struct_body
| enum struct_body
| """
if len(p) > 1:
p[0] = ListFromConcat(p[1], p[2]) | [
"def",
"p_struct_body",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
">",
"1",
":",
"p",
"[",
"0",
"]",
"=",
"ListFromConcat",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/mojo/public/bindings/pylib/parse/mojo_parser.py#L103-L108 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/coverage/coverage/parser.py | python | PythonParser.first_lines | (self, lines) | return set(self.first_line(l) for l in lines) | Map the line numbers in `lines` to the correct first line of the
statement.
Returns a set of the first lines. | Map the line numbers in `lines` to the correct first line of the
statement. | [
"Map",
"the",
"line",
"numbers",
"in",
"lines",
"to",
"the",
"correct",
"first",
"line",
"of",
"the",
"statement",
"."
] | def first_lines(self, lines):
"""Map the line numbers in `lines` to the correct first line of the
statement.
Returns a set of the first lines.
"""
return set(self.first_line(l) for l in lines) | [
"def",
"first_lines",
"(",
"self",
",",
"lines",
")",
":",
"return",
"set",
"(",
"self",
".",
"first_line",
"(",
"l",
")",
"for",
"l",
"in",
"lines",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/parser.py#L175-L182 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/__init__.py | python | ResourceManager.resource_exists | (self, package_or_requirement, resource_name) | return get_provider(package_or_requirement).has_resource(resource_name) | Does the named resource exist? | Does the named resource exist? | [
"Does",
"the",
"named",
"resource",
"exist?"
] | def resource_exists(self, package_or_requirement, resource_name):
"""Does the named resource exist?"""
return get_provider(package_or_requirement).has_resource(resource_name) | [
"def",
"resource_exists",
"(",
"self",
",",
"package_or_requirement",
",",
"resource_name",
")",
":",
"return",
"get_provider",
"(",
"package_or_requirement",
")",
".",
"has_resource",
"(",
"resource_name",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L1123-L1125 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/math_ops.py | python | _apply_tensor_op | (fn, *args, dtype=None) | return res | Applies tensor operations based on fn | Applies tensor operations based on fn | [
"Applies",
"tensor",
"operations",
"based",
"on",
"fn"
] | def _apply_tensor_op(fn, *args, dtype=None):
"""Applies tensor operations based on fn"""
args = _to_tensor(*args)
if isinstance(args, Tensor):
res = fn(args)
else:
res = fn(*args)
if dtype is not None and not _check_same_type(F.dtype(res), dtype):
res = F.cast(res, dtype)
return res | [
"def",
"_apply_tensor_op",
"(",
"fn",
",",
"*",
"args",
",",
"dtype",
"=",
"None",
")",
":",
"args",
"=",
"_to_tensor",
"(",
"*",
"args",
")",
"if",
"isinstance",
"(",
"args",
",",
"Tensor",
")",
":",
"res",
"=",
"fn",
"(",
"args",
")",
"else",
"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L4431-L4440 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py | python | rv_continuous.logsf | (self, x, *args, **kwds) | return output | Log of the survival function of the given RV.
Returns the log of the "survival function," defined as (1 - `cdf`),
evaluated at `x`.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
logsf : ndarray
Log of the survival function evaluated at `x`. | Log of the survival function of the given RV. | [
"Log",
"of",
"the",
"survival",
"function",
"of",
"the",
"given",
"RV",
"."
] | def logsf(self, x, *args, **kwds):
"""
Log of the survival function of the given RV.
Returns the log of the "survival function," defined as (1 - `cdf`),
evaluated at `x`.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
logsf : ndarray
Log of the survival function evaluated at `x`.
"""
args, loc, scale = self._parse_args(*args, **kwds)
x, loc, scale = map(asarray, (x, loc, scale))
args = tuple(map(asarray, args))
dtyp = np.find_common_type([x.dtype, np.float64], [])
x = np.asarray((x - loc)/scale, dtype=dtyp)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = self._open_support_mask(x) & (scale > 0)
cond2 = cond0 & (x <= self.a)
cond = cond0 & cond1
output = empty(shape(cond), dtyp)
output.fill(NINF)
place(output, (1-cond0)+np.isnan(x), self.badvalue)
place(output, cond2, 0.0)
if np.any(cond):
goodargs = argsreduce(cond, *((x,)+args))
place(output, cond, self._logsf(*goodargs))
if output.ndim == 0:
return output[()]
return output | [
"def",
"logsf",
"(",
"self",
",",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"args",
",",
"loc",
",",
"scale",
"=",
"self",
".",
"_parse_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"x",
",",
"loc",
",",
"scale",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py#L1843-L1886 | |
usdot-fhwa-stol/carma-platform | d9d9b93f9689b2c7dd607cf5432d5296fc1000f5 | guidance_plugin_validator/src/guidance_plugin_validator/guidance_plugin_validator.py | python | GuidancePluginValidator.__init__ | (self) | Default constructor for GuidancePluginValidator | Default constructor for GuidancePluginValidator | [
"Default",
"constructor",
"for",
"GuidancePluginValidator"
] | def __init__(self):
"""Default constructor for GuidancePluginValidator"""
# Create plugin_discovery subscriber
self.plugin_discovery_sub = rospy.Subscriber("plugin_discovery", Plugin, self.plugin_discovery_cb)
self.system_alert_sub = rospy.Subscriber("system_alert", SystemAlert, self.system_alert_cb)
# Read in config params
self.validation_duration = rospy.get_param('~validation_duration', 300) # Maximum time (sec) that node will spend conducting validation before results are considered final
self.strategic_plugin_names = rospy.get_param('~strategic_plugins_to_validate', [])
self.tactical_plugin_names = rospy.get_param('~tactical_plugins_to_validate', [])
self.control_plugin_names = rospy.get_param('~control_plugins_to_validate', [])
# Write config params to log file
rospy.loginfo("Config params for guidance_plugin_validator:")
rospy.loginfo("Validation Duration: " + str(self.validation_duration) + " seconds")
rospy.loginfo("Strategic Guidance Plugins: " + str(self.strategic_plugin_names))
rospy.loginfo("Tactical Guidance Plugins: " + str(self.tactical_plugin_names))
rospy.loginfo("Control Guidance Plugins: " + str(self.control_plugin_names))
# Boolean flag to indicate whether drivers are ready (this indicates that plugin node validation checks can begin)
self.has_startup_completed = False
# Boolean flag to indicate whether each guidance plugin's node has been validated
self.has_node_validation_completed = False
# Boolean flag to indicate whether final results have been written to log file
self.has_logged_final_results = False
# Set spin rate
self.spin_rate = rospy.Rate(10) # 10 Hz
# Initialize empty dicts that will be populated with a <plugin-type>PluginResults object for each Guidance Plugin
self.strategic_plugin_validation_results = {} # Key is plugin's name; Value is plugin's StrategicPluginResults object
self.tactical_plugin_validation_results = {} # Key is plugin's name; Value is plugin's TacticalPluginResults object
self.control_plugin_validation_results = {} # Key is plugin's name; Value is plugin's ControlPluginResults object
# Call member function to populate the 'validation results' dicts
self.populate_results_dicts(self.strategic_plugin_names, self.tactical_plugin_names, self.control_plugin_names) | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Create plugin_discovery subscriber",
"self",
".",
"plugin_discovery_sub",
"=",
"rospy",
".",
"Subscriber",
"(",
"\"plugin_discovery\"",
",",
"Plugin",
",",
"self",
".",
"plugin_discovery_cb",
")",
"self",
".",
"system_ale... | https://github.com/usdot-fhwa-stol/carma-platform/blob/d9d9b93f9689b2c7dd607cf5432d5296fc1000f5/guidance_plugin_validator/src/guidance_plugin_validator/guidance_plugin_validator.py#L32-L70 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | IconBundle.GetIcon | (*args, **kwargs) | return _gdi_.IconBundle_GetIcon(*args, **kwargs) | GetIcon(self, Size size, int flags=FALLBACK_SYSTEM) -> Icon
Returns the icon with the given size; if no such icon exists, returns
the icon with size wxSYS_ICON_[XY]; if no such icon exists, returns
the first icon in the bundle | GetIcon(self, Size size, int flags=FALLBACK_SYSTEM) -> Icon | [
"GetIcon",
"(",
"self",
"Size",
"size",
"int",
"flags",
"=",
"FALLBACK_SYSTEM",
")",
"-",
">",
"Icon"
] | def GetIcon(*args, **kwargs):
"""
GetIcon(self, Size size, int flags=FALLBACK_SYSTEM) -> Icon
Returns the icon with the given size; if no such icon exists, returns
the icon with size wxSYS_ICON_[XY]; if no such icon exists, returns
the first icon in the bundle
"""
return _gdi_.IconBundle_GetIcon(*args, **kwargs) | [
"def",
"GetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"IconBundle_GetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1465-L1473 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/screen.py | python | screen.scroll_constrain | (self) | This keeps the scroll region within the screen region. | This keeps the scroll region within the screen region. | [
"This",
"keeps",
"the",
"scroll",
"region",
"within",
"the",
"screen",
"region",
"."
] | def scroll_constrain(self):
"""This keeps the scroll region within the screen region."""
if self.scroll_row_start <= 0:
self.scroll_row_start = 1
if self.scroll_row_end > self.rows:
self.scroll_row_end = self.rows | [
"def",
"scroll_constrain",
"(",
"self",
")",
":",
"if",
"self",
".",
"scroll_row_start",
"<=",
"0",
":",
"self",
".",
"scroll_row_start",
"=",
"1",
"if",
"self",
".",
"scroll_row_end",
">",
"self",
".",
"rows",
":",
"self",
".",
"scroll_row_end",
"=",
"s... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/screen.py#L258-L264 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/bcdoc/restdoc.py | python | DocumentStructure.get_section | (self, name) | return self._structure[name] | Retrieve a section | Retrieve a section | [
"Retrieve",
"a",
"section"
] | def get_section(self, name):
"""Retrieve a section"""
return self._structure[name] | [
"def",
"get_section",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_structure",
"[",
"name",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/bcdoc/restdoc.py#L185-L187 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Type.kind | (self) | return TypeKind.from_id(self._kind_id) | Return the kind of this type. | Return the kind of this type. | [
"Return",
"the",
"kind",
"of",
"this",
"type",
"."
] | def kind(self):
"""Return the kind of this type."""
return TypeKind.from_id(self._kind_id) | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"TypeKind",
".",
"from_id",
"(",
"self",
".",
"_kind_id",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L2160-L2162 | |
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/ansic/cparse.py | python | p_postfix_expression_5 | (t) | postfix_expression : postfix_expression PERIOD ID | postfix_expression : postfix_expression PERIOD ID | [
"postfix_expression",
":",
"postfix_expression",
"PERIOD",
"ID"
] | def p_postfix_expression_5(t):
'postfix_expression : postfix_expression PERIOD ID'
pass | [
"def",
"p_postfix_expression_5",
"(",
"t",
")",
":",
"pass"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L809-L811 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mailcap.py | python | listmailcapfiles | () | return mailcaps | Return a list of all mailcap files found on the system. | Return a list of all mailcap files found on the system. | [
"Return",
"a",
"list",
"of",
"all",
"mailcap",
"files",
"found",
"on",
"the",
"system",
"."
] | def listmailcapfiles():
"""Return a list of all mailcap files found on the system."""
# XXX Actually, this is Unix-specific
if 'MAILCAPS' in os.environ:
str = os.environ['MAILCAPS']
mailcaps = str.split(':')
else:
if 'HOME' in os.environ:
home = os.environ['HOME']
else:
# Don't bother with getpwuid()
home = '.' # Last resort
mailcaps = [home + '/.mailcap', '/etc/mailcap',
'/usr/etc/mailcap', '/usr/local/etc/mailcap']
return mailcaps | [
"def",
"listmailcapfiles",
"(",
")",
":",
"# XXX Actually, this is Unix-specific",
"if",
"'MAILCAPS'",
"in",
"os",
".",
"environ",
":",
"str",
"=",
"os",
".",
"environ",
"[",
"'MAILCAPS'",
"]",
"mailcaps",
"=",
"str",
".",
"split",
"(",
"':'",
")",
"else",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailcap.py#L34-L48 | |
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | src/lib/parameters/px4params/srcparser.py | python | Parameter.GetBitmaskBit | (self, index) | return fv.strip() | Return value of the given bitmask code or None if not found. | Return value of the given bitmask code or None if not found. | [
"Return",
"value",
"of",
"the",
"given",
"bitmask",
"code",
"or",
"None",
"if",
"not",
"found",
"."
] | def GetBitmaskBit(self, index):
"""
Return value of the given bitmask code or None if not found.
"""
fv = self.bitmask.get(index)
if not fv:
# required because python 3 sorted does not accept None
return ""
return fv.strip() | [
"def",
"GetBitmaskBit",
"(",
"self",
",",
"index",
")",
":",
"fv",
"=",
"self",
".",
"bitmask",
".",
"get",
"(",
"index",
")",
"if",
"not",
"fv",
":",
"# required because python 3 sorted does not accept None",
"return",
"\"\"",
"return",
"fv",
".",
"strip",
... | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/src/lib/parameters/px4params/srcparser.py#L161-L169 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Script/Interactive.py | python | SConsInteractiveCmd.do_build | (self, argv) | \
build [TARGETS] Build the specified TARGETS and their
dependencies. 'b' is a synonym. | \
build [TARGETS] Build the specified TARGETS and their
dependencies. 'b' is a synonym. | [
"\\",
"build",
"[",
"TARGETS",
"]",
"Build",
"the",
"specified",
"TARGETS",
"and",
"their",
"dependencies",
".",
"b",
"is",
"a",
"synonym",
"."
] | def do_build(self, argv):
"""\
build [TARGETS] Build the specified TARGETS and their
dependencies. 'b' is a synonym.
"""
import SCons.Node
import SCons.SConsign
import SCons.Script.Main
options = copy.deepcopy(self.options)
options, targets = self.parser.parse_args(argv[1:], values=options)
SCons.Script.COMMAND_LINE_TARGETS = targets
if targets:
SCons.Script.BUILD_TARGETS = targets
else:
# If the user didn't specify any targets on the command line,
# use the list of default targets.
SCons.Script.BUILD_TARGETS = SCons.Script._build_plus_default
nodes = SCons.Script.Main._build_targets(self.fs,
options,
targets,
self.target_top)
if not nodes:
return
# Call each of the Node's alter_targets() methods, which may
# provide additional targets that ended up as part of the build
# (the canonical example being a VariantDir() when we're building
# from a source directory) and which we therefore need their
# state cleared, too.
x = []
for n in nodes:
x.extend(n.alter_targets()[0])
nodes.extend(x)
# Clean up so that we can perform the next build correctly.
#
# We do this by walking over all the children of the targets,
# and clearing their state.
#
# We currently have to re-scan each node to find their
# children, because built nodes have already been partially
# cleared and don't remember their children. (In scons
# 0.96.1 and earlier, this wasn't the case, and we didn't
# have to re-scan the nodes.)
#
# Because we have to re-scan each node, we can't clear the
# nodes as we walk over them, because we may end up rescanning
# a cleared node as we scan a later node. Therefore, only
# store the list of nodes that need to be cleared as we walk
# the tree, and clear them in a separate pass.
#
# XXX: Someone more familiar with the inner workings of scons
# may be able to point out a more efficient way to do this.
SCons.Script.Main.progress_display("scons: Clearing cached node information ...")
seen_nodes = {}
def get_unseen_children(node, parent, seen_nodes=seen_nodes):
def is_unseen(node, seen_nodes=seen_nodes):
return node not in seen_nodes
return [child for child in node.children(scan=1) if is_unseen(child)]
def add_to_seen_nodes(node, parent, seen_nodes=seen_nodes):
seen_nodes[node] = 1
# If this file is in a VariantDir and has a
# corresponding source file in the source tree, remember the
# node in the source tree, too. This is needed in
# particular to clear cached implicit dependencies on the
# source file, since the scanner will scan it if the
# VariantDir was created with duplicate=0.
try:
rfile_method = node.rfile
except AttributeError:
return
else:
rfile = rfile_method()
if rfile != node:
seen_nodes[rfile] = 1
for node in nodes:
walker = SCons.Node.Walker(node,
kids_func=get_unseen_children,
eval_func=add_to_seen_nodes)
n = walker.get_next()
while n:
n = walker.get_next()
for node in seen_nodes.keys():
# Call node.clear() to clear most of the state
node.clear()
# node.clear() doesn't reset node.state, so call
# node.set_state() to reset it manually
node.set_state(SCons.Node.no_state)
node.implicit = None
# Debug: Uncomment to verify that all Taskmaster reference
# counts have been reset to zero.
#if node.ref_count != 0:
# from SCons.Debug import Trace
# Trace('node %s, ref_count %s !!!\n' % (node, node.ref_count))
SCons.SConsign.Reset()
SCons.Script.Main.progress_display("scons: done clearing node information.") | [
"def",
"do_build",
"(",
"self",
",",
"argv",
")",
":",
"import",
"SCons",
".",
"Node",
"import",
"SCons",
".",
"SConsign",
"import",
"SCons",
".",
"Script",
".",
"Main",
"options",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"options",
")",
"option... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Script/Interactive.py#L151-L261 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/function.py | python | ConcreteFunction.__call__ | (self, *args, **kwargs) | return self._call_impl(args, kwargs) | Executes the wrapped function.
Args:
*args: Tensors or Variables. Positional arguments are only accepted when
they correspond one-to-one with arguments of the traced Python function.
**kwargs: Tensors or Variables specified by name. When
`get_concrete_function` was called to create this `ConcreteFunction`,
each Tensor input was given a name, defaulting to the name of the Python
function's argument but possibly overridden by the `name=` argument to
`tf.TensorSpec`. These names become the argument names for the concrete
function.
Returns:
The result of applying the TF function on the given Tensors.
Raises:
AssertionError: If this `ConcreteFunction` was not created through
`get_concrete_function`.
ValueError: If arguments contains anything other than Tensors or
Variables.
TypeError: For invalid positional/keyword argument combinations. | Executes the wrapped function. | [
"Executes",
"the",
"wrapped",
"function",
"."
] | def __call__(self, *args, **kwargs):
"""Executes the wrapped function.
Args:
*args: Tensors or Variables. Positional arguments are only accepted when
they correspond one-to-one with arguments of the traced Python function.
**kwargs: Tensors or Variables specified by name. When
`get_concrete_function` was called to create this `ConcreteFunction`,
each Tensor input was given a name, defaulting to the name of the Python
function's argument but possibly overridden by the `name=` argument to
`tf.TensorSpec`. These names become the argument names for the concrete
function.
Returns:
The result of applying the TF function on the given Tensors.
Raises:
AssertionError: If this `ConcreteFunction` was not created through
`get_concrete_function`.
ValueError: If arguments contains anything other than Tensors or
Variables.
TypeError: For invalid positional/keyword argument combinations.
"""
return self._call_impl(args, kwargs) | [
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_call_impl",
"(",
"args",
",",
"kwargs",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/function.py#L1058-L1081 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py | python | Node.pre_order | (self) | Return a pre-order iterator for the tree. | Return a pre-order iterator for the tree. | [
"Return",
"a",
"pre",
"-",
"order",
"iterator",
"for",
"the",
"tree",
"."
] | def pre_order(self):
"""Return a pre-order iterator for the tree."""
yield self
for child in self.children:
yield from child.pre_order() | [
"def",
"pre_order",
"(",
"self",
")",
":",
"yield",
"self",
"for",
"child",
"in",
"self",
".",
"children",
":",
"yield",
"from",
"child",
".",
"pre_order",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/lib2to3/pytree.py#L268-L272 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/extras/review.py | python | ReviewContext.import_review_set | (self, review_set) | Import the actual value of the reviewable options in the option
dictionary, given the current review set. | Import the actual value of the reviewable options in the option
dictionary, given the current review set. | [
"Import",
"the",
"actual",
"value",
"of",
"the",
"reviewable",
"options",
"in",
"the",
"option",
"dictionary",
"given",
"the",
"current",
"review",
"set",
"."
] | def import_review_set(self, review_set):
"""
Import the actual value of the reviewable options in the option
dictionary, given the current review set.
"""
for name in review_options.keys():
if name in review_set:
value = review_set[name]
else:
value = review_defaults[name]
setattr(Options.options, name, value) | [
"def",
"import_review_set",
"(",
"self",
",",
"review_set",
")",
":",
"for",
"name",
"in",
"review_options",
".",
"keys",
"(",
")",
":",
"if",
"name",
"in",
"review_set",
":",
"value",
"=",
"review_set",
"[",
"name",
"]",
"else",
":",
"value",
"=",
"re... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/extras/review.py#L235-L245 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/reshape/tile.py | python | qcut | (x, q, labels=None, retbins=False, precision=3, duplicates='raise') | return _postprocess_for_cut(fac, bins, retbins, x_is_series,
series_index, name, dtype) | Quantile-based discretization function. Discretize variable into
equal-sized buckets based on rank or based on sample quantiles. For example
1000 values for 10 quantiles would produce a Categorical object indicating
quantile membership for each data point.
Parameters
----------
x : 1d ndarray or Series
q : integer or array of quantiles
Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately
array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles
labels : array or boolean, default None
Used as labels for the resulting bins. Must be of the same length as
the resulting bins. If False, return only integer indicators of the
bins.
retbins : bool, optional
Whether to return the (bins, labels) or not. Can be useful if bins
is given as a scalar.
precision : int, optional
The precision at which to store and display the bins labels
duplicates : {default 'raise', 'drop'}, optional
If bin edges are not unique, raise ValueError or drop non-uniques.
.. versionadded:: 0.20.0
Returns
-------
out : Categorical or Series or array of integers if labels is False
The return type (Categorical or Series) depends on the input: a Series
of type category if input is a Series else Categorical. Bins are
represented as categories when categorical data is returned.
bins : ndarray of floats
Returned only if `retbins` is True.
Notes
-----
Out of bounds values will be NA in the resulting Categorical object
Examples
--------
>>> pd.qcut(range(5), 4)
... # doctest: +ELLIPSIS
[(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]
Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ...
>>> pd.qcut(range(5), 3, labels=["good", "medium", "bad"])
... # doctest: +SKIP
[good, good, medium, bad, bad]
Categories (3, object): [good < medium < bad]
>>> pd.qcut(range(5), 4, labels=False)
array([0, 0, 1, 2, 3]) | Quantile-based discretization function. Discretize variable into
equal-sized buckets based on rank or based on sample quantiles. For example
1000 values for 10 quantiles would produce a Categorical object indicating
quantile membership for each data point. | [
"Quantile",
"-",
"based",
"discretization",
"function",
".",
"Discretize",
"variable",
"into",
"equal",
"-",
"sized",
"buckets",
"based",
"on",
"rank",
"or",
"based",
"on",
"sample",
"quantiles",
".",
"For",
"example",
"1000",
"values",
"for",
"10",
"quantiles... | def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'):
"""
Quantile-based discretization function. Discretize variable into
equal-sized buckets based on rank or based on sample quantiles. For example
1000 values for 10 quantiles would produce a Categorical object indicating
quantile membership for each data point.
Parameters
----------
x : 1d ndarray or Series
q : integer or array of quantiles
Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately
array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles
labels : array or boolean, default None
Used as labels for the resulting bins. Must be of the same length as
the resulting bins. If False, return only integer indicators of the
bins.
retbins : bool, optional
Whether to return the (bins, labels) or not. Can be useful if bins
is given as a scalar.
precision : int, optional
The precision at which to store and display the bins labels
duplicates : {default 'raise', 'drop'}, optional
If bin edges are not unique, raise ValueError or drop non-uniques.
.. versionadded:: 0.20.0
Returns
-------
out : Categorical or Series or array of integers if labels is False
The return type (Categorical or Series) depends on the input: a Series
of type category if input is a Series else Categorical. Bins are
represented as categories when categorical data is returned.
bins : ndarray of floats
Returned only if `retbins` is True.
Notes
-----
Out of bounds values will be NA in the resulting Categorical object
Examples
--------
>>> pd.qcut(range(5), 4)
... # doctest: +ELLIPSIS
[(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]
Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ...
>>> pd.qcut(range(5), 3, labels=["good", "medium", "bad"])
... # doctest: +SKIP
[good, good, medium, bad, bad]
Categories (3, object): [good < medium < bad]
>>> pd.qcut(range(5), 4, labels=False)
array([0, 0, 1, 2, 3])
"""
x_is_series, series_index, name, x = _preprocess_for_cut(x)
x, dtype = _coerce_to_type(x)
if is_integer(q):
quantiles = np.linspace(0, 1, q + 1)
else:
quantiles = q
bins = algos.quantile(x, quantiles)
fac, bins = _bins_to_cuts(x, bins, labels=labels,
precision=precision, include_lowest=True,
dtype=dtype, duplicates=duplicates)
return _postprocess_for_cut(fac, bins, retbins, x_is_series,
series_index, name, dtype) | [
"def",
"qcut",
"(",
"x",
",",
"q",
",",
"labels",
"=",
"None",
",",
"retbins",
"=",
"False",
",",
"precision",
"=",
"3",
",",
"duplicates",
"=",
"'raise'",
")",
":",
"x_is_series",
",",
"series_index",
",",
"name",
",",
"x",
"=",
"_preprocess_for_cut",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/reshape/tile.py#L247-L316 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/gxx.py | python | gxx_common_flags | (conf) | Common flags for g++ on nearly all platforms | Common flags for g++ on nearly all platforms | [
"Common",
"flags",
"for",
"g",
"++",
"on",
"nearly",
"all",
"platforms"
] | def gxx_common_flags(conf):
"""
Common flags for g++ on nearly all platforms
"""
v = conf.env
v.CXX_SRC_F = []
v.CXX_TGT_F = ['-c', '-o']
if not v.LINK_CXX:
v.LINK_CXX = v.CXX
v.CXXLNK_SRC_F = []
v.CXXLNK_TGT_F = ['-o']
v.CPPPATH_ST = '-I%s'
v.DEFINES_ST = '-D%s'
v.LIB_ST = '-l%s' # template for adding libs
v.LIBPATH_ST = '-L%s' # template for adding libpaths
v.STLIB_ST = '-l%s'
v.STLIBPATH_ST = '-L%s'
v.RPATH_ST = '-Wl,-rpath,%s'
v.SONAME_ST = '-Wl,-h,%s'
v.SHLIB_MARKER = '-Wl,-Bdynamic'
v.STLIB_MARKER = '-Wl,-Bstatic'
v.cxxprogram_PATTERN = '%s'
v.CXXFLAGS_cxxshlib = ['-fPIC']
v.LINKFLAGS_cxxshlib = ['-shared']
v.cxxshlib_PATTERN = 'lib%s.so'
v.LINKFLAGS_cxxstlib = ['-Wl,-Bstatic']
v.cxxstlib_PATTERN = 'lib%s.a'
v.LINKFLAGS_MACBUNDLE = ['-bundle', '-undefined', 'dynamic_lookup']
v.CXXFLAGS_MACBUNDLE = ['-fPIC']
v.macbundle_PATTERN = '%s.bundle' | [
"def",
"gxx_common_flags",
"(",
"conf",
")",
":",
"v",
"=",
"conf",
".",
"env",
"v",
".",
"CXX_SRC_F",
"=",
"[",
"]",
"v",
".",
"CXX_TGT_F",
"=",
"[",
"'-c'",
",",
"'-o'",
"]",
"if",
"not",
"v",
".",
"LINK_CXX",
":",
"v",
".",
"LINK_CXX",
"=",
... | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/gxx.py#L24-L62 | ||
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/context.py | python | Context.detect_framebuffer | (self, glo=None) | return res | Detect framebuffer. This is already done when creating a context,
but if the underlying window library for some changes the default framebuffer
during the lifetime of the application this might be necessary.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object | Detect framebuffer. This is already done when creating a context,
but if the underlying window library for some changes the default framebuffer
during the lifetime of the application this might be necessary. | [
"Detect",
"framebuffer",
".",
"This",
"is",
"already",
"done",
"when",
"creating",
"a",
"context",
"but",
"if",
"the",
"underlying",
"window",
"library",
"for",
"some",
"changes",
"the",
"default",
"framebuffer",
"during",
"the",
"lifetime",
"of",
"the",
"appl... | def detect_framebuffer(self, glo=None) -> 'Framebuffer':
'''
Detect framebuffer. This is already done when creating a context,
but if the underlying window library for some changes the default framebuffer
during the lifetime of the application this might be necessary.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object
'''
res = Framebuffer.__new__(Framebuffer)
res.mglo, res._size, res._samples, res._glo = self.mglo.detect_framebuffer(glo)
res._color_attachments = None
res._depth_attachment = None
res.ctx = self
res._is_reference = True
res.extra = None
return res | [
"def",
"detect_framebuffer",
"(",
"self",
",",
"glo",
"=",
"None",
")",
"->",
"'Framebuffer'",
":",
"res",
"=",
"Framebuffer",
".",
"__new__",
"(",
"Framebuffer",
")",
"res",
".",
"mglo",
",",
"res",
".",
"_size",
",",
"res",
".",
"_samples",
",",
"res... | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/context.py#L1067-L1087 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/monitoring.py | python | SocketPublisher.__init__ | (self, socket, host, port, serializer) | Publishes monitor events to a socket
:type socket: socket.socket
:param socket: The socket object to use to publish events
:type host: string
:param host: The host to send events to
:type port: integer
:param port: The port on the host to send events to
:param serializer: The serializer to use to serialize the event
to a form that can be published to the socket. This must
have a `serialize()` method that accepts a monitor event
and return bytes | Publishes monitor events to a socket | [
"Publishes",
"monitor",
"events",
"to",
"a",
"socket"
] | def __init__(self, socket, host, port, serializer):
"""Publishes monitor events to a socket
:type socket: socket.socket
:param socket: The socket object to use to publish events
:type host: string
:param host: The host to send events to
:type port: integer
:param port: The port on the host to send events to
:param serializer: The serializer to use to serialize the event
to a form that can be published to the socket. This must
have a `serialize()` method that accepts a monitor event
and return bytes
"""
self._socket = socket
self._address = (host, port)
self._serializer = serializer | [
"def",
"__init__",
"(",
"self",
",",
"socket",
",",
"host",
",",
"port",
",",
"serializer",
")",
":",
"self",
".",
"_socket",
"=",
"socket",
"self",
".",
"_address",
"=",
"(",
"host",
",",
"port",
")",
"self",
".",
"_serializer",
"=",
"serializer"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/monitoring.py#L514-L533 | ||
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/roi_data_layer/layer.py | python | BlobFetcher._get_next_minibatch_inds | (self) | return db_inds | Return the roidb indices for the next minibatch. | Return the roidb indices for the next minibatch. | [
"Return",
"the",
"roidb",
"indices",
"for",
"the",
"next",
"minibatch",
"."
] | def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next minibatch."""
# TODO(rbg): remove duplicated code
if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]
self._cur += cfg.TRAIN.IMS_PER_BATCH
return db_inds | [
"def",
"_get_next_minibatch_inds",
"(",
"self",
")",
":",
"# TODO(rbg): remove duplicated code",
"if",
"self",
".",
"_cur",
"+",
"cfg",
".",
"TRAIN",
".",
"IMS_PER_BATCH",
">=",
"len",
"(",
"self",
".",
"_roidb",
")",
":",
"self",
".",
"_shuffle_roidb_inds",
"... | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/roi_data_layer/layer.py#L195-L203 | |
MhLiao/TextBoxes_plusplus | 39d4898de1504c53a2ed3d67966a57b3595836d0 | scripts/cpp_lint.py | python | _NestingState.CheckCompletedBlocks | (self, filename, error) | Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found. | Checks that all classes and namespaces have been completely parsed. | [
"Checks",
"that",
"all",
"classes",
"and",
"namespaces",
"have",
"been",
"completely",
"parsed",
"."
] | def CheckCompletedBlocks(self, filename, error):
"""Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
elif isinstance(obj, _NamespaceInfo):
error(filename, obj.starting_linenum, 'build/namespaces', 5,
'Failed to find complete declaration of namespace %s' %
obj.name) | [
"def",
"CheckCompletedBlocks",
"(",
"self",
",",
"filename",
",",
"error",
")",
":",
"# Note: This test can result in false positives if #ifdef constructs",
"# get in the way of brace matching. See the testBuildClass test in",
"# cpplint_unittest.py for an example of this.",
"for",
"obj"... | https://github.com/MhLiao/TextBoxes_plusplus/blob/39d4898de1504c53a2ed3d67966a57b3595836d0/scripts/cpp_lint.py#L2176-L2195 | ||
martinrotter/textosaurus | 4e2ad75abaf5b7e6a823766a2aa8a30f0c965cb8 | src/libtextosaurus/3rd-party/scintilla/scripts/FileGenerator.py | python | Generate | (inpath, outpath, commentPrefix, *lists) | Generate 'outpath' from 'inpath'. | Generate 'outpath' from 'inpath'. | [
"Generate",
"outpath",
"from",
"inpath",
"."
] | def Generate(inpath, outpath, commentPrefix, *lists):
"""Generate 'outpath' from 'inpath'.
"""
GenerateFile(inpath, outpath, commentPrefix, inpath == outpath, *lists) | [
"def",
"Generate",
"(",
"inpath",
",",
"outpath",
",",
"commentPrefix",
",",
"*",
"lists",
")",
":",
"GenerateFile",
"(",
"inpath",
",",
"outpath",
",",
"commentPrefix",
",",
"inpath",
"==",
"outpath",
",",
"*",
"lists",
")"
] | https://github.com/martinrotter/textosaurus/blob/4e2ad75abaf5b7e6a823766a2aa8a30f0c965cb8/src/libtextosaurus/3rd-party/scintilla/scripts/FileGenerator.py#L130-L133 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/layers/python/layers/layers.py | python | bias_add | (inputs,
activation_fn=None,
initializer=init_ops.zeros_initializer,
regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None) | Adds a bias to the inputs.
Can be used as a normalizer function for conv2d and fully_connected.
Args:
inputs: a tensor of with at least rank 2 and value for the last dimension,
e.g. `[batch_size, depth]`, `[None, None, None, depth]`.
activation_fn: activation function, default set to None to skip it and
maintain a linear activation.
initializer: An initializer for the bias, defaults to 0.
regularizer: A regularizer like the result of
`l1_regularizer` or `l2_regularizer`.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: optional collections for the variables.
outputs_collections: collections to add the outputs.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for variable_scope.
Returns:
a tensor representing the result of adding biases to the inputs. | Adds a bias to the inputs. | [
"Adds",
"a",
"bias",
"to",
"the",
"inputs",
"."
] | def bias_add(inputs,
activation_fn=None,
initializer=init_ops.zeros_initializer,
regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
"""Adds a bias to the inputs.
Can be used as a normalizer function for conv2d and fully_connected.
Args:
inputs: a tensor of with at least rank 2 and value for the last dimension,
e.g. `[batch_size, depth]`, `[None, None, None, depth]`.
activation_fn: activation function, default set to None to skip it and
maintain a linear activation.
initializer: An initializer for the bias, defaults to 0.
regularizer: A regularizer like the result of
`l1_regularizer` or `l2_regularizer`.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: optional collections for the variables.
outputs_collections: collections to add the outputs.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for variable_scope.
Returns:
a tensor representing the result of adding biases to the inputs.
"""
with variable_scope.variable_scope(scope, 'BiasAdd', [inputs],
reuse=reuse) as sc:
inputs = ops.convert_to_tensor(inputs)
dtype = inputs.dtype.base_dtype
num_features = utils.last_dimension(inputs.get_shape(), min_rank=2)
biases_collections = utils.get_variable_collections(variables_collections,
'biases')
biases = variables.model_variable('biases',
shape=[num_features,],
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
collections=biases_collections,
trainable=trainable)
outputs = nn.bias_add(inputs, biases)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections,
sc.original_name_scope, outputs) | [
"def",
"bias_add",
"(",
"inputs",
",",
"activation_fn",
"=",
"None",
",",
"initializer",
"=",
"init_ops",
".",
"zeros_initializer",
",",
"regularizer",
"=",
"None",
",",
"reuse",
"=",
"None",
",",
"variables_collections",
"=",
"None",
",",
"outputs_collections",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/layers.py#L312-L362 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros/rosmake/src/rosmake/engine.py | python | RosMakeAll.num_packages_built | (self) | return len(list(self.result[argument].keys())) | @return: number of packages that were built
@rtype: int | [] | def num_packages_built(self):
"""
@return: number of packages that were built
@rtype: int
"""
return len(list(self.result[argument].keys())) | [
"def",
"num_packages_built",
"(",
"self",
")",
":",
"return",
"len",
"(",
"list",
"(",
"self",
".",
"result",
"[",
"argument",
"]",
".",
"keys",
"(",
")",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/rosmake/src/rosmake/engine.py#L302-L307 | ||
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert/modeling.py | python | transformer_model | (input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
do_return_all_layers=False) | Multi-headed, multi-layer Transformer from "Attention is All You Need".
This is almost an exact implementation of the original Transformer encoder.
See the original paper:
https://arxiv.org/abs/1706.03762
Also see:
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,
seq_length], with 1 for positions that can be attended to and 0 in
positions that should not be.
hidden_size: int. Hidden size of the Transformer.
num_hidden_layers: int. Number of layers (blocks) in the Transformer.
num_attention_heads: int. Number of attention heads in the Transformer.
intermediate_size: int. The size of the "intermediate" (a.k.a., feed
forward) layer.
intermediate_act_fn: function. The non-linear activation function to apply
to the output of the intermediate/feed-forward layer.
hidden_dropout_prob: float. Dropout probability for the hidden layers.
attention_probs_dropout_prob: float. Dropout probability of the attention
probabilities.
initializer_range: float. Range of the initializer (stddev of truncated
normal).
do_return_all_layers: Whether to also return all layers or just the final
layer.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size], the final
hidden layer of the Transformer.
Raises:
ValueError: A Tensor shape or parameter is invalid. | Multi-headed, multi-layer Transformer from "Attention is All You Need". | [
"Multi",
"-",
"headed",
"multi",
"-",
"layer",
"Transformer",
"from",
"Attention",
"is",
"All",
"You",
"Need",
"."
] | def transformer_model(input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
do_return_all_layers=False):
"""Multi-headed, multi-layer Transformer from "Attention is All You Need".
This is almost an exact implementation of the original Transformer encoder.
See the original paper:
https://arxiv.org/abs/1706.03762
Also see:
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,
seq_length], with 1 for positions that can be attended to and 0 in
positions that should not be.
hidden_size: int. Hidden size of the Transformer.
num_hidden_layers: int. Number of layers (blocks) in the Transformer.
num_attention_heads: int. Number of attention heads in the Transformer.
intermediate_size: int. The size of the "intermediate" (a.k.a., feed
forward) layer.
intermediate_act_fn: function. The non-linear activation function to apply
to the output of the intermediate/feed-forward layer.
hidden_dropout_prob: float. Dropout probability for the hidden layers.
attention_probs_dropout_prob: float. Dropout probability of the attention
probabilities.
initializer_range: float. Range of the initializer (stddev of truncated
normal).
do_return_all_layers: Whether to also return all layers or just the final
layer.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size], the final
hidden layer of the Transformer.
Raises:
ValueError: A Tensor shape or parameter is invalid.
"""
if hidden_size % num_attention_heads != 0:
raise ValueError(
"The hidden size (%d) is not a multiple of the number of attention "
"heads (%d)" % (hidden_size, num_attention_heads))
attention_head_size = int(hidden_size / num_attention_heads)
input_shape = get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
input_width = input_shape[2]
# The Transformer performs sum residuals on all layers so the input needs
# to be the same as the hidden size.
if input_width != hidden_size:
raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
(input_width, hidden_size))
# We keep the representation as a 2D tensor to avoid re-shaping it back and
# forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
# the GPU/CPU but may not be free on the TPU, so we want to minimize them to
# help the optimizer.
prev_output = reshape_to_matrix(input_tensor)
all_layer_outputs = []
for layer_idx in range(num_hidden_layers):
with tf.variable_scope("layer_%d" % layer_idx):
layer_input = prev_output
with tf.variable_scope("attention"):
attention_heads = []
with tf.variable_scope("self"):
attention_head = attention_layer(
from_tensor=layer_input,
to_tensor=layer_input,
attention_mask=attention_mask,
num_attention_heads=num_attention_heads,
size_per_head=attention_head_size,
attention_probs_dropout_prob=attention_probs_dropout_prob,
initializer_range=initializer_range,
do_return_2d_tensor=True,
batch_size=batch_size,
from_seq_length=seq_length,
to_seq_length=seq_length)
attention_heads.append(attention_head)
attention_output = None
if len(attention_heads) == 1:
attention_output = attention_heads[0]
else:
# In the case where we have other sequences, we just concatenate
# them to the self-attention head before the projection.
attention_output = tf.concat(attention_heads, axis=-1)
# Run a linear projection of `hidden_size` then add a residual
# with `layer_input`.
with tf.variable_scope("output"):
attention_output = tf.layers.dense(
attention_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
attention_output = dropout(attention_output, hidden_dropout_prob)
attention_output = layer_norm(attention_output + layer_input)
# The activation is only applied to the "intermediate" hidden layer.
with tf.variable_scope("intermediate"):
intermediate_output = tf.layers.dense(
attention_output,
intermediate_size,
activation=intermediate_act_fn,
kernel_initializer=create_initializer(initializer_range))
# Down-project back to `hidden_size` then add the residual.
with tf.variable_scope("output"):
layer_output = tf.layers.dense(
intermediate_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
layer_output = dropout(layer_output, hidden_dropout_prob)
layer_output = layer_norm(layer_output + attention_output)
prev_output = layer_output
all_layer_outputs.append(layer_output)
if do_return_all_layers:
final_outputs = []
for layer_output in all_layer_outputs:
final_output = reshape_from_matrix(layer_output, input_shape)
final_outputs.append(final_output)
return final_outputs
else:
final_output = reshape_from_matrix(prev_output, input_shape)
return final_output | [
"def",
"transformer_model",
"(",
"input_tensor",
",",
"attention_mask",
"=",
"None",
",",
"hidden_size",
"=",
"768",
",",
"num_hidden_layers",
"=",
"12",
",",
"num_attention_heads",
"=",
"12",
",",
"intermediate_size",
"=",
"3072",
",",
"intermediate_act_fn",
"=",... | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert/modeling.py#L754-L892 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/numbers.py | python | Complex.__complex__ | (self) | Return a builtin complex instance. Called for complex(self). | Return a builtin complex instance. Called for complex(self). | [
"Return",
"a",
"builtin",
"complex",
"instance",
".",
"Called",
"for",
"complex",
"(",
"self",
")",
"."
] | def __complex__(self):
"""Return a builtin complex instance. Called for complex(self).""" | [
"def",
"__complex__",
"(",
"self",
")",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/numbers.py#L46-L47 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/PrecisionRecall.py | python | PrecisionRecall.reset | (self) | return self._internal.get_reset() | Checks if the statistics will be reset after each run. | Checks if the statistics will be reset after each run. | [
"Checks",
"if",
"the",
"statistics",
"will",
"be",
"reset",
"after",
"each",
"run",
"."
] | def reset(self):
"""Checks if the statistics will be reset after each run.
"""
return self._internal.get_reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"return",
"self",
".",
"_internal",
".",
"get_reset",
"(",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/PrecisionRecall.py#L71-L74 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/preprocessing/_label.py | python | LabelEncoder.fit | (self, y) | return self | Fit label encoder
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
self : returns an instance of self. | Fit label encoder | [
"Fit",
"label",
"encoder"
] | def fit(self, y):
"""Fit label encoder
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
self : returns an instance of self.
"""
y = column_or_1d(y, warn=True)
self.classes_ = _encode(y)
return self | [
"def",
"fit",
"(",
"self",
",",
"y",
")",
":",
"y",
"=",
"column_or_1d",
"(",
"y",
",",
"warn",
"=",
"True",
")",
"self",
".",
"classes_",
"=",
"_encode",
"(",
"y",
")",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/preprocessing/_label.py#L223-L237 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column.py | python | InputLayer.__init__ | (self,
feature_columns,
weight_collections=None,
trainable=True,
cols_to_vars=None,
name='feature_column_input_layer',
create_scope_now=True) | See `input_layer`. | See `input_layer`. | [
"See",
"input_layer",
"."
] | def __init__(self,
feature_columns,
weight_collections=None,
trainable=True,
cols_to_vars=None,
name='feature_column_input_layer',
create_scope_now=True):
"""See `input_layer`."""
self._feature_columns = feature_columns
self._weight_collections = weight_collections
self._trainable = trainable
self._cols_to_vars = cols_to_vars
self._name = name
self._input_layer_template = template.make_template(
self._name, _internal_input_layer, create_scope_now_=create_scope_now)
self._scope = self._input_layer_template.variable_scope | [
"def",
"__init__",
"(",
"self",
",",
"feature_columns",
",",
"weight_collections",
"=",
"None",
",",
"trainable",
"=",
"True",
",",
"cols_to_vars",
"=",
"None",
",",
"name",
"=",
"'feature_column_input_layer'",
",",
"create_scope_now",
"=",
"True",
")",
":",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column.py#L308-L324 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/categorical.py | python | Categorical.base | (self) | return None | compat, we are always our own object | compat, we are always our own object | [
"compat",
"we",
"are",
"always",
"our",
"own",
"object"
] | def base(self):
"""
compat, we are always our own object
"""
return None | [
"def",
"base",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/categorical.py#L530-L534 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/tensor_array_grad.py | python | _TensorArrayUnpackGrad | (op, flow) | return [None, grad, flow] | Gradient for TensorArrayUnpack.
Args:
op: Forward TensorArrayUnpack op.
flow: Gradient `Tensor` flow to TensorArrayUnpack.
Returns:
A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad. | Gradient for TensorArrayUnpack. | [
"Gradient",
"for",
"TensorArrayUnpack",
"."
] | def _TensorArrayUnpackGrad(op, flow):
"""Gradient for TensorArrayUnpack.
Args:
op: Forward TensorArrayUnpack op.
flow: Gradient `Tensor` flow to TensorArrayUnpack.
Returns:
A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad.
"""
handle = op.inputs[0]
dtype = op.get_attr("T")
grad_source = _GetGradSource(flow)
g = tensor_array_ops.TensorArray(dtype=dtype, handle=handle).grad(
source=grad_source, flow=flow)
grad = g.pack()
return [None, grad, flow] | [
"def",
"_TensorArrayUnpackGrad",
"(",
"op",
",",
"flow",
")",
":",
"handle",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"dtype",
"=",
"op",
".",
"get_attr",
"(",
"\"T\"",
")",
"grad_source",
"=",
"_GetGradSource",
"(",
"flow",
")",
"g",
"=",
"tensor_arra... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/tensor_array_grad.py#L147-L163 | |
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | Cursor.lexical_parent | (self) | return self._lexical_parent | Return the lexical parent for this cursor. | Return the lexical parent for this cursor. | [
"Return",
"the",
"lexical",
"parent",
"for",
"this",
"cursor",
"."
] | def lexical_parent(self):
"""Return the lexical parent for this cursor."""
if not hasattr(self, '_lexical_parent'):
self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
return self._lexical_parent | [
"def",
"lexical_parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_lexical_parent'",
")",
":",
"self",
".",
"_lexical_parent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorLexicalParent",
"(",
"self",
")",
"return",
"self",
".",
... | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1260-L1265 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/notebook/callback.py | python | PandasLogger.train_df | (self) | return self._dataframes['train'] | The dataframe with training data.
This has metrics for training minibatches, logged every
"frequent" batches. (frequent is a constructor param) | The dataframe with training data.
This has metrics for training minibatches, logged every
"frequent" batches. (frequent is a constructor param) | [
"The",
"dataframe",
"with",
"training",
"data",
".",
"This",
"has",
"metrics",
"for",
"training",
"minibatches",
"logged",
"every",
"frequent",
"batches",
".",
"(",
"frequent",
"is",
"a",
"constructor",
"param",
")"
] | def train_df(self):
"""The dataframe with training data.
This has metrics for training minibatches, logged every
"frequent" batches. (frequent is a constructor param)
"""
return self._dataframes['train'] | [
"def",
"train_df",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dataframes",
"[",
"'train'",
"]"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/notebook/callback.py#L98-L103 | |
eric612/Caffe-YOLOv3-Windows | 6736ca6e16781789b828cc64218ff77cc3454e5d | scripts/cpp_lint.py | python | CheckCStyleCast | (filename, linenum, line, raw_line, cast_type, pattern,
error) | return True | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise. | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C",
"-",
"style",
"cast",
"by",
"looking",
"for",
"the",
"pattern",
"."
] | def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
match = Search(pattern, line)
if not match:
return False
# Exclude lines with sizeof, since sizeof looks like a cast.
sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
if sizeof_match:
return False
# operator++(int) and operator--(int)
if (line[0:match.start(1) - 1].endswith(' operator++') or
line[0:match.start(1) - 1].endswith(' operator--')):
return False
# A single unnamed argument for a function tends to look like old
# style cast. If we see those, don't issue warnings for deprecated
# casts, instead issue warnings for unnamed arguments where
# appropriate.
#
# These are things that we want warnings for, since the style guide
# explicitly require all parameters to be named:
# Function(int);
# Function(int) {
# ConstMember(int) const;
# ConstMember(int) const {
# ExceptionMember(int) throw (...);
# ExceptionMember(int) throw (...) {
# PureVirtual(int) = 0;
#
# These are functions of some sort, where the compiler would be fine
# if they had named parameters, but people often omit those
# identifiers to reduce clutter:
# (FunctionPointer)(int);
# (FunctionPointer)(int) = value;
# Function((function_pointer_arg)(int))
# <TemplateArgument(int)>;
# <(FunctionPointerTemplateArgument)(int)>;
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder):
# Looks like an unnamed parameter.
# Don't warn on any kind of template arguments.
if Match(r'^\s*>', remainder):
return False
# Don't warn on assignments to function pointers, but keep warnings for
# unnamed parameters to pure virtual functions. Note that this pattern
# will also pass on assignments of "0" to function pointers, but the
# preferred values for those would be "nullptr" or "NULL".
matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
if matched_zero and matched_zero.group(1) != '0':
return False
# Don't warn on function pointer declarations. For this we need
# to check what came before the "(type)" string.
if Match(r'.*\)\s*$', line[0:match.start(0)]):
return False
# Don't warn if the parameter is named with block comments, e.g.:
# Function(int /*unused_param*/);
if '/*' in raw_line:
return False
# Passed all filters, issue warning here.
error(filename, linenum, 'readability/function', 3,
'All parameters should be named in a function')
return True
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True | [
"def",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"raw_line",
",",
"cast_type",
",",
"pattern",
",",
"error",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"not",
"match",
":",
"return",
"False",
"... | https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/scripts/cpp_lint.py#L4251-L4342 | |
linkingvision/rapidvms | 20a80c2aa78bd005a8a1556b47c2c50ee530c730 | 3rdparty/protobuf/gmock/scripts/fuse_gmock_files.py | python | GetGTestRootDir | (gmock_root) | return os.path.join(gmock_root, 'gtest') | Returns the root directory of Google Test. | Returns the root directory of Google Test. | [
"Returns",
"the",
"root",
"directory",
"of",
"Google",
"Test",
"."
] | def GetGTestRootDir(gmock_root):
"""Returns the root directory of Google Test."""
return os.path.join(gmock_root, 'gtest') | [
"def",
"GetGTestRootDir",
"(",
"gmock_root",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"gmock_root",
",",
"'gtest'",
")"
] | https://github.com/linkingvision/rapidvms/blob/20a80c2aa78bd005a8a1556b47c2c50ee530c730/3rdparty/protobuf/gmock/scripts/fuse_gmock_files.py#L91-L94 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/compiler.py | python | CodeGenerator.signature | (self, node, frame, extra_kwargs=None) | Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments should be given
as python dict. | Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments should be given
as python dict. | [
"Writes",
"a",
"function",
"call",
"to",
"the",
"stream",
"for",
"the",
"current",
"node",
".",
"A",
"leading",
"comma",
"is",
"added",
"automatically",
".",
"The",
"extra",
"keyword",
"arguments",
"may",
"not",
"include",
"python",
"keywords",
"otherwise",
... | def signature(self, node, frame, extra_kwargs=None):
"""Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments should be given
as python dict.
"""
# if any of the given keyword arguments is a python keyword
# we have to make sure that no invalid call is created.
kwarg_workaround = False
for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
if is_python_keyword(kwarg):
kwarg_workaround = True
break
for arg in node.args:
self.write(', ')
self.visit(arg, frame)
if not kwarg_workaround:
for kwarg in node.kwargs:
self.write(', ')
self.visit(kwarg, frame)
if extra_kwargs is not None:
for key, value in iteritems(extra_kwargs):
self.write(', %s=%s' % (key, value))
if node.dyn_args:
self.write(', *')
self.visit(node.dyn_args, frame)
if kwarg_workaround:
if node.dyn_kwargs is not None:
self.write(', **dict({')
else:
self.write(', **{')
for kwarg in node.kwargs:
self.write('%r: ' % kwarg.key)
self.visit(kwarg.value, frame)
self.write(', ')
if extra_kwargs is not None:
for key, value in iteritems(extra_kwargs):
self.write('%r: %s, ' % (key, value))
if node.dyn_kwargs is not None:
self.write('}, **')
self.visit(node.dyn_kwargs, frame)
self.write(')')
else:
self.write('}')
elif node.dyn_kwargs is not None:
self.write(', **')
self.visit(node.dyn_kwargs, frame) | [
"def",
"signature",
"(",
"self",
",",
"node",
",",
"frame",
",",
"extra_kwargs",
"=",
"None",
")",
":",
"# if any of the given keyword arguments is a python keyword",
"# we have to make sure that no invalid call is created.",
"kwarg_workaround",
"=",
"False",
"for",
"kwarg",
... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/compiler.py#L409-L460 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/numbers.py | python | Integral.__rlshift__ | (self, other) | other << self | other << self | [
"other",
"<<",
"self"
] | def __rlshift__(self, other):
"""other << self"""
raise NotImplementedError | [
"def",
"__rlshift__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/numbers.py#L326-L328 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | Error.message | (self) | return ret | human-readable informative error message | human-readable informative error message | [
"human",
"-",
"readable",
"informative",
"error",
"message"
] | def message(self):
"""human-readable informative error message """
ret = libxml2mod.xmlErrorGetMessage(self._o)
return ret | [
"def",
"message",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlErrorGetMessage",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L5048-L5051 | |
ycm-core/ycmd | fc0fb7e5e15176cc5a2a30c80956335988c6b59a | ycmd/utils.py | python | SplitLines | ( contents ) | return contents.split( '\n' ) | Return a list of each of the lines in the unicode string |contents|. | Return a list of each of the lines in the unicode string |contents|. | [
"Return",
"a",
"list",
"of",
"each",
"of",
"the",
"lines",
"in",
"the",
"unicode",
"string",
"|contents|",
"."
] | def SplitLines( contents ):
"""Return a list of each of the lines in the unicode string |contents|."""
# We often want to get a list representation of a buffer such that we can
# index all of the 'lines' within it. Python provides str.splitlines for this
# purpose. However, this method not only splits on newline characters (\n,
# \r\n, and \r) but also on line boundaries like \v and \f. Since old
# Macintosh newlines (\r) are obsolete and Windows newlines (\r\n) end with a
# \n character, we can ignore carriage return characters (\r) and only split
# on \n.
return contents.split( '\n' ) | [
"def",
"SplitLines",
"(",
"contents",
")",
":",
"# We often want to get a list representation of a buffer such that we can",
"# index all of the 'lines' within it. Python provides str.splitlines for this",
"# purpose. However, this method not only splits on newline characters (\\n,",
"# \\r\\n, an... | https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/utils.py#L384-L394 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/ufunc_db.py | python | get_ufunc_info | (ufunc_key) | return _ufunc_db[ufunc_key] | get the lowering information for the ufunc with key ufunc_key.
The lowering information is a dictionary that maps from a numpy
loop string (as given by the ufunc types attribute) to a function
that handles code generation for a scalar version of the ufunc
(that is, generates the "per element" operation").
raises a KeyError if the ufunc is not in the ufunc_db | get the lowering information for the ufunc with key ufunc_key. | [
"get",
"the",
"lowering",
"information",
"for",
"the",
"ufunc",
"with",
"key",
"ufunc_key",
"."
] | def get_ufunc_info(ufunc_key):
"""get the lowering information for the ufunc with key ufunc_key.
The lowering information is a dictionary that maps from a numpy
loop string (as given by the ufunc types attribute) to a function
that handles code generation for a scalar version of the ufunc
(that is, generates the "per element" operation").
raises a KeyError if the ufunc is not in the ufunc_db
"""
_lazy_init_db()
return _ufunc_db[ufunc_key] | [
"def",
"get_ufunc_info",
"(",
"ufunc_key",
")",
":",
"_lazy_init_db",
"(",
")",
"return",
"_ufunc_db",
"[",
"ufunc_key",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/ufunc_db.py#L33-L44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.