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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Control.FindAccelIndex | (*args, **kwargs) | return _core_.Control_FindAccelIndex(*args, **kwargs) | FindAccelIndex(String label) -> int
Return the accel index in the string or -1 if none. | FindAccelIndex(String label) -> int | [
"FindAccelIndex",
"(",
"String",
"label",
")",
"-",
">",
"int"
] | def FindAccelIndex(*args, **kwargs):
"""
FindAccelIndex(String label) -> int
Return the accel index in the string or -1 if none.
"""
return _core_.Control_FindAccelIndex(*args, **kwargs) | [
"def",
"FindAccelIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Control_FindAccelIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12734-L12740 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/model_pruning/python/pruning.py | python | Pruning.add_pruning_summaries | (self) | Adds summaries of weight sparsities and thresholds. | Adds summaries of weight sparsities and thresholds. | [
"Adds",
"summaries",
"of",
"weight",
"sparsities",
"and",
"thresholds",
"."
] | def add_pruning_summaries(self):
"""Adds summaries of weight sparsities and thresholds."""
with ops.name_scope(self._spec.name + '_summaries'):
summary.scalar('sparsity', self._sparsity)
summary.scalar('last_mask_update_step', self._last_update_step)
masks = get_masks()
thresholds = get_thresholds()
for mask, threshold in zip(masks, thresholds):
summary.scalar(mask.op.name + '/sparsity', nn_impl.zero_fraction(mask))
summary.scalar(threshold.op.name + '/threshold', threshold) | [
"def",
"add_pruning_summaries",
"(",
"self",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"_spec",
".",
"name",
"+",
"'_summaries'",
")",
":",
"summary",
".",
"scalar",
"(",
"'sparsity'",
",",
"self",
".",
"_sparsity",
")",
"summary",
".",
"scalar",
"(",
"'last_mask_update_step'",
",",
"self",
".",
"_last_update_step",
")",
"masks",
"=",
"get_masks",
"(",
")",
"thresholds",
"=",
"get_thresholds",
"(",
")",
"for",
"mask",
",",
"threshold",
"in",
"zip",
"(",
"masks",
",",
"thresholds",
")",
":",
"summary",
".",
"scalar",
"(",
"mask",
".",
"op",
".",
"name",
"+",
"'/sparsity'",
",",
"nn_impl",
".",
"zero_fraction",
"(",
"mask",
")",
")",
"summary",
".",
"scalar",
"(",
"threshold",
".",
"op",
".",
"name",
"+",
"'/threshold'",
",",
"threshold",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/model_pruning/python/pruning.py#L610-L619 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/tokenutil.py | python | InsertSpaceTokenAfter | (token) | Inserts a space token after the given token.
Args:
token: The token to insert a space token after
Returns:
A single space token | Inserts a space token after the given token. | [
"Inserts",
"a",
"space",
"token",
"after",
"the",
"given",
"token",
"."
] | def InsertSpaceTokenAfter(token):
"""Inserts a space token after the given token.
Args:
token: The token to insert a space token after
Returns:
A single space token
"""
space_token = JavaScriptToken(' ', Type.WHITESPACE, token.line,
token.line_number)
InsertTokenAfter(space_token, token) | [
"def",
"InsertSpaceTokenAfter",
"(",
"token",
")",
":",
"space_token",
"=",
"JavaScriptToken",
"(",
"' '",
",",
"Type",
".",
"WHITESPACE",
",",
"token",
".",
"line",
",",
"token",
".",
"line_number",
")",
"InsertTokenAfter",
"(",
"space_token",
",",
"token",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/tokenutil.py#L293-L304 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/experimental/statistical_analysis/results_stats.py | python | CombinePValues | (p_values) | return p_value | Combines p-values from a number of tests using Fisher's Method.
The tests the p-values result from must test the same null hypothesis and be
independent.
Args:
p_values: List of p-values.
Returns:
combined_p_value: Combined p-value according to Fisher's method. | Combines p-values from a number of tests using Fisher's Method. | [
"Combines",
"p",
"-",
"values",
"from",
"a",
"number",
"of",
"tests",
"using",
"Fisher",
"s",
"Method",
"."
] | def CombinePValues(p_values):
"""Combines p-values from a number of tests using Fisher's Method.
The tests the p-values result from must test the same null hypothesis and be
independent.
Args:
p_values: List of p-values.
Returns:
combined_p_value: Combined p-value according to Fisher's method.
"""
# TODO (wierichs): Update to use scipy.stats.combine_pvalues(p_values) when
# Scipy v0.15.0 becomes available as standard version.
if not np:
raise ImportError('This function requires Numpy.')
if not stats:
raise ImportError('This function requires Scipy.')
test_statistic = -2 * np.sum(np.log(p_values))
p_value = stats.chi2.sf(test_statistic, 2 * len(p_values))
return p_value | [
"def",
"CombinePValues",
"(",
"p_values",
")",
":",
"# TODO (wierichs): Update to use scipy.stats.combine_pvalues(p_values) when",
"# Scipy v0.15.0 becomes available as standard version.",
"if",
"not",
"np",
":",
"raise",
"ImportError",
"(",
"'This function requires Numpy.'",
")",
"if",
"not",
"stats",
":",
"raise",
"ImportError",
"(",
"'This function requires Scipy.'",
")",
"test_statistic",
"=",
"-",
"2",
"*",
"np",
".",
"sum",
"(",
"np",
".",
"log",
"(",
"p_values",
")",
")",
"p_value",
"=",
"stats",
".",
"chi2",
".",
"sf",
"(",
"test_statistic",
",",
"2",
"*",
"len",
"(",
"p_values",
")",
")",
"return",
"p_value"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/experimental/statistical_analysis/results_stats.py#L157-L179 | |
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/wx/wxVTKRenderWindow.py | python | wxVTKRenderWindow.OnMiddleUp | (self, event) | Overridable event. | Overridable event. | [
"Overridable",
"event",
"."
] | def OnMiddleUp(self, event):
"""Overridable event.
"""
pass | [
"def",
"OnMiddleUp",
"(",
"self",
",",
"event",
")",
":",
"pass"
] | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/wx/wxVTKRenderWindow.py#L442-L445 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/wheel/macosx_libfile.py | python | calculate_macosx_platform_tag | (archive_root, platform_tag) | return platform_tag | Calculate proper macosx platform tag basing on files which are included to wheel
Example platform tag `macosx-10.14-x86_64` | Calculate proper macosx platform tag basing on files which are included to wheel | [
"Calculate",
"proper",
"macosx",
"platform",
"tag",
"basing",
"on",
"files",
"which",
"are",
"included",
"to",
"wheel"
] | def calculate_macosx_platform_tag(archive_root, platform_tag):
"""
Calculate proper macosx platform tag basing on files which are included to wheel
Example platform tag `macosx-10.14-x86_64`
"""
prefix, base_version, suffix = platform_tag.split('-')
base_version = tuple([int(x) for x in base_version.split(".")])
base_version = base_version[:2]
if base_version[0] > 10:
base_version = (base_version[0], 0)
assert len(base_version) == 2
if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
deploy_target = tuple([int(x) for x in os.environ[
"MACOSX_DEPLOYMENT_TARGET"].split(".")])
deploy_target = deploy_target[:2]
if deploy_target[0] > 10:
deploy_target = (deploy_target[0], 0)
if deploy_target < base_version:
sys.stderr.write(
"[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than the "
"version on which the Python interpreter was compiled ({}), and will be "
"ignored.\n".format('.'.join(str(x) for x in deploy_target),
'.'.join(str(x) for x in base_version))
)
else:
base_version = deploy_target
assert len(base_version) == 2
start_version = base_version
versions_dict = {}
for (dirpath, dirnames, filenames) in os.walk(archive_root):
for filename in filenames:
if filename.endswith('.dylib') or filename.endswith('.so'):
lib_path = os.path.join(dirpath, filename)
min_ver = extract_macosx_min_system_version(lib_path)
if min_ver is not None:
min_ver = min_ver[0:2]
if min_ver[0] > 10:
min_ver = (min_ver[0], 0)
versions_dict[lib_path] = min_ver
if len(versions_dict) > 0:
base_version = max(base_version, max(versions_dict.values()))
# macosx platform tag do not support minor bugfix release
fin_base_version = "_".join([str(x) for x in base_version])
if start_version < base_version:
problematic_files = [k for k, v in versions_dict.items() if v > start_version]
problematic_files = "\n".join(problematic_files)
if len(problematic_files) == 1:
files_form = "this file"
else:
files_form = "these files"
error_message = \
"[WARNING] This wheel needs a higher macOS version than {} " \
"To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least " +\
fin_base_version + " or recreate " + files_form + " with lower " \
"MACOSX_DEPLOYMENT_TARGET: \n" + problematic_files
if "MACOSX_DEPLOYMENT_TARGET" in os.environ:
error_message = error_message.format("is set in MACOSX_DEPLOYMENT_TARGET variable.")
else:
error_message = error_message.format(
"the version your Python interpreter is compiled against.")
sys.stderr.write(error_message)
platform_tag = prefix + "_" + fin_base_version + "_" + suffix
return platform_tag | [
"def",
"calculate_macosx_platform_tag",
"(",
"archive_root",
",",
"platform_tag",
")",
":",
"prefix",
",",
"base_version",
",",
"suffix",
"=",
"platform_tag",
".",
"split",
"(",
"'-'",
")",
"base_version",
"=",
"tuple",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"base_version",
".",
"split",
"(",
"\".\"",
")",
"]",
")",
"base_version",
"=",
"base_version",
"[",
":",
"2",
"]",
"if",
"base_version",
"[",
"0",
"]",
">",
"10",
":",
"base_version",
"=",
"(",
"base_version",
"[",
"0",
"]",
",",
"0",
")",
"assert",
"len",
"(",
"base_version",
")",
"==",
"2",
"if",
"\"MACOSX_DEPLOYMENT_TARGET\"",
"in",
"os",
".",
"environ",
":",
"deploy_target",
"=",
"tuple",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"os",
".",
"environ",
"[",
"\"MACOSX_DEPLOYMENT_TARGET\"",
"]",
".",
"split",
"(",
"\".\"",
")",
"]",
")",
"deploy_target",
"=",
"deploy_target",
"[",
":",
"2",
"]",
"if",
"deploy_target",
"[",
"0",
"]",
">",
"10",
":",
"deploy_target",
"=",
"(",
"deploy_target",
"[",
"0",
"]",
",",
"0",
")",
"if",
"deploy_target",
"<",
"base_version",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than the \"",
"\"version on which the Python interpreter was compiled ({}), and will be \"",
"\"ignored.\\n\"",
".",
"format",
"(",
"'.'",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"deploy_target",
")",
",",
"'.'",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"base_version",
")",
")",
")",
"else",
":",
"base_version",
"=",
"deploy_target",
"assert",
"len",
"(",
"base_version",
")",
"==",
"2",
"start_version",
"=",
"base_version",
"versions_dict",
"=",
"{",
"}",
"for",
"(",
"dirpath",
",",
"dirnames",
",",
"filenames",
")",
"in",
"os",
".",
"walk",
"(",
"archive_root",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.dylib'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'.so'",
")",
":",
"lib_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"filename",
")",
"min_ver",
"=",
"extract_macosx_min_system_version",
"(",
"lib_path",
")",
"if",
"min_ver",
"is",
"not",
"None",
":",
"min_ver",
"=",
"min_ver",
"[",
"0",
":",
"2",
"]",
"if",
"min_ver",
"[",
"0",
"]",
">",
"10",
":",
"min_ver",
"=",
"(",
"min_ver",
"[",
"0",
"]",
",",
"0",
")",
"versions_dict",
"[",
"lib_path",
"]",
"=",
"min_ver",
"if",
"len",
"(",
"versions_dict",
")",
">",
"0",
":",
"base_version",
"=",
"max",
"(",
"base_version",
",",
"max",
"(",
"versions_dict",
".",
"values",
"(",
")",
")",
")",
"# macosx platform tag do not support minor bugfix release",
"fin_base_version",
"=",
"\"_\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"base_version",
"]",
")",
"if",
"start_version",
"<",
"base_version",
":",
"problematic_files",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"versions_dict",
".",
"items",
"(",
")",
"if",
"v",
">",
"start_version",
"]",
"problematic_files",
"=",
"\"\\n\"",
".",
"join",
"(",
"problematic_files",
")",
"if",
"len",
"(",
"problematic_files",
")",
"==",
"1",
":",
"files_form",
"=",
"\"this file\"",
"else",
":",
"files_form",
"=",
"\"these files\"",
"error_message",
"=",
"\"[WARNING] This wheel needs a higher macOS version than {} \"",
"\"To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least \"",
"+",
"fin_base_version",
"+",
"\" or recreate \"",
"+",
"files_form",
"+",
"\" with lower \"",
"\"MACOSX_DEPLOYMENT_TARGET: \\n\"",
"+",
"problematic_files",
"if",
"\"MACOSX_DEPLOYMENT_TARGET\"",
"in",
"os",
".",
"environ",
":",
"error_message",
"=",
"error_message",
".",
"format",
"(",
"\"is set in MACOSX_DEPLOYMENT_TARGET variable.\"",
")",
"else",
":",
"error_message",
"=",
"error_message",
".",
"format",
"(",
"\"the version your Python interpreter is compiled against.\"",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"error_message",
")",
"platform_tag",
"=",
"prefix",
"+",
"\"_\"",
"+",
"fin_base_version",
"+",
"\"_\"",
"+",
"suffix",
"return",
"platform_tag"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/wheel/macosx_libfile.py#L359-L428 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/filters.py | python | do_urlize | (eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None) | return rv | Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If *target* is specified, the ``target`` attribute will be added to the
``<a>`` tag:
.. sourcecode:: jinja
{{ mytext|urlize(40, target='_blank') }}
.. versionchanged:: 2.8+
The *target* parameter was added. | Converts URLs in plain text into clickable links. | [
"Converts",
"URLs",
"in",
"plain",
"text",
"into",
"clickable",
"links",
"."
] | def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If *target* is specified, the ``target`` attribute will be added to the
``<a>`` tag:
.. sourcecode:: jinja
{{ mytext|urlize(40, target='_blank') }}
.. versionchanged:: 2.8+
The *target* parameter was added.
"""
policies = eval_ctx.environment.policies
rel = set((rel or '').split() or [])
if nofollow:
rel.add('nofollow')
rel.update((policies['urlize.rel'] or '').split())
if target is None:
target = policies['urlize.target']
rel = ' '.join(sorted(rel)) or None
rv = urlize(value, trim_url_limit, rel=rel, target=target)
if eval_ctx.autoescape:
rv = Markup(rv)
return rv | [
"def",
"do_urlize",
"(",
"eval_ctx",
",",
"value",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
",",
"target",
"=",
"None",
",",
"rel",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"rel",
"=",
"set",
"(",
"(",
"rel",
"or",
"''",
")",
".",
"split",
"(",
")",
"or",
"[",
"]",
")",
"if",
"nofollow",
":",
"rel",
".",
"add",
"(",
"'nofollow'",
")",
"rel",
".",
"update",
"(",
"(",
"policies",
"[",
"'urlize.rel'",
"]",
"or",
"''",
")",
".",
"split",
"(",
")",
")",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"policies",
"[",
"'urlize.target'",
"]",
"rel",
"=",
"' '",
".",
"join",
"(",
"sorted",
"(",
"rel",
")",
")",
"or",
"None",
"rv",
"=",
"urlize",
"(",
"value",
",",
"trim_url_limit",
",",
"rel",
"=",
"rel",
",",
"target",
"=",
"target",
")",
"if",
"eval_ctx",
".",
"autoescape",
":",
"rv",
"=",
"Markup",
"(",
"rv",
")",
"return",
"rv"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/filters.py#L499-L533 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _GetLibraries | (spec) | return unique_libraries_list | Returns the list of libraries for this configuration.
Arguments:
spec: The target dictionary containing the properties of the target.
Returns:
The list of directory paths. | Returns the list of libraries for this configuration. | [
"Returns",
"the",
"list",
"of",
"libraries",
"for",
"this",
"configuration",
"."
] | def _GetLibraries(spec):
"""Returns the list of libraries for this configuration.
Arguments:
spec: The target dictionary containing the properties of the target.
Returns:
The list of directory paths.
"""
libraries = spec.get("libraries", [])
# Strip out -l, as it is not used on windows (but is needed so we can pass
# in libraries that are assumed to be in the default library path).
# Also remove duplicate entries, leaving only the last duplicate, while
# preserving order.
found = OrderedSet()
unique_libraries_list = []
for entry in reversed(libraries):
library = re.sub(r"^\-l", "", entry)
if not os.path.splitext(library)[1]:
library += ".lib"
if library not in found:
found.add(library)
unique_libraries_list.append(library)
unique_libraries_list.reverse()
return unique_libraries_list | [
"def",
"_GetLibraries",
"(",
"spec",
")",
":",
"libraries",
"=",
"spec",
".",
"get",
"(",
"\"libraries\"",
",",
"[",
"]",
")",
"# Strip out -l, as it is not used on windows (but is needed so we can pass",
"# in libraries that are assumed to be in the default library path).",
"# Also remove duplicate entries, leaving only the last duplicate, while",
"# preserving order.",
"found",
"=",
"OrderedSet",
"(",
")",
"unique_libraries_list",
"=",
"[",
"]",
"for",
"entry",
"in",
"reversed",
"(",
"libraries",
")",
":",
"library",
"=",
"re",
".",
"sub",
"(",
"r\"^\\-l\"",
",",
"\"\"",
",",
"entry",
")",
"if",
"not",
"os",
".",
"path",
".",
"splitext",
"(",
"library",
")",
"[",
"1",
"]",
":",
"library",
"+=",
"\".lib\"",
"if",
"library",
"not",
"in",
"found",
":",
"found",
".",
"add",
"(",
"library",
")",
"unique_libraries_list",
".",
"append",
"(",
"library",
")",
"unique_libraries_list",
".",
"reverse",
"(",
")",
"return",
"unique_libraries_list"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L1290-L1313 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/greater_ds.py | python | _greater_ds_tbe | () | return | Greater TBE register | Greater TBE register | [
"Greater",
"TBE",
"register"
] | def _greater_ds_tbe():
"""Greater TBE register"""
return | [
"def",
"_greater_ds_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/greater_ds.py#L40-L42 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/six.py | python | ensure_text | (s, encoding='utf-8', errors='strict') | Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str` | Coerce *s* to six.text_type. | [
"Coerce",
"*",
"s",
"*",
"to",
"six",
".",
"text_type",
"."
] | def ensure_text(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encoding, errors)
elif isinstance(s, text_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s)) | [
"def",
"ensure_text",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
"else",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%s'\"",
"%",
"type",
"(",
"s",
")",
")"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/six.py#L892-L908 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/EasyDialogs.py | python | AskString | (prompt, default = "", id=261, ok=None, cancel=None) | Display a PROMPT string and a text entry field with a DEFAULT string.
Return the contents of the text entry field when the user clicks the
OK button or presses Return.
Return None when the user clicks the Cancel button.
If omitted, DEFAULT is empty.
The PROMPT and DEFAULT strings, as well as the return value,
can be at most 255 characters long. | Display a PROMPT string and a text entry field with a DEFAULT string. | [
"Display",
"a",
"PROMPT",
"string",
"and",
"a",
"text",
"entry",
"field",
"with",
"a",
"DEFAULT",
"string",
"."
] | def AskString(prompt, default = "", id=261, ok=None, cancel=None):
"""Display a PROMPT string and a text entry field with a DEFAULT string.
Return the contents of the text entry field when the user clicks the
OK button or presses Return.
Return None when the user clicks the Cancel button.
If omitted, DEFAULT is empty.
The PROMPT and DEFAULT strings, as well as the return value,
can be at most 255 characters long.
"""
_initialize()
_interact()
d = GetNewDialog(id, -1)
if not d:
print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
return
h = d.GetDialogItemAsControl(3)
SetDialogItemText(h, lf2cr(prompt))
h = d.GetDialogItemAsControl(4)
SetDialogItemText(h, lf2cr(default))
d.SelectDialogItemText(4, 0, 999)
# d.SetDialogItem(4, 0, 255)
if ok is not None:
h = d.GetDialogItemAsControl(1)
h.SetControlTitle(ok)
if cancel is not None:
h = d.GetDialogItemAsControl(2)
h.SetControlTitle(cancel)
d.SetDialogDefaultItem(1)
d.SetDialogCancelItem(2)
d.AutoSizeDialog()
d.GetDialogWindow().ShowWindow()
while 1:
n = ModalDialog(None)
if n == 1:
h = d.GetDialogItemAsControl(4)
return cr2lf(GetDialogItemText(h))
if n == 2: return None | [
"def",
"AskString",
"(",
"prompt",
",",
"default",
"=",
"\"\"",
",",
"id",
"=",
"261",
",",
"ok",
"=",
"None",
",",
"cancel",
"=",
"None",
")",
":",
"_initialize",
"(",
")",
"_interact",
"(",
")",
"d",
"=",
"GetNewDialog",
"(",
"id",
",",
"-",
"1",
")",
"if",
"not",
"d",
":",
"print",
"\"EasyDialogs: Can't get DLOG resource with id =\"",
",",
"id",
",",
"\" (missing resource file?)\"",
"return",
"h",
"=",
"d",
".",
"GetDialogItemAsControl",
"(",
"3",
")",
"SetDialogItemText",
"(",
"h",
",",
"lf2cr",
"(",
"prompt",
")",
")",
"h",
"=",
"d",
".",
"GetDialogItemAsControl",
"(",
"4",
")",
"SetDialogItemText",
"(",
"h",
",",
"lf2cr",
"(",
"default",
")",
")",
"d",
".",
"SelectDialogItemText",
"(",
"4",
",",
"0",
",",
"999",
")",
"# d.SetDialogItem(4, 0, 255)",
"if",
"ok",
"is",
"not",
"None",
":",
"h",
"=",
"d",
".",
"GetDialogItemAsControl",
"(",
"1",
")",
"h",
".",
"SetControlTitle",
"(",
"ok",
")",
"if",
"cancel",
"is",
"not",
"None",
":",
"h",
"=",
"d",
".",
"GetDialogItemAsControl",
"(",
"2",
")",
"h",
".",
"SetControlTitle",
"(",
"cancel",
")",
"d",
".",
"SetDialogDefaultItem",
"(",
"1",
")",
"d",
".",
"SetDialogCancelItem",
"(",
"2",
")",
"d",
".",
"AutoSizeDialog",
"(",
")",
"d",
".",
"GetDialogWindow",
"(",
")",
".",
"ShowWindow",
"(",
")",
"while",
"1",
":",
"n",
"=",
"ModalDialog",
"(",
"None",
")",
"if",
"n",
"==",
"1",
":",
"h",
"=",
"d",
".",
"GetDialogItemAsControl",
"(",
"4",
")",
"return",
"cr2lf",
"(",
"GetDialogItemText",
"(",
"h",
")",
")",
"if",
"n",
"==",
"2",
":",
"return",
"None"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/EasyDialogs.py#L97-L137 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/auto_bisect/bisect_perf_regression.py | python | BisectPerformanceMetrics._GetNearestV8BleedingEdgeFromTrunk | (
self, revision, v8_branch, bleeding_edge_branch, search_forward=True) | return bleeding_edge_revision | Gets the nearest V8 roll and maps to bleeding edge revision.
V8 is a bit tricky to bisect since it isn't just rolled out like blink.
Each revision on trunk might just be whatever was in bleeding edge, rolled
directly out. Or it could be some mixture of previous v8 trunk versions,
with bits and pieces cherry picked out from bleeding edge. In order to
bisect, we need both the before/after versions on trunk v8 to be just pushes
from bleeding edge. With the V8 git migration, the branches got switched.
a) master (external/v8) == candidates (v8/v8)
b) bleeding_edge (external/v8) == master (v8/v8)
Args:
revision: A V8 revision to get its nearest bleeding edge revision
search_forward: Searches forward if True, otherwise search backward.
Return:
A mapped bleeding edge revision if found, otherwise None. | Gets the nearest V8 roll and maps to bleeding edge revision. | [
"Gets",
"the",
"nearest",
"V8",
"roll",
"and",
"maps",
"to",
"bleeding",
"edge",
"revision",
"."
] | def _GetNearestV8BleedingEdgeFromTrunk(
self, revision, v8_branch, bleeding_edge_branch, search_forward=True):
"""Gets the nearest V8 roll and maps to bleeding edge revision.
V8 is a bit tricky to bisect since it isn't just rolled out like blink.
Each revision on trunk might just be whatever was in bleeding edge, rolled
directly out. Or it could be some mixture of previous v8 trunk versions,
with bits and pieces cherry picked out from bleeding edge. In order to
bisect, we need both the before/after versions on trunk v8 to be just pushes
from bleeding edge. With the V8 git migration, the branches got switched.
a) master (external/v8) == candidates (v8/v8)
b) bleeding_edge (external/v8) == master (v8/v8)
Args:
revision: A V8 revision to get its nearest bleeding edge revision
search_forward: Searches forward if True, otherwise search backward.
Return:
A mapped bleeding edge revision if found, otherwise None.
"""
cwd = self.depot_registry.GetDepotDir('v8')
cmd = ['log', '--format=%ct', '-1', revision]
output = bisect_utils.CheckRunGit(cmd, cwd=cwd)
commit_time = int(output)
commits = []
if search_forward:
cmd = ['log',
'--format=%H',
'--after=%d' % commit_time,
v8_branch,
'--reverse']
output = bisect_utils.CheckRunGit(cmd, cwd=cwd)
output = output.split()
commits = output
#Get 10 git hashes immediately after the given commit.
commits = commits[:10]
else:
cmd = ['log',
'--format=%H',
'-10',
'--before=%d' % commit_time,
v8_branch]
output = bisect_utils.CheckRunGit(cmd, cwd=cwd)
output = output.split()
commits = output
bleeding_edge_revision = None
for c in commits:
bleeding_edge_revision = self._GetV8BleedingEdgeFromV8TrunkIfMappable(
c, bleeding_edge_branch)
if bleeding_edge_revision:
break
return bleeding_edge_revision | [
"def",
"_GetNearestV8BleedingEdgeFromTrunk",
"(",
"self",
",",
"revision",
",",
"v8_branch",
",",
"bleeding_edge_branch",
",",
"search_forward",
"=",
"True",
")",
":",
"cwd",
"=",
"self",
".",
"depot_registry",
".",
"GetDepotDir",
"(",
"'v8'",
")",
"cmd",
"=",
"[",
"'log'",
",",
"'--format=%ct'",
",",
"'-1'",
",",
"revision",
"]",
"output",
"=",
"bisect_utils",
".",
"CheckRunGit",
"(",
"cmd",
",",
"cwd",
"=",
"cwd",
")",
"commit_time",
"=",
"int",
"(",
"output",
")",
"commits",
"=",
"[",
"]",
"if",
"search_forward",
":",
"cmd",
"=",
"[",
"'log'",
",",
"'--format=%H'",
",",
"'--after=%d'",
"%",
"commit_time",
",",
"v8_branch",
",",
"'--reverse'",
"]",
"output",
"=",
"bisect_utils",
".",
"CheckRunGit",
"(",
"cmd",
",",
"cwd",
"=",
"cwd",
")",
"output",
"=",
"output",
".",
"split",
"(",
")",
"commits",
"=",
"output",
"#Get 10 git hashes immediately after the given commit.",
"commits",
"=",
"commits",
"[",
":",
"10",
"]",
"else",
":",
"cmd",
"=",
"[",
"'log'",
",",
"'--format=%H'",
",",
"'-10'",
",",
"'--before=%d'",
"%",
"commit_time",
",",
"v8_branch",
"]",
"output",
"=",
"bisect_utils",
".",
"CheckRunGit",
"(",
"cmd",
",",
"cwd",
"=",
"cwd",
")",
"output",
"=",
"output",
".",
"split",
"(",
")",
"commits",
"=",
"output",
"bleeding_edge_revision",
"=",
"None",
"for",
"c",
"in",
"commits",
":",
"bleeding_edge_revision",
"=",
"self",
".",
"_GetV8BleedingEdgeFromV8TrunkIfMappable",
"(",
"c",
",",
"bleeding_edge_branch",
")",
"if",
"bleeding_edge_revision",
":",
"break",
"return",
"bleeding_edge_revision"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/bisect_perf_regression.py#L1690-L1744 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/tools/build/src/tools/common.py | python | file_creation_command | () | Return a command which can create a file. If 'r' is result of invocation, then
'r foobar' will create foobar with unspecified content. What happens if file
already exists is unspecified. | Return a command which can create a file. If 'r' is result of invocation, then
'r foobar' will create foobar with unspecified content. What happens if file
already exists is unspecified. | [
"Return",
"a",
"command",
"which",
"can",
"create",
"a",
"file",
".",
"If",
"r",
"is",
"result",
"of",
"invocation",
"then",
"r",
"foobar",
"will",
"create",
"foobar",
"with",
"unspecified",
"content",
".",
"What",
"happens",
"if",
"file",
"already",
"exists",
"is",
"unspecified",
"."
] | def file_creation_command():
"""
Return a command which can create a file. If 'r' is result of invocation, then
'r foobar' will create foobar with unspecified content. What happens if file
already exists is unspecified.
"""
if os_name() == 'NT':
return "echo. > "
else:
return "touch " | [
"def",
"file_creation_command",
"(",
")",
":",
"if",
"os_name",
"(",
")",
"==",
"'NT'",
":",
"return",
"\"echo. > \"",
"else",
":",
"return",
"\"touch \""
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/tools/common.py#L555-L564 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py | python | easy_install.pseudo_tempname | (self) | return os.path.join(self.install_dir, "test-easy-install-%s" % pid) | Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo. | Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo. | [
"Return",
"a",
"pseudo",
"-",
"tempname",
"base",
"in",
"the",
"install",
"directory",
".",
"This",
"code",
"is",
"intentionally",
"naive",
";",
"if",
"a",
"malicious",
"party",
"can",
"write",
"to",
"the",
"target",
"directory",
"you",
"re",
"already",
"in",
"deep",
"doodoo",
"."
] | def pseudo_tempname(self):
"""Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
"""
try:
pid = os.getpid()
except Exception:
pid = random.randint(0, sys.maxsize)
return os.path.join(self.install_dir, "test-easy-install-%s" % pid) | [
"def",
"pseudo_tempname",
"(",
"self",
")",
":",
"try",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"except",
"Exception",
":",
"pid",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"sys",
".",
"maxsize",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"install_dir",
",",
"\"test-easy-install-%s\"",
"%",
"pid",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py#L442-L451 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/message.py | python | _WireReader._get_question | (self, qcount) | Read the next I{qcount} records from the wire data and add them to
the question section.
@param qcount: the number of questions in the message
@type qcount: int | Read the next I{qcount} records from the wire data and add them to
the question section. | [
"Read",
"the",
"next",
"I",
"{",
"qcount",
"}",
"records",
"from",
"the",
"wire",
"data",
"and",
"add",
"them",
"to",
"the",
"question",
"section",
"."
] | def _get_question(self, qcount):
"""Read the next I{qcount} records from the wire data and add them to
the question section.
@param qcount: the number of questions in the message
@type qcount: int"""
if self.updating and qcount > 1:
raise dns.exception.FormError
for i in xrange(0, qcount):
(qname, used) = dns.name.from_wire(self.wire, self.current)
if not self.message.origin is None:
qname = qname.relativize(self.message.origin)
self.current = self.current + used
(rdtype, rdclass) = \
struct.unpack('!HH',
self.wire[self.current:self.current + 4])
self.current = self.current + 4
self.message.find_rrset(self.message.question, qname,
rdclass, rdtype, create=True,
force_unique=True)
if self.updating:
self.zone_rdclass = rdclass | [
"def",
"_get_question",
"(",
"self",
",",
"qcount",
")",
":",
"if",
"self",
".",
"updating",
"and",
"qcount",
">",
"1",
":",
"raise",
"dns",
".",
"exception",
".",
"FormError",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"qcount",
")",
":",
"(",
"qname",
",",
"used",
")",
"=",
"dns",
".",
"name",
".",
"from_wire",
"(",
"self",
".",
"wire",
",",
"self",
".",
"current",
")",
"if",
"not",
"self",
".",
"message",
".",
"origin",
"is",
"None",
":",
"qname",
"=",
"qname",
".",
"relativize",
"(",
"self",
".",
"message",
".",
"origin",
")",
"self",
".",
"current",
"=",
"self",
".",
"current",
"+",
"used",
"(",
"rdtype",
",",
"rdclass",
")",
"=",
"struct",
".",
"unpack",
"(",
"'!HH'",
",",
"self",
".",
"wire",
"[",
"self",
".",
"current",
":",
"self",
".",
"current",
"+",
"4",
"]",
")",
"self",
".",
"current",
"=",
"self",
".",
"current",
"+",
"4",
"self",
".",
"message",
".",
"find_rrset",
"(",
"self",
".",
"message",
".",
"question",
",",
"qname",
",",
"rdclass",
",",
"rdtype",
",",
"create",
"=",
"True",
",",
"force_unique",
"=",
"True",
")",
"if",
"self",
".",
"updating",
":",
"self",
".",
"zone_rdclass",
"=",
"rdclass"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/message.py#L584-L606 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py | python | SinglePtIntegrationTable.set_reference_scan_numbers | (self, row_index, ref_numbers) | set reference scan numbers or warning as 'No match'
:param row_index:
:param ref_numbers:
:return: | set reference scan numbers or warning as 'No match'
:param row_index:
:param ref_numbers:
:return: | [
"set",
"reference",
"scan",
"numbers",
"or",
"warning",
"as",
"No",
"match",
":",
"param",
"row_index",
":",
":",
"param",
"ref_numbers",
":",
":",
"return",
":"
] | def set_reference_scan_numbers(self, row_index, ref_numbers):
""" set reference scan numbers or warning as 'No match'
:param row_index:
:param ref_numbers:
:return:
"""
# process the reference number
if isinstance(ref_numbers, str):
scans_str = ref_numbers
elif isinstance(ref_numbers, list):
scans_str = ''
for index, ref_number in enumerate(ref_numbers):
if index > 0:
scans_str += ','
scans_str += '{0}'.format(ref_number)
else:
raise AssertionError('Reference scan numbers {0} of type {1} is not supported.'
''.format(ref_numbers, type(ref_numbers)))
# add to table
self.update_cell_value(row_index, self._ref_scans_index, scans_str) | [
"def",
"set_reference_scan_numbers",
"(",
"self",
",",
"row_index",
",",
"ref_numbers",
")",
":",
"# process the reference number",
"if",
"isinstance",
"(",
"ref_numbers",
",",
"str",
")",
":",
"scans_str",
"=",
"ref_numbers",
"elif",
"isinstance",
"(",
"ref_numbers",
",",
"list",
")",
":",
"scans_str",
"=",
"''",
"for",
"index",
",",
"ref_number",
"in",
"enumerate",
"(",
"ref_numbers",
")",
":",
"if",
"index",
">",
"0",
":",
"scans_str",
"+=",
"','",
"scans_str",
"+=",
"'{0}'",
".",
"format",
"(",
"ref_number",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"'Reference scan numbers {0} of type {1} is not supported.'",
"''",
".",
"format",
"(",
"ref_numbers",
",",
"type",
"(",
"ref_numbers",
")",
")",
")",
"# add to table",
"self",
".",
"update_cell_value",
"(",
"row_index",
",",
"self",
".",
"_ref_scans_index",
",",
"scans_str",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L1567-L1588 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/pydoc.py | python | apropos | (key) | Print all the one-line module summaries that contain a substring. | Print all the one-line module summaries that contain a substring. | [
"Print",
"all",
"the",
"one",
"-",
"line",
"module",
"summaries",
"that",
"contain",
"a",
"substring",
"."
] | def apropos(key):
"""Print all the one-line module summaries that contain a substring."""
def callback(path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
print modname, desc and '- ' + desc
def onerror(modname):
pass
with warnings.catch_warnings():
warnings.filterwarnings('ignore') # ignore problems during import
ModuleScanner().run(callback, key, onerror=onerror) | [
"def",
"apropos",
"(",
"key",
")",
":",
"def",
"callback",
"(",
"path",
",",
"modname",
",",
"desc",
")",
":",
"if",
"modname",
"[",
"-",
"9",
":",
"]",
"==",
"'.__init__'",
":",
"modname",
"=",
"modname",
"[",
":",
"-",
"9",
"]",
"+",
"' (package)'",
"print",
"modname",
",",
"desc",
"and",
"'- '",
"+",
"desc",
"def",
"onerror",
"(",
"modname",
")",
":",
"pass",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
")",
"# ignore problems during import",
"ModuleScanner",
"(",
")",
".",
"run",
"(",
"callback",
",",
"key",
",",
"onerror",
"=",
"onerror",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L2038-L2048 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/client/timeline.py | python | Timeline._assign_lanes | (self) | Assigns non-overlapping lanes for the activities on each device. | Assigns non-overlapping lanes for the activities on each device. | [
"Assigns",
"non",
"-",
"overlapping",
"lanes",
"for",
"the",
"activities",
"on",
"each",
"device",
"."
] | def _assign_lanes(self):
"""Assigns non-overlapping lanes for the activities on each device."""
for device_stats in self._step_stats.dev_stats:
# TODO(pbar): Genuine thread IDs in NodeExecStats might be helpful.
lanes = [0]
for ns in device_stats.node_stats:
l = -1
for (i, lts) in enumerate(lanes):
if ns.all_start_micros > lts:
l = i
lanes[l] = ns.all_start_micros + ns.all_end_rel_micros
break
if l < 0:
l = len(lanes)
lanes.append(ns.all_start_micros + ns.all_end_rel_micros)
ns.thread_id = l | [
"def",
"_assign_lanes",
"(",
"self",
")",
":",
"for",
"device_stats",
"in",
"self",
".",
"_step_stats",
".",
"dev_stats",
":",
"# TODO(pbar): Genuine thread IDs in NodeExecStats might be helpful.",
"lanes",
"=",
"[",
"0",
"]",
"for",
"ns",
"in",
"device_stats",
".",
"node_stats",
":",
"l",
"=",
"-",
"1",
"for",
"(",
"i",
",",
"lts",
")",
"in",
"enumerate",
"(",
"lanes",
")",
":",
"if",
"ns",
".",
"all_start_micros",
">",
"lts",
":",
"l",
"=",
"i",
"lanes",
"[",
"l",
"]",
"=",
"ns",
".",
"all_start_micros",
"+",
"ns",
".",
"all_end_rel_micros",
"break",
"if",
"l",
"<",
"0",
":",
"l",
"=",
"len",
"(",
"lanes",
")",
"lanes",
".",
"append",
"(",
"ns",
".",
"all_start_micros",
"+",
"ns",
".",
"all_end_rel_micros",
")",
"ns",
".",
"thread_id",
"=",
"l"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/timeline.py#L397-L412 | ||
tiny-dnn/tiny-dnn | c0f576f5cb7b35893f62127cb7aec18f77a3bcc5 | third_party/cpplint.py | python | FlagCxx11Features | (filename, clean_lines, linenum, error) | Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Flag those c++11 features that we only allow in certain places. | [
"Flag",
"those",
"c",
"++",
"11",
"features",
"that",
"we",
"only",
"allow",
"in",
"certain",
"places",
"."
] | def FlagCxx11Features(filename, clean_lines, linenum, error):
"""Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++ TR1 headers.
if include and include.group(1).startswith('tr1/'):
error(filename, linenum, 'build/c++tr1', 5,
('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
# Flag unapproved C++11 headers.
if include and include.group(1) in ('cfenv',
'condition_variable',
'fenv.h',
'future',
'mutex',
'thread',
'chrono',
'ratio',
'regex',
'system_error',
):
error(filename, linenum, 'build/c++11', 5,
('<%s> is an unapproved C++11 header.') % include.group(1))
# The only place where we need to worry about C++11 keywords and library
# features in preprocessor directives is in macro definitions.
if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
# These are classes and free functions. The classes are always
# mentioned as std::*, but we only catch the free functions if
# they're not found by ADL. They're alphabetical by header.
for top_name in (
# type_traits
'alignment_of',
'aligned_union',
):
if Search(r'\bstd::%s\b' % top_name, line):
error(filename, linenum, 'build/c++11', 5,
('std::%s is an unapproved C++11 class or function. Send c-style '
'an example of where it would make your code more readable, and '
'they may let you use it.') % top_name) | [
"def",
"FlagCxx11Features",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"include",
"=",
"Match",
"(",
"r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]'",
",",
"line",
")",
"# Flag unapproved C++ TR1 headers.",
"if",
"include",
"and",
"include",
".",
"group",
"(",
"1",
")",
".",
"startswith",
"(",
"'tr1/'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/c++tr1'",
",",
"5",
",",
"(",
"'C++ TR1 headers such as <%s> are unapproved.'",
")",
"%",
"include",
".",
"group",
"(",
"1",
")",
")",
"# Flag unapproved C++11 headers.",
"if",
"include",
"and",
"include",
".",
"group",
"(",
"1",
")",
"in",
"(",
"'cfenv'",
",",
"'condition_variable'",
",",
"'fenv.h'",
",",
"'future'",
",",
"'mutex'",
",",
"'thread'",
",",
"'chrono'",
",",
"'ratio'",
",",
"'regex'",
",",
"'system_error'",
",",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/c++11'",
",",
"5",
",",
"(",
"'<%s> is an unapproved C++11 header.'",
")",
"%",
"include",
".",
"group",
"(",
"1",
")",
")",
"# The only place where we need to worry about C++11 keywords and library",
"# features in preprocessor directives is in macro definitions.",
"if",
"Match",
"(",
"r'\\s*#'",
",",
"line",
")",
"and",
"not",
"Match",
"(",
"r'\\s*#\\s*define\\b'",
",",
"line",
")",
":",
"return",
"# These are classes and free functions. The classes are always",
"# mentioned as std::*, but we only catch the free functions if",
"# they're not found by ADL. They're alphabetical by header.",
"for",
"top_name",
"in",
"(",
"# type_traits",
"'alignment_of'",
",",
"'aligned_union'",
",",
")",
":",
"if",
"Search",
"(",
"r'\\bstd::%s\\b'",
"%",
"top_name",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/c++11'",
",",
"5",
",",
"(",
"'std::%s is an unapproved C++11 class or function. Send c-style '",
"'an example of where it would make your code more readable, and '",
"'they may let you use it.'",
")",
"%",
"top_name",
")"
] | https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L5983-L6032 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/base.py | python | Index._add_logical_methods_disabled | (cls) | Add in logical methods to disable. | Add in logical methods to disable. | [
"Add",
"in",
"logical",
"methods",
"to",
"disable",
"."
] | def _add_logical_methods_disabled(cls):
"""
Add in logical methods to disable.
"""
cls.all = make_invalid_op("all")
cls.any = make_invalid_op("any") | [
"def",
"_add_logical_methods_disabled",
"(",
"cls",
")",
":",
"cls",
".",
"all",
"=",
"make_invalid_op",
"(",
"\"all\"",
")",
"cls",
".",
"any",
"=",
"make_invalid_op",
"(",
"\"any\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/base.py#L5229-L5234 | ||
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | scripts/cpp_lint.py | python | GetLineWidth | (line) | Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters. | Determines the width of the line in column positions. | [
"Determines",
"the",
"width",
"of",
"the",
"line",
"in",
"column",
"positions",
"."
] | def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line) | [
"def",
"GetLineWidth",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"width",
"=",
"0",
"for",
"uc",
"in",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"line",
")",
":",
"if",
"unicodedata",
".",
"east_asian_width",
"(",
"uc",
")",
"in",
"(",
"'W'",
",",
"'F'",
")",
":",
"width",
"+=",
"2",
"elif",
"not",
"unicodedata",
".",
"combining",
"(",
"uc",
")",
":",
"width",
"+=",
"1",
"return",
"width",
"else",
":",
"return",
"len",
"(",
"line",
")"
] | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/scripts/cpp_lint.py#L3437-L3456 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | tools/caffe_converter/convert_symbol.py | python | convert_symbol | (prototxt_fname) | return ret, input_dim | Convert caffe model definition into Symbol
Parameters
----------
prototxt_fname : str
Filename of the prototxt file
Returns
-------
Symbol
Converted Symbol
tuple
Input shape | Convert caffe model definition into Symbol | [
"Convert",
"caffe",
"model",
"definition",
"into",
"Symbol"
] | def convert_symbol(prototxt_fname):
"""Convert caffe model definition into Symbol
Parameters
----------
prototxt_fname : str
Filename of the prototxt file
Returns
-------
Symbol
Converted Symbol
tuple
Input shape
"""
sym, output_name, input_dim = _parse_proto(prototxt_fname)
exec(sym) # pylint: disable=exec-used
_locals = locals()
ret = []
for i in output_name:
exec("ret = " + i, globals(), _locals) # pylint: disable=exec-used
ret.append(_locals['ret'])
ret = mx.sym.Group(ret)
return ret, input_dim | [
"def",
"convert_symbol",
"(",
"prototxt_fname",
")",
":",
"sym",
",",
"output_name",
",",
"input_dim",
"=",
"_parse_proto",
"(",
"prototxt_fname",
")",
"exec",
"(",
"sym",
")",
"# pylint: disable=exec-used",
"_locals",
"=",
"locals",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"output_name",
":",
"exec",
"(",
"\"ret = \"",
"+",
"i",
",",
"globals",
"(",
")",
",",
"_locals",
")",
"# pylint: disable=exec-used",
"ret",
".",
"append",
"(",
"_locals",
"[",
"'ret'",
"]",
")",
"ret",
"=",
"mx",
".",
"sym",
".",
"Group",
"(",
"ret",
")",
"return",
"ret",
",",
"input_dim"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/tools/caffe_converter/convert_symbol.py#L295-L318 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/data_flow_ops.py | python | BaseStagingArea._scope_vals | (self, vals) | Return a list of values to pass to `name_scope()`.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary.
Returns:
The values in vals as a list. | Return a list of values to pass to `name_scope()`. | [
"Return",
"a",
"list",
"of",
"values",
"to",
"pass",
"to",
"name_scope",
"()",
"."
] | def _scope_vals(self, vals):
"""Return a list of values to pass to `name_scope()`.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary.
Returns:
The values in vals as a list.
"""
if isinstance(vals, (list, tuple)):
return vals
elif isinstance(vals, dict):
return vals.values()
else:
return [vals] | [
"def",
"_scope_vals",
"(",
"self",
",",
"vals",
")",
":",
"if",
"isinstance",
"(",
"vals",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"vals",
"elif",
"isinstance",
"(",
"vals",
",",
"dict",
")",
":",
"return",
"vals",
".",
"values",
"(",
")",
"else",
":",
"return",
"[",
"vals",
"]"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_ops.py#L1559-L1573 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/vision/transforms/functional.py | python | hflip | (img) | Horizontally flips the given Image or np.array.
Args:
img (PIL.Image|np.array): Image to be flipped.
Returns:
PIL.Image or np.array: Horizontall flipped image.
Examples:
.. code-block:: python
import numpy as np
from PIL import Image
from paddle.vision.transforms import functional as F
fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')
fake_img = Image.fromarray(fake_img)
flpped_img = F.hflip(fake_img)
print(flpped_img.size) | Horizontally flips the given Image or np.array. | [
"Horizontally",
"flips",
"the",
"given",
"Image",
"or",
"np",
".",
"array",
"."
] | def hflip(img):
"""Horizontally flips the given Image or np.array.
Args:
img (PIL.Image|np.array): Image to be flipped.
Returns:
PIL.Image or np.array: Horizontall flipped image.
Examples:
.. code-block:: python
import numpy as np
from PIL import Image
from paddle.vision.transforms import functional as F
fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8')
fake_img = Image.fromarray(fake_img)
flpped_img = F.hflip(fake_img)
print(flpped_img.size)
"""
if not (_is_pil_image(img) or _is_numpy_image(img) or
_is_tensor_image(img)):
raise TypeError(
'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'.
format(type(img)))
if _is_pil_image(img):
return F_pil.hflip(img)
elif _is_tensor_image(img):
return F_t.hflip(img)
else:
return F_cv2.hflip(img) | [
"def",
"hflip",
"(",
"img",
")",
":",
"if",
"not",
"(",
"_is_pil_image",
"(",
"img",
")",
"or",
"_is_numpy_image",
"(",
"img",
")",
"or",
"_is_tensor_image",
"(",
"img",
")",
")",
":",
"raise",
"TypeError",
"(",
"'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}'",
".",
"format",
"(",
"type",
"(",
"img",
")",
")",
")",
"if",
"_is_pil_image",
"(",
"img",
")",
":",
"return",
"F_pil",
".",
"hflip",
"(",
"img",
")",
"elif",
"_is_tensor_image",
"(",
"img",
")",
":",
"return",
"F_t",
".",
"hflip",
"(",
"img",
")",
"else",
":",
"return",
"F_cv2",
".",
"hflip",
"(",
"img",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/vision/transforms/functional.py#L291-L326 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/position.py | python | Position.current_comm | (self) | return self._current_comm | Gets the current_comm of this Position. # noqa: E501
:return: The current_comm of this Position. # noqa: E501
:rtype: float | Gets the current_comm of this Position. # noqa: E501 | [
"Gets",
"the",
"current_comm",
"of",
"this",
"Position",
".",
"#",
"noqa",
":",
"E501"
] | def current_comm(self):
"""Gets the current_comm of this Position. # noqa: E501
:return: The current_comm of this Position. # noqa: E501
:rtype: float
"""
return self._current_comm | [
"def",
"current_comm",
"(",
"self",
")",
":",
"return",
"self",
".",
"_current_comm"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L1260-L1267 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/changelog.py | python | bullet_list_class_from_docutils | (bullet_list, bullet_type=None) | return content | Processes elements of bullet list into an encapsulating class
:param bullet_list: ``docutils.nodes.bullet_list`` list to be processed
:param bullet_type: ``str`` either 'bullet' or 'enumerated'
:returns: ``BulletList`` object representing a docutils bullet_list | Processes elements of bullet list into an encapsulating class | [
"Processes",
"elements",
"of",
"bullet",
"list",
"into",
"an",
"encapsulating",
"class"
] | def bullet_list_class_from_docutils(bullet_list, bullet_type=None):
'''
Processes elements of bullet list into an encapsulating class
:param bullet_list: ``docutils.nodes.bullet_list`` list to be processed
:param bullet_type: ``str`` either 'bullet' or 'enumerated'
:returns: ``BulletList`` object representing a docutils bullet_list
'''
content = BulletList(bullet_type=bullet_type)
for child in bullet_list.children:
if isinstance(child, docutils.nodes.list_item):
content.bullets.append(mixed_text_from_docutils(child))
else:
log.debug("Skipped bullet_list child: '{0}'".format(child))
return content | [
"def",
"bullet_list_class_from_docutils",
"(",
"bullet_list",
",",
"bullet_type",
"=",
"None",
")",
":",
"content",
"=",
"BulletList",
"(",
"bullet_type",
"=",
"bullet_type",
")",
"for",
"child",
"in",
"bullet_list",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"list_item",
")",
":",
"content",
".",
"bullets",
".",
"append",
"(",
"mixed_text_from_docutils",
"(",
"child",
")",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"Skipped bullet_list child: '{0}'\"",
".",
"format",
"(",
"child",
")",
")",
"return",
"content"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/changelog.py#L126-L140 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/metric_spec.py | python | _adapt_metric_fn | (
metric_fn, metric_fn_name, is_labels_required, is_weights_required) | return _positional_no_labels_metric_fn | Adapt `metric_fn` to take only named args.
This returns a function that takes only named args `labels`, `predictions`,
and `weights`, and invokes `metric_fn` according to the following rules:
- If `metric_fn` args include exactly one of `_LABELS_ARGS`, that arg is
passed (usually by name, but positionally if both it and `predictions` need
to be passed positionally). Otherwise, `labels` are omitted.
- If `metric_fn` args include exactly one of `_PREDICTIONS_ARGS`, that arg is
passed by name. Otherwise, `predictions` are passed positionally as the
first non-label argument.
- If exactly one of `_WEIGHTS_ARGS` is provided, that arg is passed by
name.
Args:
metric_fn: Metric function to be wrapped.
metric_fn_name: `metric_fn` name, only used for logging.
is_labels_required: Whether `labels` is a required arg.
is_weights_required: Whether `weights` is a required arg.
Returns:
Function accepting only named args `labels, `predictions`, and `weights`,
and passing those to `metric_fn`.
Raises:
ValueError: if one of the following is true:
- `metric_fn` has more than one arg of `_LABELS_ARGS`, `_PREDICTIONS_ARGS`,
or `_WEIGHTS_ARGS`
- `is_labels_required` is true, and `metric_fn` has no arg from
`_LABELS_ARGS`.
- `is_weights_required` is true, and `metric_fn` has no arg from
`_WEIGHTS_ARGS`. | Adapt `metric_fn` to take only named args. | [
"Adapt",
"metric_fn",
"to",
"take",
"only",
"named",
"args",
"."
] | def _adapt_metric_fn(
metric_fn, metric_fn_name, is_labels_required, is_weights_required):
"""Adapt `metric_fn` to take only named args.
This returns a function that takes only named args `labels`, `predictions`,
and `weights`, and invokes `metric_fn` according to the following rules:
- If `metric_fn` args include exactly one of `_LABELS_ARGS`, that arg is
passed (usually by name, but positionally if both it and `predictions` need
to be passed positionally). Otherwise, `labels` are omitted.
- If `metric_fn` args include exactly one of `_PREDICTIONS_ARGS`, that arg is
passed by name. Otherwise, `predictions` are passed positionally as the
first non-label argument.
- If exactly one of `_WEIGHTS_ARGS` is provided, that arg is passed by
name.
Args:
metric_fn: Metric function to be wrapped.
metric_fn_name: `metric_fn` name, only used for logging.
is_labels_required: Whether `labels` is a required arg.
is_weights_required: Whether `weights` is a required arg.
Returns:
Function accepting only named args `labels, `predictions`, and `weights`,
and passing those to `metric_fn`.
Raises:
ValueError: if one of the following is true:
- `metric_fn` has more than one arg of `_LABELS_ARGS`, `_PREDICTIONS_ARGS`,
or `_WEIGHTS_ARGS`
- `is_labels_required` is true, and `metric_fn` has no arg from
`_LABELS_ARGS`.
- `is_weights_required` is true, and `metric_fn` has no arg from
`_WEIGHTS_ARGS`.
"""
args = _args(metric_fn)
labels_arg = _matching_arg(
metric_fn_name, args, _LABELS_ARGS, _CANONICAL_LABELS_ARG,
is_labels_required)
predictions_arg = _matching_arg(
metric_fn_name, args, _PREDICTIONS_ARGS, _CANONICAL_PREDICTIONS_ARG)
weights_arg = _matching_arg(
metric_fn_name, args, _WEIGHTS_ARGS, _CANONICAL_WEIGHTS_ARG,
is_weights_required)
# pylint: disable=invalid-name
if labels_arg:
if predictions_arg:
# Both labels and predictions are named args.
def _named_metric_fn(
_sentinel=None, labels=None, predictions=None, weights=None):
_assert_named_args(_sentinel)
kwargs = {
labels_arg: labels,
predictions_arg: predictions,
}
if weights is not None:
kwargs[weights_arg] = weights
return metric_fn(**kwargs)
return _named_metric_fn
if labels_arg == args[0]:
# labels is a named arg, and first. predictions is not a named arg, so we
# want to pass it as the 2nd positional arg (i.e., the first non-labels
# position), which means passing both positionally.
def _positional_metric_fn(
_sentinel=None, labels=None, predictions=None, weights=None):
_assert_named_args(_sentinel)
# TODO(ptucker): Should we support metrics that take only labels?
# Currently, if you want streaming mean of a label, you have to wrap it
# in a fn that takes discards predictions.
if weights is None:
return metric_fn(labels, predictions)
return metric_fn(labels, predictions, **{weights_arg: weights})
return _positional_metric_fn
# labels is a named arg, and not first, so we pass predictions positionally
# and labels by name.
def _positional_predictions_metric_fn(
_sentinel=None, labels=None, predictions=None, weights=None):
_assert_named_args(_sentinel)
kwargs = {
labels_arg: labels,
}
if weights is not None:
kwargs[weights_arg] = weights
return metric_fn(predictions, **kwargs)
return _positional_predictions_metric_fn
if predictions_arg:
# No labels, and predictions is named, so we pass the latter as a named arg.
def _named_no_labels_metric_fn(
_sentinel=None, labels=None, predictions=None, weights=None):
del labels
_assert_named_args(_sentinel)
kwargs = {
predictions_arg: predictions,
}
# TODO(ptucker): Should we allow weights with no labels?
if weights is not None:
kwargs[weights_arg] = weights
return metric_fn(**kwargs)
return _named_no_labels_metric_fn
# Neither labels nor predictions are named, so we just pass predictions as the
# first arg.
def _positional_no_labels_metric_fn(
_sentinel=None, labels=None, predictions=None, weights=None):
del labels
_assert_named_args(_sentinel)
if weights is None:
return metric_fn(predictions)
# TODO(ptucker): Should we allow weights with no labels?
return metric_fn(predictions, **{weights_arg: weights})
return _positional_no_labels_metric_fn | [
"def",
"_adapt_metric_fn",
"(",
"metric_fn",
",",
"metric_fn_name",
",",
"is_labels_required",
",",
"is_weights_required",
")",
":",
"args",
"=",
"_args",
"(",
"metric_fn",
")",
"labels_arg",
"=",
"_matching_arg",
"(",
"metric_fn_name",
",",
"args",
",",
"_LABELS_ARGS",
",",
"_CANONICAL_LABELS_ARG",
",",
"is_labels_required",
")",
"predictions_arg",
"=",
"_matching_arg",
"(",
"metric_fn_name",
",",
"args",
",",
"_PREDICTIONS_ARGS",
",",
"_CANONICAL_PREDICTIONS_ARG",
")",
"weights_arg",
"=",
"_matching_arg",
"(",
"metric_fn_name",
",",
"args",
",",
"_WEIGHTS_ARGS",
",",
"_CANONICAL_WEIGHTS_ARG",
",",
"is_weights_required",
")",
"# pylint: disable=invalid-name",
"if",
"labels_arg",
":",
"if",
"predictions_arg",
":",
"# Both labels and predictions are named args.",
"def",
"_named_metric_fn",
"(",
"_sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"predictions",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"_assert_named_args",
"(",
"_sentinel",
")",
"kwargs",
"=",
"{",
"labels_arg",
":",
"labels",
",",
"predictions_arg",
":",
"predictions",
",",
"}",
"if",
"weights",
"is",
"not",
"None",
":",
"kwargs",
"[",
"weights_arg",
"]",
"=",
"weights",
"return",
"metric_fn",
"(",
"*",
"*",
"kwargs",
")",
"return",
"_named_metric_fn",
"if",
"labels_arg",
"==",
"args",
"[",
"0",
"]",
":",
"# labels is a named arg, and first. predictions is not a named arg, so we",
"# want to pass it as the 2nd positional arg (i.e., the first non-labels",
"# position), which means passing both positionally.",
"def",
"_positional_metric_fn",
"(",
"_sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"predictions",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"_assert_named_args",
"(",
"_sentinel",
")",
"# TODO(ptucker): Should we support metrics that take only labels?",
"# Currently, if you want streaming mean of a label, you have to wrap it",
"# in a fn that takes discards predictions.",
"if",
"weights",
"is",
"None",
":",
"return",
"metric_fn",
"(",
"labels",
",",
"predictions",
")",
"return",
"metric_fn",
"(",
"labels",
",",
"predictions",
",",
"*",
"*",
"{",
"weights_arg",
":",
"weights",
"}",
")",
"return",
"_positional_metric_fn",
"# labels is a named arg, and not first, so we pass predictions positionally",
"# and labels by name.",
"def",
"_positional_predictions_metric_fn",
"(",
"_sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"predictions",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"_assert_named_args",
"(",
"_sentinel",
")",
"kwargs",
"=",
"{",
"labels_arg",
":",
"labels",
",",
"}",
"if",
"weights",
"is",
"not",
"None",
":",
"kwargs",
"[",
"weights_arg",
"]",
"=",
"weights",
"return",
"metric_fn",
"(",
"predictions",
",",
"*",
"*",
"kwargs",
")",
"return",
"_positional_predictions_metric_fn",
"if",
"predictions_arg",
":",
"# No labels, and predictions is named, so we pass the latter as a named arg.",
"def",
"_named_no_labels_metric_fn",
"(",
"_sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"predictions",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"del",
"labels",
"_assert_named_args",
"(",
"_sentinel",
")",
"kwargs",
"=",
"{",
"predictions_arg",
":",
"predictions",
",",
"}",
"# TODO(ptucker): Should we allow weights with no labels?",
"if",
"weights",
"is",
"not",
"None",
":",
"kwargs",
"[",
"weights_arg",
"]",
"=",
"weights",
"return",
"metric_fn",
"(",
"*",
"*",
"kwargs",
")",
"return",
"_named_no_labels_metric_fn",
"# Neither labels nor predictions are named, so we just pass predictions as the",
"# first arg.",
"def",
"_positional_no_labels_metric_fn",
"(",
"_sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"predictions",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"del",
"labels",
"_assert_named_args",
"(",
"_sentinel",
")",
"if",
"weights",
"is",
"None",
":",
"return",
"metric_fn",
"(",
"predictions",
")",
"# TODO(ptucker): Should we allow weights with no labels?",
"return",
"metric_fn",
"(",
"predictions",
",",
"*",
"*",
"{",
"weights_arg",
":",
"weights",
"}",
")",
"return",
"_positional_no_labels_metric_fn"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/metric_spec.py#L112-L226 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | SashEvent.SetEdge | (*args, **kwargs) | return _windows_.SashEvent_SetEdge(*args, **kwargs) | SetEdge(self, int edge) | SetEdge(self, int edge) | [
"SetEdge",
"(",
"self",
"int",
"edge",
")"
] | def SetEdge(*args, **kwargs):
"""SetEdge(self, int edge)"""
return _windows_.SashEvent_SetEdge(*args, **kwargs) | [
"def",
"SetEdge",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"SashEvent_SetEdge",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1902-L1904 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Plugins/pvblot/blotish.py | python | color | (ncol=None) | Set the maximum number of standard color scale colors to use on a color
plot to ncol. | Set the maximum number of standard color scale colors to use on a color
plot to ncol. | [
"Set",
"the",
"maximum",
"number",
"of",
"standard",
"color",
"scale",
"colors",
"to",
"use",
"on",
"a",
"color",
"plot",
"to",
"ncol",
"."
] | def color(ncol=None):
"""
Set the maximum number of standard color scale colors to use on a color
plot to ncol.
"""
maxColors = len(_standard_colors)
if not ncol:
print "Set to", state.numBlockColors, "of", maxColors, "colors."
return
ncol = int(ncol)
if ncol > maxColors:
print "Setting to maximum of", maxColors, "instead of", ncol
ncol = maxColors
state.numBlockColors = ncol
state.rebuildBlockLookupTable()
_finish_plot_change() | [
"def",
"color",
"(",
"ncol",
"=",
"None",
")",
":",
"maxColors",
"=",
"len",
"(",
"_standard_colors",
")",
"if",
"not",
"ncol",
":",
"print",
"\"Set to\"",
",",
"state",
".",
"numBlockColors",
",",
"\"of\"",
",",
"maxColors",
",",
"\"colors.\"",
"return",
"ncol",
"=",
"int",
"(",
"ncol",
")",
"if",
"ncol",
">",
"maxColors",
":",
"print",
"\"Setting to maximum of\"",
",",
"maxColors",
",",
"\"instead of\"",
",",
"ncol",
"ncol",
"=",
"maxColors",
"state",
".",
"numBlockColors",
"=",
"ncol",
"state",
".",
"rebuildBlockLookupTable",
"(",
")",
"_finish_plot_change",
"(",
")"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Plugins/pvblot/blotish.py#L583-L600 | ||
microsoft/Azure-Kinect-Sensor-SDK | d87ef578676c05b9a5d23c097502942753bf3777 | src/python/k4a/src/k4a/_bindings/image.py | python | Image.create | (
image_format:EImageFormat,
width_pixels:int,
height_pixels:int,
stride_bytes:int) | return image | ! Create an image.
@param image_format (EImageFormat): The format of the image that will
be stored in this image container.
@param width_pixels (int): Width in pixels.
@param height_pixels (int): Height in pixels.
@param stride_bytes (int): The number of bytes per horizontal line of
the image. If set to 0, the stride will be set to the minimum size
given the image format and width_pixels.
@returns Image: An Image instance with an allocated data buffer. If an
error occurs, then None is returned.
@remarks
- This function is used to create images of formats that have
consistent stride. The function is not suitable for compressed
formats that may not be represented by the same number of bytes per
line.
@remarks
- For most image formats, the function will allocate an image buffer of
size @p height_pixels * @p stride_bytes. Buffers with image format
of EImageFormat.COLOR_NV12 will allocate an additional
@p height_pixels / 2 set of lines (each of @p stride_bytes). This
function cannot be used to allocate EImageFormat.COLOR_MJPG buffer.
@remarks
- To create an image object without the API allocating memory, or to
represent an image that has a non-deterministic stride, use
create_from_ndarray().
@remarks
- If an error occurs, then None is returned. | ! Create an image. | [
"!",
"Create",
"an",
"image",
"."
] | def create(
image_format:EImageFormat,
width_pixels:int,
height_pixels:int,
stride_bytes:int):
'''! Create an image.
@param image_format (EImageFormat): The format of the image that will
be stored in this image container.
@param width_pixels (int): Width in pixels.
@param height_pixels (int): Height in pixels.
@param stride_bytes (int): The number of bytes per horizontal line of
the image. If set to 0, the stride will be set to the minimum size
given the image format and width_pixels.
@returns Image: An Image instance with an allocated data buffer. If an
error occurs, then None is returned.
@remarks
- This function is used to create images of formats that have
consistent stride. The function is not suitable for compressed
formats that may not be represented by the same number of bytes per
line.
@remarks
- For most image formats, the function will allocate an image buffer of
size @p height_pixels * @p stride_bytes. Buffers with image format
of EImageFormat.COLOR_NV12 will allocate an additional
@p height_pixels / 2 set of lines (each of @p stride_bytes). This
function cannot be used to allocate EImageFormat.COLOR_MJPG buffer.
@remarks
- To create an image object without the API allocating memory, or to
represent an image that has a non-deterministic stride, use
create_from_ndarray().
@remarks
- If an error occurs, then None is returned.
'''
image = None
assert(isinstance(image_format, EImageFormat)), "image_format parameter must be an EImageFormat."
assert(width_pixels > 0), "width_pixels must be greater than zero."
assert(height_pixels > 0), "height_pixels must be greater than zero."
assert(stride_bytes > 0), "stride_bytes must be greater than zero."
assert(stride_bytes > width_pixels), "stride_bytes must be greater than width_pixels."
assert(stride_bytes > height_pixels), "stride_bytes must be greater than height_pixels."
# Create an image.
image_handle = _ImageHandle()
status = k4a_image_create(
_ctypes.c_int(image_format),
_ctypes.c_int(width_pixels),
_ctypes.c_int(height_pixels),
_ctypes.c_int(stride_bytes),
_ctypes.byref(image_handle))
if status == EStatus.SUCCEEDED:
image = Image._create_from_existing_image_handle(image_handle)
return image | [
"def",
"create",
"(",
"image_format",
":",
"EImageFormat",
",",
"width_pixels",
":",
"int",
",",
"height_pixels",
":",
"int",
",",
"stride_bytes",
":",
"int",
")",
":",
"image",
"=",
"None",
"assert",
"(",
"isinstance",
"(",
"image_format",
",",
"EImageFormat",
")",
")",
",",
"\"image_format parameter must be an EImageFormat.\"",
"assert",
"(",
"width_pixels",
">",
"0",
")",
",",
"\"width_pixels must be greater than zero.\"",
"assert",
"(",
"height_pixels",
">",
"0",
")",
",",
"\"height_pixels must be greater than zero.\"",
"assert",
"(",
"stride_bytes",
">",
"0",
")",
",",
"\"stride_bytes must be greater than zero.\"",
"assert",
"(",
"stride_bytes",
">",
"width_pixels",
")",
",",
"\"stride_bytes must be greater than width_pixels.\"",
"assert",
"(",
"stride_bytes",
">",
"height_pixels",
")",
",",
"\"stride_bytes must be greater than height_pixels.\"",
"# Create an image.",
"image_handle",
"=",
"_ImageHandle",
"(",
")",
"status",
"=",
"k4a_image_create",
"(",
"_ctypes",
".",
"c_int",
"(",
"image_format",
")",
",",
"_ctypes",
".",
"c_int",
"(",
"width_pixels",
")",
",",
"_ctypes",
".",
"c_int",
"(",
"height_pixels",
")",
",",
"_ctypes",
".",
"c_int",
"(",
"stride_bytes",
")",
",",
"_ctypes",
".",
"byref",
"(",
"image_handle",
")",
")",
"if",
"status",
"==",
"EStatus",
".",
"SUCCEEDED",
":",
"image",
"=",
"Image",
".",
"_create_from_existing_image_handle",
"(",
"image_handle",
")",
"return",
"image"
] | https://github.com/microsoft/Azure-Kinect-Sensor-SDK/blob/d87ef578676c05b9a5d23c097502942753bf3777/src/python/k4a/src/k4a/_bindings/image.py#L284-L348 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/MACCSkeys.py | python | _InitKeys | (keyList, keyDict) | *Internal Use Only*
generates SMARTS patterns for the keys, run once | *Internal Use Only* | [
"*",
"Internal",
"Use",
"Only",
"*"
] | def _InitKeys(keyList, keyDict):
""" *Internal Use Only*
generates SMARTS patterns for the keys, run once
"""
assert len(keyList) == len(keyDict.keys()), 'length mismatch'
for key in keyDict.keys():
patt, count = keyDict[key]
if patt != '?':
sma = Chem.MolFromSmarts(patt)
if not sma:
print('SMARTS parser error for key #%d: %s' % (key, patt))
else:
keyList[key - 1] = sma, count | [
"def",
"_InitKeys",
"(",
"keyList",
",",
"keyDict",
")",
":",
"assert",
"len",
"(",
"keyList",
")",
"==",
"len",
"(",
"keyDict",
".",
"keys",
"(",
")",
")",
",",
"'length mismatch'",
"for",
"key",
"in",
"keyDict",
".",
"keys",
"(",
")",
":",
"patt",
",",
"count",
"=",
"keyDict",
"[",
"key",
"]",
"if",
"patt",
"!=",
"'?'",
":",
"sma",
"=",
"Chem",
".",
"MolFromSmarts",
"(",
"patt",
")",
"if",
"not",
"sma",
":",
"print",
"(",
"'SMARTS parser error for key #%d: %s'",
"%",
"(",
"key",
",",
"patt",
")",
")",
"else",
":",
"keyList",
"[",
"key",
"-",
"1",
"]",
"=",
"sma",
",",
"count"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/MACCSkeys.py#L220-L234 | ||
TimoSaemann/caffe-segnet-cudnn5 | abcf30dca449245e101bf4ced519f716177f0885 | scripts/cpp_lint.py | python | ProcessLine | (filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]) | Processes a single line in the file.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
clean_lines: An array of strings, each representing a line of the file,
with comments stripped.
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Processes a single line in the file. | [
"Processes",
"a",
"single",
"line",
"in",
"the",
"file",
"."
] | def ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]):
"""Processes a single line in the file.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
clean_lines: An array of strings, each representing a line of the file,
with comments stripped.
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[line], line, error)
nesting_state.Update(filename, clean_lines, line, error)
if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM:
return
CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
CheckLanguage(filename, clean_lines, line, file_extension, include_state,
nesting_state, error)
CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
CheckForNonStandardConstructs(filename, clean_lines, line,
nesting_state, error)
CheckVlogArguments(filename, clean_lines, line, error)
CheckCaffeAlternatives(filename, clean_lines, line, error)
CheckCaffeDataLayerSetUp(filename, clean_lines, line, error)
CheckCaffeRandom(filename, clean_lines, line, error)
CheckPosixThreading(filename, clean_lines, line, error)
CheckInvalidIncrement(filename, clean_lines, line, error)
CheckMakePairUsesDeduction(filename, clean_lines, line, error)
for check_fn in extra_check_functions:
check_fn(filename, clean_lines, line, error) | [
"def",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"raw_lines",
"=",
"clean_lines",
".",
"raw_lines",
"ParseNolintSuppressions",
"(",
"filename",
",",
"raw_lines",
"[",
"line",
"]",
",",
"line",
",",
"error",
")",
"nesting_state",
".",
"Update",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"if",
"nesting_state",
".",
"stack",
"and",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"inline_asm",
"!=",
"_NO_ASM",
":",
"return",
"CheckForFunctionLengths",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"function_state",
",",
"error",
")",
"CheckForMultilineCommentsAndStrings",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckStyle",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"file_extension",
",",
"nesting_state",
",",
"error",
")",
"CheckLanguage",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"file_extension",
",",
"include_state",
",",
"nesting_state",
",",
"error",
")",
"CheckForNonConstReference",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"nesting_state",
",",
"error",
")",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"nesting_state",
",",
"error",
")",
"CheckVlogArguments",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckCaffeAlternatives",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckCaffeDataLayerSetUp",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckCaffeRandom",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckPosixThreading",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckInvalidIncrement",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckMakePairUsesDeduction",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"for",
"check_fn",
"in",
"extra_check_functions",
":",
"check_fn",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")"
] | https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L4600-L4642 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/image/detection.py | python | ImageDetIter.augmentation_transform | (self, data, label) | return (data, label) | Override Transforms input data with specified augmentations. | Override Transforms input data with specified augmentations. | [
"Override",
"Transforms",
"input",
"data",
"with",
"specified",
"augmentations",
"."
] | def augmentation_transform(self, data, label): # pylint: disable=arguments-differ
"""Override Transforms input data with specified augmentations."""
for aug in self.auglist:
data, label = aug(data, label)
return (data, label) | [
"def",
"augmentation_transform",
"(",
"self",
",",
"data",
",",
"label",
")",
":",
"# pylint: disable=arguments-differ",
"for",
"aug",
"in",
"self",
".",
"auglist",
":",
"data",
",",
"label",
"=",
"aug",
"(",
"data",
",",
"label",
")",
"return",
"(",
"data",
",",
"label",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/image/detection.py#L786-L790 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/rexec.py | python | RExec.r_reload | (self, m) | return self.importer.reload(m) | Reload the module object, re-parsing and re-initializing it.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment. | Reload the module object, re-parsing and re-initializing it. | [
"Reload",
"the",
"module",
"object",
"re",
"-",
"parsing",
"and",
"re",
"-",
"initializing",
"it",
"."
] | def r_reload(self, m):
"""Reload the module object, re-parsing and re-initializing it.
This method is implicitly called by code executing in the
restricted environment. Overriding this method in a subclass is
used to change the policies enforced by a restricted environment.
"""
return self.importer.reload(m) | [
"def",
"r_reload",
"(",
"self",
",",
"m",
")",
":",
"return",
"self",
".",
"importer",
".",
"reload",
"(",
"m",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/rexec.py#L349-L357 | |
coinapi/coinapi-sdk | 854f21e7f69ea8599ae35c5403565cf299d8b795 | oeml-sdk/python/openapi_client/model/order_cancel_all_request.py | python | OrderCancelAllRequest.openapi_types | () | return {
'exchange_id': (str,), # noqa: E501
} | This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. | This must be a method because a model may have properties that are
of type self, this must run after the class is loaded | [
"This",
"must",
"be",
"a",
"method",
"because",
"a",
"model",
"may",
"have",
"properties",
"that",
"are",
"of",
"type",
"self",
"this",
"must",
"run",
"after",
"the",
"class",
"is",
"loaded"
] | def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
return {
'exchange_id': (str,), # noqa: E501
} | [
"def",
"openapi_types",
"(",
")",
":",
"return",
"{",
"'exchange_id'",
":",
"(",
"str",
",",
")",
",",
"# noqa: E501",
"}"
] | https://github.com/coinapi/coinapi-sdk/blob/854f21e7f69ea8599ae35c5403565cf299d8b795/oeml-sdk/python/openapi_client/model/order_cancel_all_request.py#L75-L86 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/overrides.py | python | array_function_from_dispatcher | (
implementation, module=None, verify=True, docs_from_dispatcher=True) | return decorator | Like array_function_dispatcher, but with function arguments flipped. | Like array_function_dispatcher, but with function arguments flipped. | [
"Like",
"array_function_dispatcher",
"but",
"with",
"function",
"arguments",
"flipped",
"."
] | def array_function_from_dispatcher(
implementation, module=None, verify=True, docs_from_dispatcher=True):
"""Like array_function_dispatcher, but with function arguments flipped."""
def decorator(dispatcher):
return array_function_dispatch(
dispatcher, module, verify=verify,
docs_from_dispatcher=docs_from_dispatcher)(implementation)
return decorator | [
"def",
"array_function_from_dispatcher",
"(",
"implementation",
",",
"module",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"docs_from_dispatcher",
"=",
"True",
")",
":",
"def",
"decorator",
"(",
"dispatcher",
")",
":",
"return",
"array_function_dispatch",
"(",
"dispatcher",
",",
"module",
",",
"verify",
"=",
"verify",
",",
"docs_from_dispatcher",
"=",
"docs_from_dispatcher",
")",
"(",
"implementation",
")",
"return",
"decorator"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/overrides.py#L202-L210 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/SIP/sipspectrum.py | python | SIPSpectrum.showAll | (self, save=False, ax=None) | return fig, ax | Plot spectrum, Cole-Cole fit and Debye distribution | Plot spectrum, Cole-Cole fit and Debye distribution | [
"Plot",
"spectrum",
"Cole",
"-",
"Cole",
"fit",
"and",
"Debye",
"distribution"
] | def showAll(self, save=False, ax=None):
"""Plot spectrum, Cole-Cole fit and Debye distribution"""
# generate title strings
if np.any(self.mCC):
mCC = self.mCC
if mCC[0] > 1:
tstr = r'CC: $\rho$={:.1f} m={:.3f} $\tau$={:.1e}s c={:.2f}'
else:
tstr = r'CC: m={:.3f} $\tau$={:.1e}s c={:.2f}'
if len(mCC) == 6: # double Cole-Cole
tstr = tstr.replace('CC', 'CC1') + ' ' + \
tstr.replace('CC', 'CC2')
elif len(mCC) > 3: # second (EM) tau
tstr += r' $\tau_2$={:.1e}s'
tCC = tstr.format(*mCC)
if ax is None:
fig, ax = plt.subplots(nrows=2+(self.mDD is not None),
figsize=(12, 12))
else:
fig = ax[0].figure
self.fig['all'] = fig
fig.subplots_adjust(hspace=0.25)
# amplitude
drawAmplitudeSpectrum(ax[0], self.f, self.amp, label='data', ylog=0)
if np.any(self.ampDD):
ax[0].plot(self.f, self.ampDD, 'm-', label='DD response')
if np.any(self.ampCC):
ax[0].semilogx(self.f, self.ampCC, 'r-', label='CC model')
ax[0].legend(loc='best')
# phase
if np.any(self.ampOrg):
ax[0].semilogx(self.f, self.ampOrg, 'c+-', label='org. data')
ax[0].legend(loc='best')
if np.any(self.phiOrg):
ax[1].semilogx(self.f, self.phiOrg * 1e3, 'c+-', label='org. data')
ax[1].semilogx(self.f, self.phi * 1e3, 'b+-', label='data')
if np.any(self.phiCC):
ax[1].semilogx(self.f, self.phiCC * 1e3, 'r-', label='CC model')
if np.any(self.phiDD):
ax[1].semilogx(self.f, self.phiDD * 1e3, 'm-', label='DD model')
ax[1].grid(True)
ax[1].legend(loc='best')
ax[1].set_xlabel('f (Hz)')
ax[1].set_ylabel('-phi (mrad)')
if np.any(self.mCC):
ax[1].set_title(tCC, loc='left')
if np.any(self.mDD):
mtot = self.totalChargeability()
lmtau = self.logMeanTau()
tDD = r'DD: m={:.3f} $\tau$={:.1e}s'.format(mtot, lmtau)
ax[2].semilogx(self.tau, self.mDD * 1e3)
ax[2].set_xlim(ax[2].get_xlim()[::-1])
ax[2].grid(True)
ax[2].set_xlabel(r'$\tau$ (ms)')
ax[2].set_ylabel('m (mV/V)')
ax[2].set_title(tDD, loc='left')
if save:
if isinstance(save, str):
savename = save
else:
savename = self.basename + '.pdf'
fig.savefig(savename, bbox_inches='tight')
plt.show(block=False)
return fig, ax | [
"def",
"showAll",
"(",
"self",
",",
"save",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"# generate title strings",
"if",
"np",
".",
"any",
"(",
"self",
".",
"mCC",
")",
":",
"mCC",
"=",
"self",
".",
"mCC",
"if",
"mCC",
"[",
"0",
"]",
">",
"1",
":",
"tstr",
"=",
"r'CC: $\\rho$={:.1f} m={:.3f} $\\tau$={:.1e}s c={:.2f}'",
"else",
":",
"tstr",
"=",
"r'CC: m={:.3f} $\\tau$={:.1e}s c={:.2f}'",
"if",
"len",
"(",
"mCC",
")",
"==",
"6",
":",
"# double Cole-Cole",
"tstr",
"=",
"tstr",
".",
"replace",
"(",
"'CC'",
",",
"'CC1'",
")",
"+",
"' '",
"+",
"tstr",
".",
"replace",
"(",
"'CC'",
",",
"'CC2'",
")",
"elif",
"len",
"(",
"mCC",
")",
">",
"3",
":",
"# second (EM) tau",
"tstr",
"+=",
"r' $\\tau_2$={:.1e}s'",
"tCC",
"=",
"tstr",
".",
"format",
"(",
"*",
"mCC",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"2",
"+",
"(",
"self",
".",
"mDD",
"is",
"not",
"None",
")",
",",
"figsize",
"=",
"(",
"12",
",",
"12",
")",
")",
"else",
":",
"fig",
"=",
"ax",
"[",
"0",
"]",
".",
"figure",
"self",
".",
"fig",
"[",
"'all'",
"]",
"=",
"fig",
"fig",
".",
"subplots_adjust",
"(",
"hspace",
"=",
"0.25",
")",
"# amplitude",
"drawAmplitudeSpectrum",
"(",
"ax",
"[",
"0",
"]",
",",
"self",
".",
"f",
",",
"self",
".",
"amp",
",",
"label",
"=",
"'data'",
",",
"ylog",
"=",
"0",
")",
"if",
"np",
".",
"any",
"(",
"self",
".",
"ampDD",
")",
":",
"ax",
"[",
"0",
"]",
".",
"plot",
"(",
"self",
".",
"f",
",",
"self",
".",
"ampDD",
",",
"'m-'",
",",
"label",
"=",
"'DD response'",
")",
"if",
"np",
".",
"any",
"(",
"self",
".",
"ampCC",
")",
":",
"ax",
"[",
"0",
"]",
".",
"semilogx",
"(",
"self",
".",
"f",
",",
"self",
".",
"ampCC",
",",
"'r-'",
",",
"label",
"=",
"'CC model'",
")",
"ax",
"[",
"0",
"]",
".",
"legend",
"(",
"loc",
"=",
"'best'",
")",
"# phase",
"if",
"np",
".",
"any",
"(",
"self",
".",
"ampOrg",
")",
":",
"ax",
"[",
"0",
"]",
".",
"semilogx",
"(",
"self",
".",
"f",
",",
"self",
".",
"ampOrg",
",",
"'c+-'",
",",
"label",
"=",
"'org. data'",
")",
"ax",
"[",
"0",
"]",
".",
"legend",
"(",
"loc",
"=",
"'best'",
")",
"if",
"np",
".",
"any",
"(",
"self",
".",
"phiOrg",
")",
":",
"ax",
"[",
"1",
"]",
".",
"semilogx",
"(",
"self",
".",
"f",
",",
"self",
".",
"phiOrg",
"*",
"1e3",
",",
"'c+-'",
",",
"label",
"=",
"'org. data'",
")",
"ax",
"[",
"1",
"]",
".",
"semilogx",
"(",
"self",
".",
"f",
",",
"self",
".",
"phi",
"*",
"1e3",
",",
"'b+-'",
",",
"label",
"=",
"'data'",
")",
"if",
"np",
".",
"any",
"(",
"self",
".",
"phiCC",
")",
":",
"ax",
"[",
"1",
"]",
".",
"semilogx",
"(",
"self",
".",
"f",
",",
"self",
".",
"phiCC",
"*",
"1e3",
",",
"'r-'",
",",
"label",
"=",
"'CC model'",
")",
"if",
"np",
".",
"any",
"(",
"self",
".",
"phiDD",
")",
":",
"ax",
"[",
"1",
"]",
".",
"semilogx",
"(",
"self",
".",
"f",
",",
"self",
".",
"phiDD",
"*",
"1e3",
",",
"'m-'",
",",
"label",
"=",
"'DD model'",
")",
"ax",
"[",
"1",
"]",
".",
"grid",
"(",
"True",
")",
"ax",
"[",
"1",
"]",
".",
"legend",
"(",
"loc",
"=",
"'best'",
")",
"ax",
"[",
"1",
"]",
".",
"set_xlabel",
"(",
"'f (Hz)'",
")",
"ax",
"[",
"1",
"]",
".",
"set_ylabel",
"(",
"'-phi (mrad)'",
")",
"if",
"np",
".",
"any",
"(",
"self",
".",
"mCC",
")",
":",
"ax",
"[",
"1",
"]",
".",
"set_title",
"(",
"tCC",
",",
"loc",
"=",
"'left'",
")",
"if",
"np",
".",
"any",
"(",
"self",
".",
"mDD",
")",
":",
"mtot",
"=",
"self",
".",
"totalChargeability",
"(",
")",
"lmtau",
"=",
"self",
".",
"logMeanTau",
"(",
")",
"tDD",
"=",
"r'DD: m={:.3f} $\\tau$={:.1e}s'",
".",
"format",
"(",
"mtot",
",",
"lmtau",
")",
"ax",
"[",
"2",
"]",
".",
"semilogx",
"(",
"self",
".",
"tau",
",",
"self",
".",
"mDD",
"*",
"1e3",
")",
"ax",
"[",
"2",
"]",
".",
"set_xlim",
"(",
"ax",
"[",
"2",
"]",
".",
"get_xlim",
"(",
")",
"[",
":",
":",
"-",
"1",
"]",
")",
"ax",
"[",
"2",
"]",
".",
"grid",
"(",
"True",
")",
"ax",
"[",
"2",
"]",
".",
"set_xlabel",
"(",
"r'$\\tau$ (ms)'",
")",
"ax",
"[",
"2",
"]",
".",
"set_ylabel",
"(",
"'m (mV/V)'",
")",
"ax",
"[",
"2",
"]",
".",
"set_title",
"(",
"tDD",
",",
"loc",
"=",
"'left'",
")",
"if",
"save",
":",
"if",
"isinstance",
"(",
"save",
",",
"str",
")",
":",
"savename",
"=",
"save",
"else",
":",
"savename",
"=",
"self",
".",
"basename",
"+",
"'.pdf'",
"fig",
".",
"savefig",
"(",
"savename",
",",
"bbox_inches",
"=",
"'tight'",
")",
"plt",
".",
"show",
"(",
"block",
"=",
"False",
")",
"return",
"fig",
",",
"ax"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/SIP/sipspectrum.py#L788-L856 | |
ros-planning/moveit2 | dd240ef6fd8b9932a7a53964140f2952786187a9 | moveit_commander/src/moveit_commander/move_group.py | python | MoveGroupCommander.set_position_target | (self, xyz, end_effector_link="") | Specify a target position for the end-effector. Any orientation of the end-effector is acceptable. | Specify a target position for the end-effector. Any orientation of the end-effector is acceptable. | [
"Specify",
"a",
"target",
"position",
"for",
"the",
"end",
"-",
"effector",
".",
"Any",
"orientation",
"of",
"the",
"end",
"-",
"effector",
"is",
"acceptable",
"."
] | def set_position_target(self, xyz, end_effector_link=""):
""" Specify a target position for the end-effector. Any orientation of the end-effector is acceptable."""
if len(end_effector_link) > 0 or self.has_end_effector_link():
if not self._g.set_position_target(
xyz[0], xyz[1], xyz[2], end_effector_link
):
raise MoveItCommanderException("Unable to set position target")
else:
raise MoveItCommanderException(
"There is no end effector to set the pose for"
) | [
"def",
"set_position_target",
"(",
"self",
",",
"xyz",
",",
"end_effector_link",
"=",
"\"\"",
")",
":",
"if",
"len",
"(",
"end_effector_link",
")",
">",
"0",
"or",
"self",
".",
"has_end_effector_link",
"(",
")",
":",
"if",
"not",
"self",
".",
"_g",
".",
"set_position_target",
"(",
"xyz",
"[",
"0",
"]",
",",
"xyz",
"[",
"1",
"]",
",",
"xyz",
"[",
"2",
"]",
",",
"end_effector_link",
")",
":",
"raise",
"MoveItCommanderException",
"(",
"\"Unable to set position target\"",
")",
"else",
":",
"raise",
"MoveItCommanderException",
"(",
"\"There is no end effector to set the pose for\"",
")"
] | https://github.com/ros-planning/moveit2/blob/dd240ef6fd8b9932a7a53964140f2952786187a9/moveit_commander/src/moveit_commander/move_group.py#L322-L332 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | buildscripts/packager-enterprise.py | python | tarfile | (build_os, arch, spec) | return "dl/mongodb-linux-%s-enterprise-%s-%s.tar.gz" % (spec.version(), build_os, arch) | Return the location where we store the downloaded tarball for
this package | Return the location where we store the downloaded tarball for
this package | [
"Return",
"the",
"location",
"where",
"we",
"store",
"the",
"downloaded",
"tarball",
"for",
"this",
"package"
] | def tarfile(build_os, arch, spec):
"""Return the location where we store the downloaded tarball for
this package"""
return "dl/mongodb-linux-%s-enterprise-%s-%s.tar.gz" % (spec.version(), build_os, arch) | [
"def",
"tarfile",
"(",
"build_os",
",",
"arch",
",",
"spec",
")",
":",
"return",
"\"dl/mongodb-linux-%s-enterprise-%s-%s.tar.gz\"",
"%",
"(",
"spec",
".",
"version",
"(",
")",
",",
"build_os",
",",
"arch",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/packager-enterprise.py#L175-L178 | |
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | scripts/upload.py | python | SubversionVCS.GuessBase | (self, required) | return self.svn_base | Wrapper for _GuessBase. | Wrapper for _GuessBase. | [
"Wrapper",
"for",
"_GuessBase",
"."
] | def GuessBase(self, required):
"""Wrapper for _GuessBase."""
return self.svn_base | [
"def",
"GuessBase",
"(",
"self",
",",
"required",
")",
":",
"return",
"self",
".",
"svn_base"
] | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/upload.py#L1260-L1262 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/gxx.py | python | gxx_modifier_aix | (conf) | Configuration flags for executing g++ on AIX | Configuration flags for executing g++ on AIX | [
"Configuration",
"flags",
"for",
"executing",
"g",
"++",
"on",
"AIX"
] | def gxx_modifier_aix(conf):
"""Configuration flags for executing g++ on AIX"""
v = conf.env
v['LINKFLAGS_cxxprogram']= ['-Wl,-brtl']
v['LINKFLAGS_cxxshlib'] = ['-shared', '-Wl,-brtl,-bexpfull']
v['SHLIB_MARKER'] = [] | [
"def",
"gxx_modifier_aix",
"(",
"conf",
")",
":",
"v",
"=",
"conf",
".",
"env",
"v",
"[",
"'LINKFLAGS_cxxprogram'",
"]",
"=",
"[",
"'-Wl,-brtl'",
"]",
"v",
"[",
"'LINKFLAGS_cxxshlib'",
"]",
"=",
"[",
"'-shared'",
",",
"'-Wl,-brtl,-bexpfull'",
"]",
"v",
"[",
"'SHLIB_MARKER'",
"]",
"=",
"[",
"]"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/gxx.py#L113-L119 | ||
kungfu-origin/kungfu | 90c84b2b590855654cb9a6395ed050e0f7763512 | core/deps/SQLiteCpp-2.3.0/cpplint.py | python | CheckLanguage | (filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error) | Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks rules from the 'C++ language rules' section of cppguide.html. | [
"Checks",
"rules",
"from",
"the",
"C",
"++",
"language",
"rules",
"section",
"of",
"cppguide",
".",
"html",
"."
] | def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# If the line is empty or consists of entirely a comment, no need to
# check it.
line = clean_lines.elided[linenum]
if not line:
return
match = _RE_PATTERN_INCLUDE.search(line)
if match:
CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
return
# Reset include state across preprocessor directives. This is meant
# to silence warnings for conditional includes.
if Match(r'^\s*#\s*(?:ifdef|elif|else|endif)\b', line):
include_state.ResetSection()
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
# TODO(unknown): figure out if they're using default arguments in fn proto.
# Check to see if they're using an conversion function cast.
# I just try to capture the most common basic types, though there are more.
# Parameterless conversion functions, such as bool(), are allowed as they are
# probably a member operator declaration or default constructor.
match = Search(
r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
r'(int|short|long|float|double|bool|char|const char*|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t)'
r'(\([^)].*)', line)
if match:
matched_new = match.group(1)
matched_type = match.group(2)
matched_funcptr = match.group(3)
# gMock methods are defined using some variant of MOCK_METHODx(name, type)
# where type may be float(), int(string), etc. Without context they are
# virtually indistinguishable from int(x) casts. Likewise, gMock's
# MockCallback takes a template parameter of the form return_type(arg_type),
# which looks much like the cast we're trying to detect.
#
# std::function<> wrapper has a similar problem.
#
# Return types for function pointers also look like casts if they
# don't have an extra space.
if (matched_new is None and # If new operator, then this isn't a cast
not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
Search(r'\bMockCallback<.*>', line) or
Search(r'\bstd::function<.*>', line)) and
not (matched_funcptr and
Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
matched_funcptr))):
# Try a bit harder to catch gmock lines: the only place where
# something looks like an old-style cast is where we declare the
# return type of the mocked method, and the only time when we
# are missing context is if MOCK_METHOD was split across
# multiple lines. The missing MOCK_METHOD is usually one or two
# lines back, so scan back one or two lines.
#
# It's not possible for gmock macros to appear in the first 2
# lines, since the class head + section name takes up 2 lines.
if (linenum < 2 or
not (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]))):
error(filename, linenum, 'readability/casting', 4,
'Using deprecated casting style. '
'Use static_cast<%s>(...) instead' %
matched_type)
# SRombauts: adding many builtin type
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'static_cast',
r'\((int|float|double|bool|long|short|char|unsigned long|unsigned int|unsigned short|unsigned char|size_t|time_t|u?int(16|32|64))\)', error)
# This doesn't catch all cases. Consider (const char * const)"hello".
#
# (char *) "foo" should always be a const_cast (reinterpret_cast won't
# compile).
if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
pass
else:
# Check pointer casts for other than string constants
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
# point where you think.
match = Search(
r'(?:&\(([^)]+)\)[\w(])|'
r'(?:&(static|dynamic|down|reinterpret)_cast\b)', line)
if match and match.group(1) != '*':
error(filename, linenum, 'runtime/casting', 4,
('Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'))
# Create an extended_line, which is the concatenation of the current and
# next lines, for more effective checking of code that may span more than one
# line.
if linenum + 1 < clean_lines.NumLines():
extended_line = line + clean_lines.elided[linenum + 1]
else:
extended_line = line
# Check for people declaring static/global STL strings at the top level.
# This is dangerous because the C++ language does not guarantee that
# globals with constructors are initialized before the first access.
match = Match(
r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
line)
# Make sure it's not a function.
# Function template specialization looks like: "string foo<Type>(...".
# Class template definitions look like: "string Foo<Type>::Method(...".
#
# Also ignore things that look like operators. These are matched separately
# because operator names cross non-word boundaries. If we change the pattern
# above, we would decrease the accuracy of matching identifiers.
if (match and
not Search(r'\boperator\W', line) and
not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3))):
error(filename, linenum, 'runtime/string', 4,
'For a static/global string constant, use a C style string instead: '
'"%schar %s[]".' %
(match.group(1), match.group(2)))
if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
error(filename, linenum, 'runtime/init', 4,
'You seem to be initializing a member variable with itself.')
if file_extension == 'h':
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
# (level 1 error)
pass
# Check if people are using the verboten C basic types. The only exception
# we regularly allow is "unsigned short port" for port.
if Search(r'\bshort port\b', line):
if not Search(r'\bunsigned short port\b', line):
error(filename, linenum, 'runtime/int', 4,
'Use "unsigned short" for ports, not "short"')
else:
match = Search(r'\b(short|long(?! +double)|long long)\b', line)
if match:
error(filename, linenum, 'runtime/int', 2,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
# When snprintf is used, the second argument shouldn't be a literal.
match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
if match and match.group(2) != '0':
# If 2nd arg is zero, snprintf is used to calculate size.
error(filename, linenum, 'runtime/printf', 3,
'If you can, use sizeof(%s) instead of %s as the 2nd arg '
'to snprintf.' % (match.group(1), match.group(2)))
# Check if some verboten C functions are being used.
if Search(r'\bsprintf\b', line):
error(filename, linenum, 'runtime/printf', 5,
'Never use sprintf. Use snprintf instead.')
match = Search(r'\b(strcpy|strcat)\b', line)
if match:
error(filename, linenum, 'runtime/printf', 4,
'Almost always, snprintf is better than %s' % match.group(1))
# Check if some verboten operator overloading is going on
# TODO(unknown): catch out-of-line unary operator&:
# class X {};
# int operator&(const X& x) { return 42; } // unary operator&
# The trick is it's hard to tell apart from binary operator&:
# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
if Search(r'\boperator\s*&\s*\(\s*\)', line):
error(filename, linenum, 'runtime/operator', 4,
'Unary operator& is dangerous. Do not use it.')
# Check for suspicious usage of "if" like
# } if (a == b) {
if Search(r'\}\s*if\s*\(', line):
error(filename, linenum, 'readability/braces', 4,
'Did you mean "else if"? If not, start a new line for "if".')
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
# TODO(sugawarayu): Catch the following case. Need to change the calling
# convention of the whole function to process multiple line to handle it.
# printf(
# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
if printf_args:
match = Match(r'([\w.\->()]+)$', printf_args)
if match and match.group(1) != '__VA_ARGS__':
function_name = re.search(r'\b((?:string)?printf)\s*\(',
line, re.I).group(1)
error(filename, linenum, 'runtime/printf', 4,
'Potential format string bug. Do %s("%%s", %s) instead.'
% (function_name, match.group(1)))
# Check for potential memset bugs like memset(buf, sizeof(buf), 0).
match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
error(filename, linenum, 'runtime/memset', 4,
'Did you mean "memset(%s, 0, %s)"?'
% (match.group(1), match.group(2)))
if Search(r'\busing namespace\b', line):
error(filename, linenum, 'build/namespaces', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
# Detect variable-length arrays.
match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
match.group(3).find(']') == -1):
# Split the size using space and arithmetic operators as delimiters.
# If any of the resulting tokens are not compile time constants then
# report the error.
tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
is_const = True
skip_next = False
for tok in tokens:
if skip_next:
skip_next = False
continue
if Search(r'sizeof\(.+\)', tok): continue
if Search(r'arraysize\(\w+\)', tok): continue
tok = tok.lstrip('(')
tok = tok.rstrip(')')
if not tok: continue
if Match(r'\d+', tok): continue
if Match(r'0[xX][0-9a-fA-F]+', tok): continue
if Match(r'k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
# A catch all for tricky sizeof cases, including 'sizeof expression',
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
# requires skipping the next token because we split on ' ' and '*'.
if tok.startswith('sizeof'):
skip_next = True
continue
is_const = False
break
if not is_const:
error(filename, linenum, 'runtime/arrays', 1,
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
# in the class declaration.
match = Match(
(r'\s*'
r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
r'\(.*\);$'),
line)
if match and linenum + 1 < clean_lines.NumLines():
next_line = clean_lines.elided[linenum + 1]
# We allow some, but not all, declarations of variables to be present
# in the statement that defines the class. The [\w\*,\s]* fragment of
# the regular expression below allows users to declare instances of
# the class or pointers to instances, but not less common types such
# as function pointers or arrays. It's a tradeoff between allowing
# reasonable code and avoiding trying to parse more C++ using regexps.
if not Search(r'^\s*}[\w\*,\s]*;', next_line):
error(filename, linenum, 'readability/constructors', 3,
match.group(1) + ' should be the last thing in the class')
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
if (file_extension == 'h'
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.')
# SRombauts: Detects post increment/decrement: sugests preincrement/predecrement instead
match = Search(r'(\w+)(\+\+|--)', line)
if match:
error(filename, linenum, 'runtime/preincrement', 4,
'Considere using "%s%s". '
'"%s%s" does a copy of "%s" which can be expensive for non simple scalar type.'
% (match.group(2), match.group(1), match.group(1), match.group(2), match.group(1)) ) | [
"def",
"CheckLanguage",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"include_state",
",",
"nesting_state",
",",
"error",
")",
":",
"# If the line is empty or consists of entirely a comment, no need to",
"# check it.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"not",
"line",
":",
"return",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
"return",
"# Reset include state across preprocessor directives. This is meant",
"# to silence warnings for conditional includes.",
"if",
"Match",
"(",
"r'^\\s*#\\s*(?:ifdef|elif|else|endif)\\b'",
",",
"line",
")",
":",
"include_state",
".",
"ResetSection",
"(",
")",
"# Make Windows paths like Unix.",
"fullname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"# TODO(unknown): figure out if they're using default arguments in fn proto.",
"# Check to see if they're using an conversion function cast.",
"# I just try to capture the most common basic types, though there are more.",
"# Parameterless conversion functions, such as bool(), are allowed as they are",
"# probably a member operator declaration or default constructor.",
"match",
"=",
"Search",
"(",
"r'(\\bnew\\s+)?\\b'",
"# Grab 'new' operator, if it's there",
"r'(int|short|long|float|double|bool|char|const char*|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t)'",
"r'(\\([^)].*)'",
",",
"line",
")",
"if",
"match",
":",
"matched_new",
"=",
"match",
".",
"group",
"(",
"1",
")",
"matched_type",
"=",
"match",
".",
"group",
"(",
"2",
")",
"matched_funcptr",
"=",
"match",
".",
"group",
"(",
"3",
")",
"# gMock methods are defined using some variant of MOCK_METHODx(name, type)",
"# where type may be float(), int(string), etc. Without context they are",
"# virtually indistinguishable from int(x) casts. Likewise, gMock's",
"# MockCallback takes a template parameter of the form return_type(arg_type),",
"# which looks much like the cast we're trying to detect.",
"#",
"# std::function<> wrapper has a similar problem.",
"#",
"# Return types for function pointers also look like casts if they",
"# don't have an extra space.",
"if",
"(",
"matched_new",
"is",
"None",
"and",
"# If new operator, then this isn't a cast",
"not",
"(",
"Match",
"(",
"r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('",
",",
"line",
")",
"or",
"Search",
"(",
"r'\\bMockCallback<.*>'",
",",
"line",
")",
"or",
"Search",
"(",
"r'\\bstd::function<.*>'",
",",
"line",
")",
")",
"and",
"not",
"(",
"matched_funcptr",
"and",
"Match",
"(",
"r'\\((?:[^() ]+::\\s*\\*\\s*)?[^() ]+\\)\\s*\\('",
",",
"matched_funcptr",
")",
")",
")",
":",
"# Try a bit harder to catch gmock lines: the only place where",
"# something looks like an old-style cast is where we declare the",
"# return type of the mocked method, and the only time when we",
"# are missing context is if MOCK_METHOD was split across",
"# multiple lines. The missing MOCK_METHOD is usually one or two",
"# lines back, so scan back one or two lines.",
"#",
"# It's not possible for gmock macros to appear in the first 2",
"# lines, since the class head + section name takes up 2 lines.",
"if",
"(",
"linenum",
"<",
"2",
"or",
"not",
"(",
"Match",
"(",
"r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
"or",
"Match",
"(",
"r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\(\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"2",
"]",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using deprecated casting style. '",
"'Use static_cast<%s>(...) instead'",
"%",
"matched_type",
")",
"# SRombauts: adding many builtin type",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'static_cast'",
",",
"r'\\((int|float|double|bool|long|short|char|unsigned long|unsigned int|unsigned short|unsigned char|size_t|time_t|u?int(16|32|64))\\)'",
",",
"error",
")",
"# This doesn't catch all cases. Consider (const char * const)\"hello\".",
"#",
"# (char *) \"foo\" should always be a const_cast (reinterpret_cast won't",
"# compile).",
"if",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'const_cast'",
",",
"r'\\((char\\s?\\*+\\s?)\\)\\s*\"'",
",",
"error",
")",
":",
"pass",
"else",
":",
"# Check pointer casts for other than string constants",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'reinterpret_cast'",
",",
"r'\\((\\w+\\s?\\*+\\s?)\\)'",
",",
"error",
")",
"# In addition, we look for people taking the address of a cast. This",
"# is dangerous -- casts can assign to temporaries, so the pointer doesn't",
"# point where you think.",
"match",
"=",
"Search",
"(",
"r'(?:&\\(([^)]+)\\)[\\w(])|'",
"r'(?:&(static|dynamic|down|reinterpret)_cast\\b)'",
",",
"line",
")",
"if",
"match",
"and",
"match",
".",
"group",
"(",
"1",
")",
"!=",
"'*'",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/casting'",
",",
"4",
",",
"(",
"'Are you taking an address of a cast? '",
"'This is dangerous: could be a temp var. '",
"'Take the address before doing the cast, rather than after'",
")",
")",
"# Create an extended_line, which is the concatenation of the current and",
"# next lines, for more effective checking of code that may span more than one",
"# line.",
"if",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"extended_line",
"=",
"line",
"+",
"clean_lines",
".",
"elided",
"[",
"linenum",
"+",
"1",
"]",
"else",
":",
"extended_line",
"=",
"line",
"# Check for people declaring static/global STL strings at the top level.",
"# This is dangerous because the C++ language does not guarantee that",
"# globals with constructors are initialized before the first access.",
"match",
"=",
"Match",
"(",
"r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\\b(.*)'",
",",
"line",
")",
"# Make sure it's not a function.",
"# Function template specialization looks like: \"string foo<Type>(...\".",
"# Class template definitions look like: \"string Foo<Type>::Method(...\".",
"#",
"# Also ignore things that look like operators. These are matched separately",
"# because operator names cross non-word boundaries. If we change the pattern",
"# above, we would decrease the accuracy of matching identifiers.",
"if",
"(",
"match",
"and",
"not",
"Search",
"(",
"r'\\boperator\\W'",
",",
"line",
")",
"and",
"not",
"Match",
"(",
"r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)?\\s*\\(([^\"]|$)'",
",",
"match",
".",
"group",
"(",
"3",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/string'",
",",
"4",
",",
"'For a static/global string constant, use a C style string instead: '",
"'\"%schar %s[]\".'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"if",
"Search",
"(",
"r'\\b([A-Za-z0-9_]*_)\\(\\1\\)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/init'",
",",
"4",
",",
"'You seem to be initializing a member variable with itself.'",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"# TODO(unknown): check that 1-arg constructors are explicit.",
"# How to tell it's a constructor?",
"# (handled in CheckForNonStandardConstructs for now)",
"# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS",
"# (level 1 error)",
"pass",
"# Check if people are using the verboten C basic types. The only exception",
"# we regularly allow is \"unsigned short port\" for port.",
"if",
"Search",
"(",
"r'\\bshort port\\b'",
",",
"line",
")",
":",
"if",
"not",
"Search",
"(",
"r'\\bunsigned short port\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/int'",
",",
"4",
",",
"'Use \"unsigned short\" for ports, not \"short\"'",
")",
"else",
":",
"match",
"=",
"Search",
"(",
"r'\\b(short|long(?! +double)|long long)\\b'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/int'",
",",
"2",
",",
"'Use int16/int64/etc, rather than the C type %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# When snprintf is used, the second argument shouldn't be a literal.",
"match",
"=",
"Search",
"(",
"r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,'",
",",
"line",
")",
"if",
"match",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'0'",
":",
"# If 2nd arg is zero, snprintf is used to calculate size.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"3",
",",
"'If you can, use sizeof(%s) instead of %s as the 2nd arg '",
"'to snprintf.'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"# Check if some verboten C functions are being used.",
"if",
"Search",
"(",
"r'\\bsprintf\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"5",
",",
"'Never use sprintf. Use snprintf instead.'",
")",
"match",
"=",
"Search",
"(",
"r'\\b(strcpy|strcat)\\b'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"4",
",",
"'Almost always, snprintf is better than %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# Check if some verboten operator overloading is going on",
"# TODO(unknown): catch out-of-line unary operator&:",
"# class X {};",
"# int operator&(const X& x) { return 42; } // unary operator&",
"# The trick is it's hard to tell apart from binary operator&:",
"# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&",
"if",
"Search",
"(",
"r'\\boperator\\s*&\\s*\\(\\s*\\)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/operator'",
",",
"4",
",",
"'Unary operator& is dangerous. Do not use it.'",
")",
"# Check for suspicious usage of \"if\" like",
"# } if (a == b) {",
"if",
"Search",
"(",
"r'\\}\\s*if\\s*\\('",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/braces'",
",",
"4",
",",
"'Did you mean \"else if\"? If not, start a new line for \"if\".'",
")",
"# Check for potential format string bugs like printf(foo).",
"# We constrain the pattern not to pick things like DocidForPrintf(foo).",
"# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())",
"# TODO(sugawarayu): Catch the following case. Need to change the calling",
"# convention of the whole function to process multiple line to handle it.",
"# printf(",
"# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);",
"printf_args",
"=",
"_GetTextInside",
"(",
"line",
",",
"r'(?i)\\b(string)?printf\\s*\\('",
")",
"if",
"printf_args",
":",
"match",
"=",
"Match",
"(",
"r'([\\w.\\->()]+)$'",
",",
"printf_args",
")",
"if",
"match",
"and",
"match",
".",
"group",
"(",
"1",
")",
"!=",
"'__VA_ARGS__'",
":",
"function_name",
"=",
"re",
".",
"search",
"(",
"r'\\b((?:string)?printf)\\s*\\('",
",",
"line",
",",
"re",
".",
"I",
")",
".",
"group",
"(",
"1",
")",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"4",
",",
"'Potential format string bug. Do %s(\"%%s\", %s) instead.'",
"%",
"(",
"function_name",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"# Check for potential memset bugs like memset(buf, sizeof(buf), 0).",
"match",
"=",
"Search",
"(",
"r'memset\\s*\\(([^,]*),\\s*([^,]*),\\s*0\\s*\\)'",
",",
"line",
")",
"if",
"match",
"and",
"not",
"Match",
"(",
"r\"^''|-?[0-9]+|0x[0-9A-Fa-f]$\"",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/memset'",
",",
"4",
",",
"'Did you mean \"memset(%s, 0, %s)\"?'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"if",
"Search",
"(",
"r'\\busing namespace\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces'",
",",
"5",
",",
"'Do not use namespace using-directives. '",
"'Use using-declarations instead.'",
")",
"# Detect variable-length arrays.",
"match",
"=",
"Match",
"(",
"r'\\s*(.+::)?(\\w+) [a-z]\\w*\\[(.+)];'",
",",
"line",
")",
"if",
"(",
"match",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'return'",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'delete'",
"and",
"match",
".",
"group",
"(",
"3",
")",
".",
"find",
"(",
"']'",
")",
"==",
"-",
"1",
")",
":",
"# Split the size using space and arithmetic operators as delimiters.",
"# If any of the resulting tokens are not compile time constants then",
"# report the error.",
"tokens",
"=",
"re",
".",
"split",
"(",
"r'\\s|\\+|\\-|\\*|\\/|<<|>>]'",
",",
"match",
".",
"group",
"(",
"3",
")",
")",
"is_const",
"=",
"True",
"skip_next",
"=",
"False",
"for",
"tok",
"in",
"tokens",
":",
"if",
"skip_next",
":",
"skip_next",
"=",
"False",
"continue",
"if",
"Search",
"(",
"r'sizeof\\(.+\\)'",
",",
"tok",
")",
":",
"continue",
"if",
"Search",
"(",
"r'arraysize\\(\\w+\\)'",
",",
"tok",
")",
":",
"continue",
"tok",
"=",
"tok",
".",
"lstrip",
"(",
"'('",
")",
"tok",
"=",
"tok",
".",
"rstrip",
"(",
"')'",
")",
"if",
"not",
"tok",
":",
"continue",
"if",
"Match",
"(",
"r'\\d+'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'0[xX][0-9a-fA-F]+'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'k[A-Z0-9]\\w*'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'(.+::)?k[A-Z0-9]\\w*'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'(.+::)?[A-Z][A-Z0-9_]*'",
",",
"tok",
")",
":",
"continue",
"# A catch all for tricky sizeof cases, including 'sizeof expression',",
"# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'",
"# requires skipping the next token because we split on ' ' and '*'.",
"if",
"tok",
".",
"startswith",
"(",
"'sizeof'",
")",
":",
"skip_next",
"=",
"True",
"continue",
"is_const",
"=",
"False",
"break",
"if",
"not",
"is_const",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/arrays'",
",",
"1",
",",
"'Do not use variable-length arrays. Use an appropriately named '",
"\"('k' followed by CamelCase) compile-time constant for the size.\"",
")",
"# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or",
"# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing",
"# in the class declaration.",
"match",
"=",
"Match",
"(",
"(",
"r'\\s*'",
"r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'",
"r'\\(.*\\);$'",
")",
",",
"line",
")",
"if",
"match",
"and",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"next_line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"+",
"1",
"]",
"# We allow some, but not all, declarations of variables to be present",
"# in the statement that defines the class. The [\\w\\*,\\s]* fragment of",
"# the regular expression below allows users to declare instances of",
"# the class or pointers to instances, but not less common types such",
"# as function pointers or arrays. It's a tradeoff between allowing",
"# reasonable code and avoiding trying to parse more C++ using regexps.",
"if",
"not",
"Search",
"(",
"r'^\\s*}[\\w\\*,\\s]*;'",
",",
"next_line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/constructors'",
",",
"3",
",",
"match",
".",
"group",
"(",
"1",
")",
"+",
"' should be the last thing in the class'",
")",
"# Check for use of unnamed namespaces in header files. Registration",
"# macros are typically OK, so we allow use of \"namespace {\" on lines",
"# that end with backslashes.",
"if",
"(",
"file_extension",
"==",
"'h'",
"and",
"Search",
"(",
"r'\\bnamespace\\s*{'",
",",
"line",
")",
"and",
"line",
"[",
"-",
"1",
"]",
"!=",
"'\\\\'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces'",
",",
"4",
",",
"'Do not use unnamed namespaces in header files. See '",
"'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'",
"' for more information.'",
")",
"# SRombauts: Detects post increment/decrement: sugests preincrement/predecrement instead",
"match",
"=",
"Search",
"(",
"r'(\\w+)(\\+\\+|--)'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/preincrement'",
",",
"4",
",",
"'Considere using \"%s%s\". '",
"'\"%s%s\" does a copy of \"%s\" which can be expensive for non simple scalar type.'",
"%",
"(",
"match",
".",
"group",
"(",
"2",
")",
",",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")"
] | https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L3763-L4070 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/atom/core.py | python | parse | (xml_string, target_class=None, version=1, encoding=None) | return _xml_element_from_tree(tree, target_class, version) | Parses the XML string according to the rules for the target_class.
Args:
xml_string: str or unicode
target_class: XmlElement or a subclass. If None is specified, the
XmlElement class is used.
version: int (optional) The version of the schema which should be used when
converting the XML into an object. The default is 1.
encoding: str (optional) The character encoding of the bytes in the
xml_string. Default is 'UTF-8'. | Parses the XML string according to the rules for the target_class. | [
"Parses",
"the",
"XML",
"string",
"according",
"to",
"the",
"rules",
"for",
"the",
"target_class",
"."
] | def parse(xml_string, target_class=None, version=1, encoding=None):
"""Parses the XML string according to the rules for the target_class.
Args:
xml_string: str or unicode
target_class: XmlElement or a subclass. If None is specified, the
XmlElement class is used.
version: int (optional) The version of the schema which should be used when
converting the XML into an object. The default is 1.
encoding: str (optional) The character encoding of the bytes in the
xml_string. Default is 'UTF-8'.
"""
if target_class is None:
target_class = XmlElement
if isinstance(xml_string, unicode):
if encoding is None:
xml_string = xml_string.encode(STRING_ENCODING)
else:
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _xml_element_from_tree(tree, target_class, version) | [
"def",
"parse",
"(",
"xml_string",
",",
"target_class",
"=",
"None",
",",
"version",
"=",
"1",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"target_class",
"is",
"None",
":",
"target_class",
"=",
"XmlElement",
"if",
"isinstance",
"(",
"xml_string",
",",
"unicode",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"xml_string",
"=",
"xml_string",
".",
"encode",
"(",
"STRING_ENCODING",
")",
"else",
":",
"xml_string",
"=",
"xml_string",
".",
"encode",
"(",
"encoding",
")",
"tree",
"=",
"ElementTree",
".",
"fromstring",
"(",
"xml_string",
")",
"return",
"_xml_element_from_tree",
"(",
"tree",
",",
"target_class",
",",
"version",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/atom/core.py#L485-L505 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py | python | _is_leap | (year) | return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) | year -> 1 if leap year, else 0. | year -> 1 if leap year, else 0. | [
"year",
"-",
">",
"1",
"if",
"leap",
"year",
"else",
"0",
"."
] | def _is_leap(year):
"year -> 1 if leap year, else 0."
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) | [
"def",
"_is_leap",
"(",
"year",
")",
":",
"return",
"year",
"%",
"4",
"==",
"0",
"and",
"(",
"year",
"%",
"100",
"!=",
"0",
"or",
"year",
"%",
"400",
"==",
"0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py#L37-L39 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/xgboost/python-package/xgboost/core.py | python | DMatrix.get_uint_info | (self, field) | return ctypes2numpy(ret, length.value, np.uint32) | Get unsigned integer property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of float information of the data | Get unsigned integer property from the DMatrix. | [
"Get",
"unsigned",
"integer",
"property",
"from",
"the",
"DMatrix",
"."
] | def get_uint_info(self, field):
"""Get unsigned integer property from the DMatrix.
Parameters
----------
field: str
The field name of the information
Returns
-------
info : array
a numpy array of float information of the data
"""
length = ctypes.c_ulong()
ret = ctypes.POINTER(ctypes.c_uint)()
_check_call(_LIB.XGDMatrixGetUIntInfo(self.handle,
c_str(field),
ctypes.byref(length),
ctypes.byref(ret)))
return ctypes2numpy(ret, length.value, np.uint32) | [
"def",
"get_uint_info",
"(",
"self",
",",
"field",
")",
":",
"length",
"=",
"ctypes",
".",
"c_ulong",
"(",
")",
"ret",
"=",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_uint",
")",
"(",
")",
"_check_call",
"(",
"_LIB",
".",
"XGDMatrixGetUIntInfo",
"(",
"self",
".",
"handle",
",",
"c_str",
"(",
"field",
")",
",",
"ctypes",
".",
"byref",
"(",
"length",
")",
",",
"ctypes",
".",
"byref",
"(",
"ret",
")",
")",
")",
"return",
"ctypes2numpy",
"(",
"ret",
",",
"length",
".",
"value",
",",
"np",
".",
"uint32",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/xgboost/python-package/xgboost/core.py#L298-L317 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBThreadPlan.__init__ | (self, *args) | __init__(lldb::SBThreadPlan self) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, SBThreadPlan threadPlan) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, lldb::ThreadPlanSP const & lldb_object_sp) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, SBThread thread, char const * class_name) -> SBThreadPlan | __init__(lldb::SBThreadPlan self) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, SBThreadPlan threadPlan) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, lldb::ThreadPlanSP const & lldb_object_sp) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, SBThread thread, char const * class_name) -> SBThreadPlan | [
"__init__",
"(",
"lldb",
"::",
"SBThreadPlan",
"self",
")",
"-",
">",
"SBThreadPlan",
"__init__",
"(",
"lldb",
"::",
"SBThreadPlan",
"self",
"SBThreadPlan",
"threadPlan",
")",
"-",
">",
"SBThreadPlan",
"__init__",
"(",
"lldb",
"::",
"SBThreadPlan",
"self",
"lldb",
"::",
"ThreadPlanSP",
"const",
"&",
"lldb_object_sp",
")",
"-",
">",
"SBThreadPlan",
"__init__",
"(",
"lldb",
"::",
"SBThreadPlan",
"self",
"SBThread",
"thread",
"char",
"const",
"*",
"class_name",
")",
"-",
">",
"SBThreadPlan"
] | def __init__(self, *args):
"""
__init__(lldb::SBThreadPlan self) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, SBThreadPlan threadPlan) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, lldb::ThreadPlanSP const & lldb_object_sp) -> SBThreadPlan
__init__(lldb::SBThreadPlan self, SBThread thread, char const * class_name) -> SBThreadPlan
"""
this = _lldb.new_SBThreadPlan(*args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"this",
"=",
"_lldb",
".",
"new_SBThreadPlan",
"(",
"*",
"args",
")",
"try",
":",
"self",
".",
"this",
".",
"append",
"(",
"this",
")",
"except",
"__builtin__",
".",
"Exception",
":",
"self",
".",
"this",
"=",
"this"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12085-L12096 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/plot.py | python | PlotGraphics.setPrinterScale | (self, scale) | Thickens up lines and markers only for printing | Thickens up lines and markers only for printing | [
"Thickens",
"up",
"lines",
"and",
"markers",
"only",
"for",
"printing"
] | def setPrinterScale(self, scale):
"""Thickens up lines and markers only for printing"""
self.printerScale = scale | [
"def",
"setPrinterScale",
"(",
"self",
",",
"scale",
")",
":",
"self",
".",
"printerScale",
"=",
"scale"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/plot.py#L480-L482 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/serial/serialutil.py | python | SerialBase.bytesize | (self) | return self._bytesize | Get the current byte size setting. | Get the current byte size setting. | [
"Get",
"the",
"current",
"byte",
"size",
"setting",
"."
] | def bytesize(self):
"""Get the current byte size setting."""
return self._bytesize | [
"def",
"bytesize",
"(",
"self",
")",
":",
"return",
"self",
".",
"_bytesize"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/serialutil.py#L298-L300 | |
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vtr_flow/scripts/python_libs/vtr/util.py | python | run_dir_name | (run_num) | return "run{:03d}".format(run_num) | Returns the formatted directory name for a specific run number | Returns the formatted directory name for a specific run number | [
"Returns",
"the",
"formatted",
"directory",
"name",
"for",
"a",
"specific",
"run",
"number"
] | def run_dir_name(run_num):
"""
Returns the formatted directory name for a specific run number
"""
return "run{:03d}".format(run_num) | [
"def",
"run_dir_name",
"(",
"run_num",
")",
":",
"return",
"\"run{:03d}\"",
".",
"format",
"(",
"run_num",
")"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/util.py#L511-L515 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/categorical.py | python | Categorical.isna | (self) | return ret | Detect missing values
Missing values (-1 in .codes) are detected.
Returns
-------
a boolean array of whether my values are null
See Also
--------
isna : Top-level isna.
isnull : Alias of isna.
Categorical.notna : Boolean inverse of Categorical.isna. | Detect missing values | [
"Detect",
"missing",
"values"
] | def isna(self):
"""
Detect missing values
Missing values (-1 in .codes) are detected.
Returns
-------
a boolean array of whether my values are null
See Also
--------
isna : Top-level isna.
isnull : Alias of isna.
Categorical.notna : Boolean inverse of Categorical.isna.
"""
ret = self._codes == -1
return ret | [
"def",
"isna",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_codes",
"==",
"-",
"1",
"return",
"ret"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/categorical.py#L1383-L1402 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/factorization_ops.py | python | WALSModel._cached_copy | (self, var, name) | Helper function to create a worker cached copy of a Variable.
Args:
var: Variable or list of Variable to cache. If a list, the items are
concatenated along dimension 0 to get the cached entry.
name: name of cached variable.
Returns:
Tuple consisting of following three entries:
cache: the new transient Variable.
cache_init: op to initialize the Variable
cache_reset: op to reset the Variable to some default value | Helper function to create a worker cached copy of a Variable. | [
"Helper",
"function",
"to",
"create",
"a",
"worker",
"cached",
"copy",
"of",
"a",
"Variable",
"."
] | def _cached_copy(self, var, name):
"""Helper function to create a worker cached copy of a Variable.
Args:
var: Variable or list of Variable to cache. If a list, the items are
concatenated along dimension 0 to get the cached entry.
name: name of cached variable.
Returns:
Tuple consisting of following three entries:
cache: the new transient Variable.
cache_init: op to initialize the Variable
cache_reset: op to reset the Variable to some default value
"""
if var is None:
return None, None, None
else:
cache = WALSModel._transient_var(name)
with ops.colocate_with(cache):
if isinstance(var, list):
assert var
if len(var) == 1:
var = var[0]
else:
var = tf.concat(0, var)
cache_init = tf.assign(cache, var, validate_shape=False)
cache_reset = tf.assign(cache, 1.0, validate_shape=False)
return cache, cache_init, cache_reset | [
"def",
"_cached_copy",
"(",
"self",
",",
"var",
",",
"name",
")",
":",
"if",
"var",
"is",
"None",
":",
"return",
"None",
",",
"None",
",",
"None",
"else",
":",
"cache",
"=",
"WALSModel",
".",
"_transient_var",
"(",
"name",
")",
"with",
"ops",
".",
"colocate_with",
"(",
"cache",
")",
":",
"if",
"isinstance",
"(",
"var",
",",
"list",
")",
":",
"assert",
"var",
"if",
"len",
"(",
"var",
")",
"==",
"1",
":",
"var",
"=",
"var",
"[",
"0",
"]",
"else",
":",
"var",
"=",
"tf",
".",
"concat",
"(",
"0",
",",
"var",
")",
"cache_init",
"=",
"tf",
".",
"assign",
"(",
"cache",
",",
"var",
",",
"validate_shape",
"=",
"False",
")",
"cache_reset",
"=",
"tf",
".",
"assign",
"(",
"cache",
",",
"1.0",
",",
"validate_shape",
"=",
"False",
")",
"return",
"cache",
",",
"cache_init",
",",
"cache_reset"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L211-L239 | ||
google/ml-metadata | b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d | ml_metadata/metadata_store/types.py | python | _NodeAndType._is_consistent | (self) | return True | Test if the type and the node are consistent. | Test if the type and the node are consistent. | [
"Test",
"if",
"the",
"type",
"and",
"the",
"node",
"are",
"consistent",
"."
] | def _is_consistent(self) -> bool:
"""Test if the type and the node are consistent."""
node = self._get_node()
node_type = self._get_type()
if node.HasField("type_id") and node_type.HasField("id"):
if node.type_id != node_type.id:
return False
# All fields are optional, by definition.
for k, v in node.properties.items():
if k not in node_type.properties:
return False
if not _value_is_consistent(v, node_type.properties[k]):
return False
return True | [
"def",
"_is_consistent",
"(",
"self",
")",
"->",
"bool",
":",
"node",
"=",
"self",
".",
"_get_node",
"(",
")",
"node_type",
"=",
"self",
".",
"_get_type",
"(",
")",
"if",
"node",
".",
"HasField",
"(",
"\"type_id\"",
")",
"and",
"node_type",
".",
"HasField",
"(",
"\"id\"",
")",
":",
"if",
"node",
".",
"type_id",
"!=",
"node_type",
".",
"id",
":",
"return",
"False",
"# All fields are optional, by definition.",
"for",
"k",
",",
"v",
"in",
"node",
".",
"properties",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"node_type",
".",
"properties",
":",
"return",
"False",
"if",
"not",
"_value_is_consistent",
"(",
"v",
",",
"node_type",
".",
"properties",
"[",
"k",
"]",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/google/ml-metadata/blob/b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d/ml_metadata/metadata_store/types.py#L329-L343 | |
zhaoweicai/cascade-rcnn | 2252f46158ea6555868ca6fa5c221ea71d9b5e6c | scripts/cpp_lint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",
")",
"include_state",
"=",
"_IncludeState",
"(",
")",
"function_state",
"=",
"_FunctionState",
"(",
")",
"nesting_state",
"=",
"_NestingState",
"(",
")",
"ResetNolintSuppressions",
"(",
")",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"CheckForHeaderGuard",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"clean_lines",
"=",
"CleansedLines",
"(",
"lines",
")",
"for",
"line",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
")",
"nesting_state",
".",
"CheckCompletedBlocks",
"(",
"filename",
",",
"error",
")",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
")",
"# We check here rather than inside ProcessLine so that we see raw",
"# lines rather than \"cleaned\" lines.",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")"
] | https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L4648-L4691 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py | python | KMeans._infer_graph | (self, inputs, clusters) | return zip(*output) | Maps input to closest cluster and the score.
Args:
inputs: list of input Tensors.
clusters: Tensor of cluster centers.
Returns:
List of tuple, where each value in tuple corresponds to a value in inp.
The tuple has following three elements:
all_scores: distance of each input to each cluster center.
score: distance of each input to closest cluster center.
cluster_idx: index of cluster center closest to the corresponding input. | Maps input to closest cluster and the score. | [
"Maps",
"input",
"to",
"closest",
"cluster",
"and",
"the",
"score",
"."
] | def _infer_graph(self, inputs, clusters):
"""Maps input to closest cluster and the score.
Args:
inputs: list of input Tensors.
clusters: Tensor of cluster centers.
Returns:
List of tuple, where each value in tuple corresponds to a value in inp.
The tuple has following three elements:
all_scores: distance of each input to each cluster center.
score: distance of each input to closest cluster center.
cluster_idx: index of cluster center closest to the corresponding input.
"""
assert isinstance(inputs, list)
# Pairwise distances are used only by transform(). In all other cases, this
# sub-graph is not evaluated.
scores = self._distance_graph(inputs, clusters, self._distance_metric)
output = []
if (self._distance_metric == COSINE_DISTANCE and
not self._clusters_l2_normalized()):
# The cosine distance between normalized vectors x and y is the same as
# 2 * squared_euclidean_distance. We are using this fact and reusing the
# nearest_neighbors op.
# TODO(ands): Support COSINE distance in nearest_neighbors and remove
# this.
with ops.colocate_with(clusters, ignore_existing=True):
clusters = nn_impl.l2_normalize(clusters, dim=1)
for inp, score in zip(inputs, scores):
with ops.colocate_with(inp, ignore_existing=True):
(indices, distances) = gen_clustering_ops.nearest_neighbors(
inp, clusters, 1)
if self._distance_metric == COSINE_DISTANCE:
distances *= 0.5
output.append((score, array_ops.squeeze(distances, [-1]),
array_ops.squeeze(indices, [-1])))
return zip(*output) | [
"def",
"_infer_graph",
"(",
"self",
",",
"inputs",
",",
"clusters",
")",
":",
"assert",
"isinstance",
"(",
"inputs",
",",
"list",
")",
"# Pairwise distances are used only by transform(). In all other cases, this",
"# sub-graph is not evaluated.",
"scores",
"=",
"self",
".",
"_distance_graph",
"(",
"inputs",
",",
"clusters",
",",
"self",
".",
"_distance_metric",
")",
"output",
"=",
"[",
"]",
"if",
"(",
"self",
".",
"_distance_metric",
"==",
"COSINE_DISTANCE",
"and",
"not",
"self",
".",
"_clusters_l2_normalized",
"(",
")",
")",
":",
"# The cosine distance between normalized vectors x and y is the same as",
"# 2 * squared_euclidean_distance. We are using this fact and reusing the",
"# nearest_neighbors op.",
"# TODO(ands): Support COSINE distance in nearest_neighbors and remove",
"# this.",
"with",
"ops",
".",
"colocate_with",
"(",
"clusters",
",",
"ignore_existing",
"=",
"True",
")",
":",
"clusters",
"=",
"nn_impl",
".",
"l2_normalize",
"(",
"clusters",
",",
"dim",
"=",
"1",
")",
"for",
"inp",
",",
"score",
"in",
"zip",
"(",
"inputs",
",",
"scores",
")",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"inp",
",",
"ignore_existing",
"=",
"True",
")",
":",
"(",
"indices",
",",
"distances",
")",
"=",
"gen_clustering_ops",
".",
"nearest_neighbors",
"(",
"inp",
",",
"clusters",
",",
"1",
")",
"if",
"self",
".",
"_distance_metric",
"==",
"COSINE_DISTANCE",
":",
"distances",
"*=",
"0.5",
"output",
".",
"append",
"(",
"(",
"score",
",",
"array_ops",
".",
"squeeze",
"(",
"distances",
",",
"[",
"-",
"1",
"]",
")",
",",
"array_ops",
".",
"squeeze",
"(",
"indices",
",",
"[",
"-",
"1",
"]",
")",
")",
")",
"return",
"zip",
"(",
"*",
"output",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py#L227-L263 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | FSFile.GetModificationTime | (*args, **kwargs) | return _core_.FSFile_GetModificationTime(*args, **kwargs) | GetModificationTime(self) -> DateTime | GetModificationTime(self) -> DateTime | [
"GetModificationTime",
"(",
"self",
")",
"-",
">",
"DateTime"
] | def GetModificationTime(*args, **kwargs):
"""GetModificationTime(self) -> DateTime"""
return _core_.FSFile_GetModificationTime(*args, **kwargs) | [
"def",
"GetModificationTime",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"FSFile_GetModificationTime",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2311-L2313 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py | python | OptionMenu.__init__ | (self, master, variable, default=None, *values, **kwargs) | Construct a themed OptionMenu widget with master as the parent,
the resource textvariable set to variable, the initially selected
value specified by the default parameter, the menu values given by
*values and additional keywords.
WIDGET-SPECIFIC OPTIONS
style: stylename
Menubutton style.
direction: 'above', 'below', 'left', 'right', or 'flush'
Menubutton direction.
command: callback
A callback that will be invoked after selecting an item. | Construct a themed OptionMenu widget with master as the parent,
the resource textvariable set to variable, the initially selected
value specified by the default parameter, the menu values given by
*values and additional keywords. | [
"Construct",
"a",
"themed",
"OptionMenu",
"widget",
"with",
"master",
"as",
"the",
"parent",
"the",
"resource",
"textvariable",
"set",
"to",
"variable",
"the",
"initially",
"selected",
"value",
"specified",
"by",
"the",
"default",
"parameter",
"the",
"menu",
"values",
"given",
"by",
"*",
"values",
"and",
"additional",
"keywords",
"."
] | def __init__(self, master, variable, default=None, *values, **kwargs):
"""Construct a themed OptionMenu widget with master as the parent,
the resource textvariable set to variable, the initially selected
value specified by the default parameter, the menu values given by
*values and additional keywords.
WIDGET-SPECIFIC OPTIONS
style: stylename
Menubutton style.
direction: 'above', 'below', 'left', 'right', or 'flush'
Menubutton direction.
command: callback
A callback that will be invoked after selecting an item.
"""
kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
'direction': kwargs.pop('direction', None)}
Menubutton.__init__(self, master, **kw)
self['menu'] = Tkinter.Menu(self, tearoff=False)
self._variable = variable
self._callback = kwargs.pop('command', None)
if kwargs:
raise Tkinter.TclError('unknown option -%s' % (
kwargs.iterkeys().next()))
self.set_menu(default, *values) | [
"def",
"__init__",
"(",
"self",
",",
"master",
",",
"variable",
",",
"default",
"=",
"None",
",",
"*",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"{",
"'textvariable'",
":",
"variable",
",",
"'style'",
":",
"kwargs",
".",
"pop",
"(",
"'style'",
",",
"None",
")",
",",
"'direction'",
":",
"kwargs",
".",
"pop",
"(",
"'direction'",
",",
"None",
")",
"}",
"Menubutton",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"*",
"*",
"kw",
")",
"self",
"[",
"'menu'",
"]",
"=",
"Tkinter",
".",
"Menu",
"(",
"self",
",",
"tearoff",
"=",
"False",
")",
"self",
".",
"_variable",
"=",
"variable",
"self",
".",
"_callback",
"=",
"kwargs",
".",
"pop",
"(",
"'command'",
",",
"None",
")",
"if",
"kwargs",
":",
"raise",
"Tkinter",
".",
"TclError",
"(",
"'unknown option -%s'",
"%",
"(",
"kwargs",
".",
"iterkeys",
"(",
")",
".",
"next",
"(",
")",
")",
")",
"self",
".",
"set_menu",
"(",
"default",
",",
"*",
"values",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py#L1557-L1583 | ||
sfzhang15/RefineDet | 52b6fe23dc1a160fe710b7734576dca509bf4fae | scripts/cpp_lint.py | python | CheckEmptyBlockBody | (filename, clean_lines, linenum, error) | Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Look for empty loop/conditional body with only a single semicolon. | [
"Look",
"for",
"empty",
"loop",
"/",
"conditional",
"body",
"with",
"only",
"a",
"single",
"semicolon",
"."
] | def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
"""Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" blocks here, since an empty conditional block
# is likely an error.
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
# Find the end of the conditional expression
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
# Output warning if what follows the condition expression is a semicolon.
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
if matched.group(1) == 'if':
error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
'Empty conditional bodies should use {}')
else:
error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
'Empty loop bodies should use {} or continue') | [
"def",
"CheckEmptyBlockBody",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Search for loop keywords at the beginning of the line. Because only",
"# whitespaces are allowed before the keywords, this will also ignore most",
"# do-while-loops, since those lines should start with closing brace.",
"#",
"# We also check \"if\" blocks here, since an empty conditional block",
"# is likely an error.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"matched",
"=",
"Match",
"(",
"r'\\s*(for|while|if)\\s*\\('",
",",
"line",
")",
"if",
"matched",
":",
"# Find the end of the conditional expression",
"(",
"end_line",
",",
"end_linenum",
",",
"end_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"line",
".",
"find",
"(",
"'('",
")",
")",
"# Output warning if what follows the condition expression is a semicolon.",
"# No warning for all other cases, including whitespace or newline, since we",
"# have a separate check for semicolons preceded by whitespace.",
"if",
"end_pos",
">=",
"0",
"and",
"Match",
"(",
"r';'",
",",
"end_line",
"[",
"end_pos",
":",
"]",
")",
":",
"if",
"matched",
".",
"group",
"(",
"1",
")",
"==",
"'if'",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_conditional_body'",
",",
"5",
",",
"'Empty conditional bodies should use {}'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_loop_body'",
",",
"5",
",",
"'Empty loop bodies should use {} or continue'",
")"
] | https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/scripts/cpp_lint.py#L3247-L3279 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_model.py | python | GeneralFittingModel.simultaneous_fit_by | (self, simultaneous_fit_by: str) | Sets the simultaneous fit by parameter stored in the model. | Sets the simultaneous fit by parameter stored in the model. | [
"Sets",
"the",
"simultaneous",
"fit",
"by",
"parameter",
"stored",
"in",
"the",
"model",
"."
] | def simultaneous_fit_by(self, simultaneous_fit_by: str) -> None:
"""Sets the simultaneous fit by parameter stored in the model."""
self.fitting_context.simultaneous_fit_by = simultaneous_fit_by | [
"def",
"simultaneous_fit_by",
"(",
"self",
",",
"simultaneous_fit_by",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"fitting_context",
".",
"simultaneous_fit_by",
"=",
"simultaneous_fit_by"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_model.py#L71-L73 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py | python | _Type.ConvertToMSBuild | (self, value) | return value | Returns the MSBuild equivalent of the MSVS value given.
Args:
value: the MSVS value to convert.
Returns:
the MSBuild equivalent.
Raises:
ValueError if value is not valid. | Returns the MSBuild equivalent of the MSVS value given. | [
"Returns",
"the",
"MSBuild",
"equivalent",
"of",
"the",
"MSVS",
"value",
"given",
"."
] | def ConvertToMSBuild(self, value):
"""Returns the MSBuild equivalent of the MSVS value given.
Args:
value: the MSVS value to convert.
Returns:
the MSBuild equivalent.
Raises:
ValueError if value is not valid.
"""
return value | [
"def",
"ConvertToMSBuild",
"(",
"self",
",",
"value",
")",
":",
"return",
"value"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L94-L106 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/mfc/activex.py | python | MakeControlInstance | ( controlClass, name = None ) | return MakeControlClass(controlClass, name)() | As for MakeControlClass(), but returns an instance of the class. | As for MakeControlClass(), but returns an instance of the class. | [
"As",
"for",
"MakeControlClass",
"()",
"but",
"returns",
"an",
"instance",
"of",
"the",
"class",
"."
] | def MakeControlInstance( controlClass, name = None ):
"""As for MakeControlClass(), but returns an instance of the class.
"""
return MakeControlClass(controlClass, name)() | [
"def",
"MakeControlInstance",
"(",
"controlClass",
",",
"name",
"=",
"None",
")",
":",
"return",
"MakeControlClass",
"(",
"controlClass",
",",
"name",
")",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/mfc/activex.py#L72-L75 | |
microsoft/EdgeML | ef9f8a77f096acbdeb941014791f8eda1c1bc35b | tools/SeeDot/seedot/compiler/converter/util.py | python | extractXandYfromMat | (mat, numOutputs) | return X, Y | The first numOutputs entries are used as Y.
The remaining entries are part of X. | The first numOutputs entries are used as Y.
The remaining entries are part of X. | [
"The",
"first",
"numOutputs",
"entries",
"are",
"used",
"as",
"Y",
".",
"The",
"remaining",
"entries",
"are",
"part",
"of",
"X",
"."
] | def extractXandYfromMat(mat, numOutputs):
'''
The first numOutputs entries are used as Y.
The remaining entries are part of X.
'''
X = []
Y = []
for i in range(len(mat)):
ys = [float(x) for x in mat[i][0:numOutputs]]
isInt = all(element.is_integer() for element in ys)
if isInt:
Y.append([int(x) for x in mat[i][0:numOutputs]])
else:
Y.append(ys)
X.append(mat[i][numOutputs:])
return X, Y | [
"def",
"extractXandYfromMat",
"(",
"mat",
",",
"numOutputs",
")",
":",
"X",
"=",
"[",
"]",
"Y",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"mat",
")",
")",
":",
"ys",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"mat",
"[",
"i",
"]",
"[",
"0",
":",
"numOutputs",
"]",
"]",
"isInt",
"=",
"all",
"(",
"element",
".",
"is_integer",
"(",
")",
"for",
"element",
"in",
"ys",
")",
"if",
"isInt",
":",
"Y",
".",
"append",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"mat",
"[",
"i",
"]",
"[",
"0",
":",
"numOutputs",
"]",
"]",
")",
"else",
":",
"Y",
".",
"append",
"(",
"ys",
")",
"X",
".",
"append",
"(",
"mat",
"[",
"i",
"]",
"[",
"numOutputs",
":",
"]",
")",
"return",
"X",
",",
"Y"
] | https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/tools/SeeDot/seedot/compiler/converter/util.py#L217-L234 | |
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | build-support/check_compatibility.py | python | get_artifact_name | (jar_path) | return ARTIFACT_NAME_PATTERN.search(jar_path).group(1) | Return the artifact name given a full jar path. | Return the artifact name given a full jar path. | [
"Return",
"the",
"artifact",
"name",
"given",
"a",
"full",
"jar",
"path",
"."
] | def get_artifact_name(jar_path):
""" Return the artifact name given a full jar path. """
return ARTIFACT_NAME_PATTERN.search(jar_path).group(1) | [
"def",
"get_artifact_name",
"(",
"jar_path",
")",
":",
"return",
"ARTIFACT_NAME_PATTERN",
".",
"search",
"(",
"jar_path",
")",
".",
"group",
"(",
"1",
")"
] | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/check_compatibility.py#L139-L141 | |
bairdzhang/smallhardface | 76fa1d87a9602d9b13d7a7fe693fc7aec91cab80 | caffe/scripts/cpp_lint.py | python | CheckCaffeRandom | (filename, clean_lines, linenum, error) | Checks for calls to C random functions (rand, rand_r, random, ...).
Caffe code should (almost) always use the caffe_rng_* functions rather
than these, as the internal state of these C functions is independent of the
native Caffe RNG system which should produce deterministic results for a
fixed Caffe seed set using Caffe::set_random_seed(...).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for calls to C random functions (rand, rand_r, random, ...). | [
"Checks",
"for",
"calls",
"to",
"C",
"random",
"functions",
"(",
"rand",
"rand_r",
"random",
"...",
")",
"."
] | def CheckCaffeRandom(filename, clean_lines, linenum, error):
"""Checks for calls to C random functions (rand, rand_r, random, ...).
Caffe code should (almost) always use the caffe_rng_* functions rather
than these, as the internal state of these C functions is independent of the
native Caffe RNG system which should produce deterministic results for a
fixed Caffe seed set using Caffe::set_random_seed(...).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for function in c_random_function_list:
ix = line.find(function)
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
error(filename, linenum, 'caffe/random_fn', 2,
'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '
+ function +
') to ensure results are deterministic for a fixed Caffe seed.') | [
"def",
"CheckCaffeRandom",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"for",
"function",
"in",
"c_random_function_list",
":",
"ix",
"=",
"line",
".",
"find",
"(",
"function",
")",
"# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison",
"if",
"ix",
">=",
"0",
"and",
"(",
"ix",
"==",
"0",
"or",
"(",
"not",
"line",
"[",
"ix",
"-",
"1",
"]",
".",
"isalnum",
"(",
")",
"and",
"line",
"[",
"ix",
"-",
"1",
"]",
"not",
"in",
"(",
"'_'",
",",
"'.'",
",",
"'>'",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'caffe/random_fn'",
",",
"2",
",",
"'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '",
"+",
"function",
"+",
"') to ensure results are deterministic for a fixed Caffe seed.'",
")"
] | https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/scripts/cpp_lint.py#L1644-L1667 | ||
google/asylo | a3b09ebff6c0e3b10e25d40f14991e16bb75d883 | asylo/platform/system_call/type_conversions/types_parse_functions.py | python | get_structs | () | return '#define STRUCTS_INIT \\\n{}\n'.format(', \\\n'.join(struct_rows)) | r"""Returns a macro containing all struct descriptions.
The returned macro is used by types conversion generator to initialize a
struct description table (struct_properties_table) mapping struct names to a
struct (StructProperties) describing the struct properties, including struct
members. A typical output of get_structs looks like the following -
#define STRUCTS_INIT \
{"stat", {true, false, {{"st_dev", "int64_t"}, {"st_ino", "int64_t"}}}}, \
{"timespec", {true, false, {{"tv_sec", "int64_t"}, {"tv_nsec", "int64_t"}}}}
Each line contains a struct, and has the following pattern -
{"struct_name", {pack_attributes, skip_conversions, \
{{"member_name1", "member_type1"}, {"member_name2", "member_type2"}}}} | r"""Returns a macro containing all struct descriptions. | [
"r",
"Returns",
"a",
"macro",
"containing",
"all",
"struct",
"descriptions",
"."
] | def get_structs():
r"""Returns a macro containing all struct descriptions.
The returned macro is used by types conversion generator to initialize a
struct description table (struct_properties_table) mapping struct names to a
struct (StructProperties) describing the struct properties, including struct
members. A typical output of get_structs looks like the following -
#define STRUCTS_INIT \
{"stat", {true, false, {{"st_dev", "int64_t"}, {"st_ino", "int64_t"}}}}, \
{"timespec", {true, false, {{"tv_sec", "int64_t"}, {"tv_nsec", "int64_t"}}}}
Each line contains a struct, and has the following pattern -
{"struct_name", {pack_attributes, skip_conversions, \
{{"member_name1", "member_type1"}, {"member_name2", "member_type2"}}}}
"""
struct_rows = []
for struct_name, struct_properties in sorted(_struct_map.items()):
struct_rows.append(
'{{{struct}, {{{pack_attributes}, {skip_conversions}, {{{values}}}}}}}'
.format(
struct='"{}"'.format(struct_name),
pack_attributes='true'
if struct_properties['pack_attributes'] else 'false',
skip_conversions='true'
if struct_properties['skip_conversions'] else 'false',
values=struct_properties['values']))
return '#define STRUCTS_INIT \\\n{}\n'.format(', \\\n'.join(struct_rows)) | [
"def",
"get_structs",
"(",
")",
":",
"struct_rows",
"=",
"[",
"]",
"for",
"struct_name",
",",
"struct_properties",
"in",
"sorted",
"(",
"_struct_map",
".",
"items",
"(",
")",
")",
":",
"struct_rows",
".",
"append",
"(",
"'{{{struct}, {{{pack_attributes}, {skip_conversions}, {{{values}}}}}}}'",
".",
"format",
"(",
"struct",
"=",
"'\"{}\"'",
".",
"format",
"(",
"struct_name",
")",
",",
"pack_attributes",
"=",
"'true'",
"if",
"struct_properties",
"[",
"'pack_attributes'",
"]",
"else",
"'false'",
",",
"skip_conversions",
"=",
"'true'",
"if",
"struct_properties",
"[",
"'skip_conversions'",
"]",
"else",
"'false'",
",",
"values",
"=",
"struct_properties",
"[",
"'values'",
"]",
")",
")",
"return",
"'#define STRUCTS_INIT \\\\\\n{}\\n'",
".",
"format",
"(",
"', \\\\\\n'",
".",
"join",
"(",
"struct_rows",
")",
")"
] | https://github.com/google/asylo/blob/a3b09ebff6c0e3b10e25d40f14991e16bb75d883/asylo/platform/system_call/type_conversions/types_parse_functions.py#L241-L269 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/Job.py | python | Job.suspend | (self) | Called when JobManager is going to stop running this job for a
while. | Called when JobManager is going to stop running this job for a
while. | [
"Called",
"when",
"JobManager",
"is",
"going",
"to",
"stop",
"running",
"this",
"job",
"for",
"a",
"while",
"."
] | def suspend(self):
"""Called when JobManager is going to stop running this job for a
while.
""" | [
"def",
"suspend",
"(",
"self",
")",
":"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Job.py#L77-L80 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/multiversionconstants.py | python | version_str | (version) | return '{}.{}'.format(version.major, version.minor) | Return a string of the given version in 'MAJOR.MINOR' form. | Return a string of the given version in 'MAJOR.MINOR' form. | [
"Return",
"a",
"string",
"of",
"the",
"given",
"version",
"in",
"MAJOR",
".",
"MINOR",
"form",
"."
] | def version_str(version):
"""Return a string of the given version in 'MAJOR.MINOR' form."""
return '{}.{}'.format(version.major, version.minor) | [
"def",
"version_str",
"(",
"version",
")",
":",
"return",
"'{}.{}'",
".",
"format",
"(",
"version",
".",
"major",
",",
"version",
".",
"minor",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/multiversionconstants.py#L134-L136 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | demo/DPU-for-RNN/rnn_u25_u50lv/apps/open_information_extraction/utils/run_oie.py | python | get_confidence | (model, tag_per_token, class_probs) | return prod_prob | Get the confidence of a given model in a token list, using the class probabilities
associated with this prediction. | Get the confidence of a given model in a token list, using the class probabilities
associated with this prediction. | [
"Get",
"the",
"confidence",
"of",
"a",
"given",
"model",
"in",
"a",
"token",
"list",
"using",
"the",
"class",
"probabilities",
"associated",
"with",
"this",
"prediction",
"."
] | def get_confidence(model, tag_per_token, class_probs):
"""
Get the confidence of a given model in a token list, using the class probabilities
associated with this prediction.
"""
#tag_per_token = list([tag for tag in tag_per_token if tag != 'O'])
token_indexes = [model._model.vocab.get_token_index(tag, namespace = "labels") for tag in tag_per_token]
# Get probability per tag
#probs = [class_prob[token_index] for token_index, class_prob in zip(token_indexes, class_probs) if token_index != 0]
probs = [class_prob[token_index] for token_index, class_prob in zip(token_indexes, class_probs)]
# Combine (product)
if len(probs) == 0:
prod_prob = 0.0
print(tag_per_token)
else:
prod_prob = functools.reduce(operator.mul, probs)
return prod_prob | [
"def",
"get_confidence",
"(",
"model",
",",
"tag_per_token",
",",
"class_probs",
")",
":",
"#tag_per_token = list([tag for tag in tag_per_token if tag != 'O'])",
"token_indexes",
"=",
"[",
"model",
".",
"_model",
".",
"vocab",
".",
"get_token_index",
"(",
"tag",
",",
"namespace",
"=",
"\"labels\"",
")",
"for",
"tag",
"in",
"tag_per_token",
"]",
"# Get probability per tag",
"#probs = [class_prob[token_index] for token_index, class_prob in zip(token_indexes, class_probs) if token_index != 0]",
"probs",
"=",
"[",
"class_prob",
"[",
"token_index",
"]",
"for",
"token_index",
",",
"class_prob",
"in",
"zip",
"(",
"token_indexes",
",",
"class_probs",
")",
"]",
"# Combine (product)",
"if",
"len",
"(",
"probs",
")",
"==",
"0",
":",
"prod_prob",
"=",
"0.0",
"print",
"(",
"tag_per_token",
")",
"else",
":",
"prod_prob",
"=",
"functools",
".",
"reduce",
"(",
"operator",
".",
"mul",
",",
"probs",
")",
"return",
"prod_prob"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/demo/DPU-for-RNN/rnn_u25_u50lv/apps/open_information_extraction/utils/run_oie.py#L89-L107 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.get_element_attribute_names | (self, blkId) | return list(names) | get the list of element attribute names for a block
>>> attr_names = exo.get_element_attribute_names(elem_blk_id)
Parameters
----------
elem_blk_id : int
element block *ID* (not *INDEX*)
Returns
-------
<list<string>> attr_names | get the list of element attribute names for a block | [
"get",
"the",
"list",
"of",
"element",
"attribute",
"names",
"for",
"a",
"block"
] | def get_element_attribute_names(self, blkId):
"""
get the list of element attribute names for a block
>>> attr_names = exo.get_element_attribute_names(elem_blk_id)
Parameters
----------
elem_blk_id : int
element block *ID* (not *INDEX*)
Returns
-------
<list<string>> attr_names
"""
names = self.__ex_get_elem_attr_names(blkId)
return list(names) | [
"def",
"get_element_attribute_names",
"(",
"self",
",",
"blkId",
")",
":",
"names",
"=",
"self",
".",
"__ex_get_elem_attr_names",
"(",
"blkId",
")",
"return",
"list",
"(",
"names",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L3031-L3047 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py | python | TensorArray.__init__ | (self, dtype, size=None, dynamic_size=None,
clear_after_read=None, tensor_array_name=None, handle=None,
flow=None, infer_shape=True, name=None) | Construct a new TensorArray or wrap an existing TensorArray handle.
A note about the parameter `name`:
The name of the `TensorArray` (even if passed in) is uniquified: each time
a new `TensorArray` is created at runtime it is assigned its own name for
the duration of the run. This avoids name collissions if a `TensorArray`
is created within a `while_loop`.
Args:
dtype: (required) data type of the TensorArray.
size: (optional) int32 scalar `Tensor`: the size of the TensorArray.
Required if handle is not provided.
dynamic_size: (optional) Python bool: If true, writes to the TensorArray
can grow the TensorArray past its initial size. Default: False.
clear_after_read: Boolean (optional, default: True). If True, clear
TensorArray values after reading them. This disables read-many
semantics, but allows early release of memory.
tensor_array_name: (optional) Python string: the name of the TensorArray.
This is used when creating the TensorArray handle. If this value is
set, handle should be None.
handle: (optional) A `Tensor` handle to an existing TensorArray. If this
is set, tensor_array_name should be None.
flow: (optional) A float `Tensor` scalar coming from an existing
`TensorArray.flow`.
infer_shape: (optional, default: True) If True, shape inference
is enabled. In this case, all elements must have the same shape.
name: A name for the operation (optional).
Raises:
ValueError: if both handle and tensor_array_name are provided.
TypeError: if handle is provided but is not a Tensor. | Construct a new TensorArray or wrap an existing TensorArray handle. | [
"Construct",
"a",
"new",
"TensorArray",
"or",
"wrap",
"an",
"existing",
"TensorArray",
"handle",
"."
] | def __init__(self, dtype, size=None, dynamic_size=None,
clear_after_read=None, tensor_array_name=None, handle=None,
flow=None, infer_shape=True, name=None):
"""Construct a new TensorArray or wrap an existing TensorArray handle.
A note about the parameter `name`:
The name of the `TensorArray` (even if passed in) is uniquified: each time
a new `TensorArray` is created at runtime it is assigned its own name for
the duration of the run. This avoids name collissions if a `TensorArray`
is created within a `while_loop`.
Args:
dtype: (required) data type of the TensorArray.
size: (optional) int32 scalar `Tensor`: the size of the TensorArray.
Required if handle is not provided.
dynamic_size: (optional) Python bool: If true, writes to the TensorArray
can grow the TensorArray past its initial size. Default: False.
clear_after_read: Boolean (optional, default: True). If True, clear
TensorArray values after reading them. This disables read-many
semantics, but allows early release of memory.
tensor_array_name: (optional) Python string: the name of the TensorArray.
This is used when creating the TensorArray handle. If this value is
set, handle should be None.
handle: (optional) A `Tensor` handle to an existing TensorArray. If this
is set, tensor_array_name should be None.
flow: (optional) A float `Tensor` scalar coming from an existing
`TensorArray.flow`.
infer_shape: (optional, default: True) If True, shape inference
is enabled. In this case, all elements must have the same shape.
name: A name for the operation (optional).
Raises:
ValueError: if both handle and tensor_array_name are provided.
TypeError: if handle is provided but is not a Tensor.
"""
if handle is not None and tensor_array_name:
raise ValueError(
"Cannot construct with both handle and tensor_array_name")
if handle is not None and not isinstance(handle, ops.Tensor):
raise TypeError("Handle must be a Tensor")
if handle is None and size is None:
raise ValueError("Size must be provided if handle is not provided")
if handle is not None and size is not None:
raise ValueError("Cannot provide both a handle and size "
"at the same time")
if handle is not None and dynamic_size is not None:
raise ValueError("Cannot provide both a handle and dynamic_size "
"at the same time")
if handle is not None and clear_after_read is not None:
raise ValueError("Cannot provide both a handle and clear_after_read "
"at the same time")
if clear_after_read is None:
clear_after_read = True
dynamic_size = dynamic_size or False
self._dtype = dtype
self._infer_shape = infer_shape
# Record the current static shape for the array elements. The first
# write adds the shape of the tensor it writes, and all subsequent
# writes checks for shape equality.
self._elem_shape = []
with ops.op_scope([handle, size, flow], name, "TensorArray") as scope:
if handle is not None:
self._handle = handle
else:
if flow is not None:
with ops.colocate_with(flow):
self._handle = gen_data_flow_ops._tensor_array(
dtype=dtype, size=size, dynamic_size=dynamic_size,
clear_after_read=clear_after_read,
tensor_array_name=tensor_array_name, name=scope)
else:
self._handle = gen_data_flow_ops._tensor_array(
dtype=dtype, size=size, dynamic_size=dynamic_size,
clear_after_read=clear_after_read,
tensor_array_name=tensor_array_name, name=scope)
if flow is not None:
self._flow = flow
else:
with ops.colocate_with(self._handle):
self._flow = constant_op.constant(0, dtype=_dtypes.float32) | [
"def",
"__init__",
"(",
"self",
",",
"dtype",
",",
"size",
"=",
"None",
",",
"dynamic_size",
"=",
"None",
",",
"clear_after_read",
"=",
"None",
",",
"tensor_array_name",
"=",
"None",
",",
"handle",
"=",
"None",
",",
"flow",
"=",
"None",
",",
"infer_shape",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"if",
"handle",
"is",
"not",
"None",
"and",
"tensor_array_name",
":",
"raise",
"ValueError",
"(",
"\"Cannot construct with both handle and tensor_array_name\"",
")",
"if",
"handle",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"handle",
",",
"ops",
".",
"Tensor",
")",
":",
"raise",
"TypeError",
"(",
"\"Handle must be a Tensor\"",
")",
"if",
"handle",
"is",
"None",
"and",
"size",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Size must be provided if handle is not provided\"",
")",
"if",
"handle",
"is",
"not",
"None",
"and",
"size",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot provide both a handle and size \"",
"\"at the same time\"",
")",
"if",
"handle",
"is",
"not",
"None",
"and",
"dynamic_size",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot provide both a handle and dynamic_size \"",
"\"at the same time\"",
")",
"if",
"handle",
"is",
"not",
"None",
"and",
"clear_after_read",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot provide both a handle and clear_after_read \"",
"\"at the same time\"",
")",
"if",
"clear_after_read",
"is",
"None",
":",
"clear_after_read",
"=",
"True",
"dynamic_size",
"=",
"dynamic_size",
"or",
"False",
"self",
".",
"_dtype",
"=",
"dtype",
"self",
".",
"_infer_shape",
"=",
"infer_shape",
"# Record the current static shape for the array elements. The first",
"# write adds the shape of the tensor it writes, and all subsequent",
"# writes checks for shape equality.",
"self",
".",
"_elem_shape",
"=",
"[",
"]",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"handle",
",",
"size",
",",
"flow",
"]",
",",
"name",
",",
"\"TensorArray\"",
")",
"as",
"scope",
":",
"if",
"handle",
"is",
"not",
"None",
":",
"self",
".",
"_handle",
"=",
"handle",
"else",
":",
"if",
"flow",
"is",
"not",
"None",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"flow",
")",
":",
"self",
".",
"_handle",
"=",
"gen_data_flow_ops",
".",
"_tensor_array",
"(",
"dtype",
"=",
"dtype",
",",
"size",
"=",
"size",
",",
"dynamic_size",
"=",
"dynamic_size",
",",
"clear_after_read",
"=",
"clear_after_read",
",",
"tensor_array_name",
"=",
"tensor_array_name",
",",
"name",
"=",
"scope",
")",
"else",
":",
"self",
".",
"_handle",
"=",
"gen_data_flow_ops",
".",
"_tensor_array",
"(",
"dtype",
"=",
"dtype",
",",
"size",
"=",
"size",
",",
"dynamic_size",
"=",
"dynamic_size",
",",
"clear_after_read",
"=",
"clear_after_read",
",",
"tensor_array_name",
"=",
"tensor_array_name",
",",
"name",
"=",
"scope",
")",
"if",
"flow",
"is",
"not",
"None",
":",
"self",
".",
"_flow",
"=",
"flow",
"else",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"self",
".",
"_handle",
")",
":",
"self",
".",
"_flow",
"=",
"constant_op",
".",
"constant",
"(",
"0",
",",
"dtype",
"=",
"_dtypes",
".",
"float32",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py#L62-L144 | ||
cvmfs/cvmfs | 4637bdb5153178eadf885c1acf37bdc5c685bf8a | cpplint.py | python | FilesBelongToSameModule | (filename_cc, filename_h) | return files_belong_to_same_module, common_path | Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file. | Check if these two filenames belong to the same module. | [
"Check",
"if",
"these",
"two",
"filenames",
"belong",
"to",
"the",
"same",
"module",
"."
] | def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file.
"""
if not filename_cc.endswith('.cc'):
return (False, '')
filename_cc = filename_cc[:-len('.cc')]
if filename_cc.endswith('_unittest'):
filename_cc = filename_cc[:-len('_unittest')]
elif filename_cc.endswith('_test'):
filename_cc = filename_cc[:-len('_test')]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
if not filename_h.endswith('.h'):
return (False, '')
filename_h = filename_h[:-len('.h')]
if filename_h.endswith('-inl'):
filename_h = filename_h[:-len('-inl')]
filename_h = filename_h.replace('/public/', '/')
filename_h = filename_h.replace('/internal/', '/')
files_belong_to_same_module = filename_cc.endswith(filename_h)
common_path = ''
if files_belong_to_same_module:
common_path = filename_cc[:-len(filename_h)]
return files_belong_to_same_module, common_path | [
"def",
"FilesBelongToSameModule",
"(",
"filename_cc",
",",
"filename_h",
")",
":",
"if",
"not",
"filename_cc",
".",
"endswith",
"(",
"'.cc'",
")",
":",
"return",
"(",
"False",
",",
"''",
")",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'.cc'",
")",
"]",
"if",
"filename_cc",
".",
"endswith",
"(",
"'_unittest'",
")",
":",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'_unittest'",
")",
"]",
"elif",
"filename_cc",
".",
"endswith",
"(",
"'_test'",
")",
":",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'_test'",
")",
"]",
"filename_cc",
"=",
"filename_cc",
".",
"replace",
"(",
"'/public/'",
",",
"'/'",
")",
"filename_cc",
"=",
"filename_cc",
".",
"replace",
"(",
"'/internal/'",
",",
"'/'",
")",
"if",
"not",
"filename_h",
".",
"endswith",
"(",
"'.h'",
")",
":",
"return",
"(",
"False",
",",
"''",
")",
"filename_h",
"=",
"filename_h",
"[",
":",
"-",
"len",
"(",
"'.h'",
")",
"]",
"if",
"filename_h",
".",
"endswith",
"(",
"'-inl'",
")",
":",
"filename_h",
"=",
"filename_h",
"[",
":",
"-",
"len",
"(",
"'-inl'",
")",
"]",
"filename_h",
"=",
"filename_h",
".",
"replace",
"(",
"'/public/'",
",",
"'/'",
")",
"filename_h",
"=",
"filename_h",
".",
"replace",
"(",
"'/internal/'",
",",
"'/'",
")",
"files_belong_to_same_module",
"=",
"filename_cc",
".",
"endswith",
"(",
"filename_h",
")",
"common_path",
"=",
"''",
"if",
"files_belong_to_same_module",
":",
"common_path",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"filename_h",
")",
"]",
"return",
"files_belong_to_same_module",
",",
"common_path"
] | https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L5529-L5581 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextCtrl.GetDefaultStyle | (*args, **kwargs) | return _richtext.RichTextCtrl_GetDefaultStyle(*args, **kwargs) | GetDefaultStyle(self) -> RichTextAttr
Retrieves a copy of the default style object. | GetDefaultStyle(self) -> RichTextAttr | [
"GetDefaultStyle",
"(",
"self",
")",
"-",
">",
"RichTextAttr"
] | def GetDefaultStyle(*args, **kwargs):
"""
GetDefaultStyle(self) -> RichTextAttr
Retrieves a copy of the default style object.
"""
return _richtext.RichTextCtrl_GetDefaultStyle(*args, **kwargs) | [
"def",
"GetDefaultStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_GetDefaultStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3173-L3179 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py | python | _InitializeClustersOpFactory._add_new_centers | (self) | return self._num_clusters - array_ops.shape(a)[0] | Adds some centers and returns the number of centers remaining. | Adds some centers and returns the number of centers remaining. | [
"Adds",
"some",
"centers",
"and",
"returns",
"the",
"number",
"of",
"centers",
"remaining",
"."
] | def _add_new_centers(self):
"""Adds some centers and returns the number of centers remaining."""
new_centers = self._choose_initial_centers()
if self._distance_metric == COSINE_DISTANCE:
new_centers = nn_impl.l2_normalize(new_centers, dim=1)
# If cluster_centers is empty, it doesn't have the right shape for concat.
all_centers = control_flow_ops.cond(
math_ops.equal(self._num_selected, 0), lambda: new_centers,
lambda: array_ops.concat([self._cluster_centers, new_centers], 0))
# TODO(ccolby): De-dupe all_centers?
a = state_ops.assign(
self._cluster_centers, all_centers, validate_shape=False)
if self._cluster_centers_updated is not self._cluster_centers:
a = state_ops.assign(
self._cluster_centers_updated, a, validate_shape=False)
return self._num_clusters - array_ops.shape(a)[0] | [
"def",
"_add_new_centers",
"(",
"self",
")",
":",
"new_centers",
"=",
"self",
".",
"_choose_initial_centers",
"(",
")",
"if",
"self",
".",
"_distance_metric",
"==",
"COSINE_DISTANCE",
":",
"new_centers",
"=",
"nn_impl",
".",
"l2_normalize",
"(",
"new_centers",
",",
"dim",
"=",
"1",
")",
"# If cluster_centers is empty, it doesn't have the right shape for concat.",
"all_centers",
"=",
"control_flow_ops",
".",
"cond",
"(",
"math_ops",
".",
"equal",
"(",
"self",
".",
"_num_selected",
",",
"0",
")",
",",
"lambda",
":",
"new_centers",
",",
"lambda",
":",
"array_ops",
".",
"concat",
"(",
"[",
"self",
".",
"_cluster_centers",
",",
"new_centers",
"]",
",",
"0",
")",
")",
"# TODO(ccolby): De-dupe all_centers?",
"a",
"=",
"state_ops",
".",
"assign",
"(",
"self",
".",
"_cluster_centers",
",",
"all_centers",
",",
"validate_shape",
"=",
"False",
")",
"if",
"self",
".",
"_cluster_centers_updated",
"is",
"not",
"self",
".",
"_cluster_centers",
":",
"a",
"=",
"state_ops",
".",
"assign",
"(",
"self",
".",
"_cluster_centers_updated",
",",
"a",
",",
"validate_shape",
"=",
"False",
")",
"return",
"self",
".",
"_num_clusters",
"-",
"array_ops",
".",
"shape",
"(",
"a",
")",
"[",
"0",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/clustering_ops.py#L735-L750 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html.py | python | HtmlCell.Layout | (*args, **kwargs) | return _html.HtmlCell_Layout(*args, **kwargs) | Layout(self, int w) | Layout(self, int w) | [
"Layout",
"(",
"self",
"int",
"w",
")"
] | def Layout(*args, **kwargs):
"""Layout(self, int w)"""
return _html.HtmlCell_Layout(*args, **kwargs) | [
"def",
"Layout",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlCell_Layout",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L682-L684 | |
KhronosGroup/Vulkan-Headers | b32da5329b50e3cb96229aaecba9ded032fe29cc | registry/spec_tools/util.py | python | findFirstWithPredicate | (collection, pred) | return None | Return the first element that satisfies the predicate, or None if none exist.
NOTE: Some places where this is used might be better served by changing to a dictionary. | Return the first element that satisfies the predicate, or None if none exist. | [
"Return",
"the",
"first",
"element",
"that",
"satisfies",
"the",
"predicate",
"or",
"None",
"if",
"none",
"exist",
"."
] | def findFirstWithPredicate(collection, pred):
"""Return the first element that satisfies the predicate, or None if none exist.
NOTE: Some places where this is used might be better served by changing to a dictionary.
"""
for elt in collection:
if pred(elt):
return elt
return None | [
"def",
"findFirstWithPredicate",
"(",
"collection",
",",
"pred",
")",
":",
"for",
"elt",
"in",
"collection",
":",
"if",
"pred",
"(",
"elt",
")",
":",
"return",
"elt",
"return",
"None"
] | https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/spec_tools/util.py#L26-L34 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/pickle.py | python | Unpickler.load | (self) | Read a pickled object representation from the open file.
Return the reconstituted object hierarchy specified in the file. | Read a pickled object representation from the open file. | [
"Read",
"a",
"pickled",
"object",
"representation",
"from",
"the",
"open",
"file",
"."
] | def load(self):
"""Read a pickled object representation from the open file.
Return the reconstituted object hierarchy specified in the file.
"""
self.mark = object() # any new unique object
self.stack = []
self.append = self.stack.append
read = self.read
dispatch = self.dispatch
try:
while 1:
key = read(1)
dispatch[key](self)
except _Stop, stopinst:
return stopinst.value | [
"def",
"load",
"(",
"self",
")",
":",
"self",
".",
"mark",
"=",
"object",
"(",
")",
"# any new unique object",
"self",
".",
"stack",
"=",
"[",
"]",
"self",
".",
"append",
"=",
"self",
".",
"stack",
".",
"append",
"read",
"=",
"self",
".",
"read",
"dispatch",
"=",
"self",
".",
"dispatch",
"try",
":",
"while",
"1",
":",
"key",
"=",
"read",
"(",
"1",
")",
"dispatch",
"[",
"key",
"]",
"(",
"self",
")",
"except",
"_Stop",
",",
"stopinst",
":",
"return",
"stopinst",
".",
"value"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pickle.py#L845-L860 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/elementwise/log.py | python | log.is_atom_concave | (self) | return True | Is the atom concave? | Is the atom concave? | [
"Is",
"the",
"atom",
"concave?"
] | def is_atom_concave(self) -> bool:
"""Is the atom concave?
"""
return True | [
"def",
"is_atom_concave",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/log.py#L48-L51 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/universe_generation/galaxy.py | python | AdjacencyGrid.nearest_neighbor | (self, p) | return None | Return nearest neighbor at any distance. | Return nearest neighbor at any distance. | [
"Return",
"nearest",
"neighbor",
"at",
"any",
"distance",
"."
] | def nearest_neighbor(self, p):
"""Return nearest neighbor at any distance."""
for ring in self._generate_rings_around_point(p):
candidates = [pos for cell in ring for pos in self.grid[cell]]
if candidates:
(_, pt) = min((util.distance(pos, p), pos) for pos in candidates)
return pt
return None | [
"def",
"nearest_neighbor",
"(",
"self",
",",
"p",
")",
":",
"for",
"ring",
"in",
"self",
".",
"_generate_rings_around_point",
"(",
"p",
")",
":",
"candidates",
"=",
"[",
"pos",
"for",
"cell",
"in",
"ring",
"for",
"pos",
"in",
"self",
".",
"grid",
"[",
"cell",
"]",
"]",
"if",
"candidates",
":",
"(",
"_",
",",
"pt",
")",
"=",
"min",
"(",
"(",
"util",
".",
"distance",
"(",
"pos",
",",
"p",
")",
",",
"pos",
")",
"for",
"pos",
"in",
"candidates",
")",
"return",
"pt",
"return",
"None"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/universe_generation/galaxy.py#L74-L81 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Menu.unpost | (self) | Unmap a menu. | Unmap a menu. | [
"Unmap",
"a",
"menu",
"."
] | def unpost(self):
"""Unmap a menu."""
self.tk.call(self._w, 'unpost') | [
"def",
"unpost",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'unpost'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2746-L2748 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/CoSimulationApplication/python_scripts/utilities/model_part_utilities.py | python | CreateModelPartsFromCouplingDataSettings | (data_settings_list, model, solver_name) | This function creates the ModelParts-hierarchie that are used in the specified CouplingInterfaceData-settings | This function creates the ModelParts-hierarchie that are used in the specified CouplingInterfaceData-settings | [
"This",
"function",
"creates",
"the",
"ModelParts",
"-",
"hierarchie",
"that",
"are",
"used",
"in",
"the",
"specified",
"CouplingInterfaceData",
"-",
"settings"
] | def CreateModelPartsFromCouplingDataSettings(data_settings_list, model, solver_name):
'''This function creates the ModelParts-hierarchie that are used in the specified CouplingInterfaceData-settings'''
data_settings_list = data_settings_list.Clone() # clone to not mess with the following validation
for data_settings in data_settings_list.values():
CouplingInterfaceData.GetDefaultParameters()
data_settings.ValidateAndAssignDefaults(CouplingInterfaceData.GetDefaultParameters())
splitted_name = data_settings["model_part_name"].GetString().split(".")
main_model_part_name = splitted_name[0]
sub_model_part_names = splitted_name[1:]
if model.HasModelPart(main_model_part_name):
main_model_part = model.GetModelPart(main_model_part_name)
else:
main_model_part = model.CreateModelPart(main_model_part_name)
cs_print_info("CoSimTools", 'Created ModelPart "{}" for solver "{}"'.format(main_model_part_name, solver_name))
if len(sub_model_part_names) > 0:
RecursiveCreateModelParts(main_model_part, ".".join(sub_model_part_names)) | [
"def",
"CreateModelPartsFromCouplingDataSettings",
"(",
"data_settings_list",
",",
"model",
",",
"solver_name",
")",
":",
"data_settings_list",
"=",
"data_settings_list",
".",
"Clone",
"(",
")",
"# clone to not mess with the following validation",
"for",
"data_settings",
"in",
"data_settings_list",
".",
"values",
"(",
")",
":",
"CouplingInterfaceData",
".",
"GetDefaultParameters",
"(",
")",
"data_settings",
".",
"ValidateAndAssignDefaults",
"(",
"CouplingInterfaceData",
".",
"GetDefaultParameters",
"(",
")",
")",
"splitted_name",
"=",
"data_settings",
"[",
"\"model_part_name\"",
"]",
".",
"GetString",
"(",
")",
".",
"split",
"(",
"\".\"",
")",
"main_model_part_name",
"=",
"splitted_name",
"[",
"0",
"]",
"sub_model_part_names",
"=",
"splitted_name",
"[",
"1",
":",
"]",
"if",
"model",
".",
"HasModelPart",
"(",
"main_model_part_name",
")",
":",
"main_model_part",
"=",
"model",
".",
"GetModelPart",
"(",
"main_model_part_name",
")",
"else",
":",
"main_model_part",
"=",
"model",
".",
"CreateModelPart",
"(",
"main_model_part_name",
")",
"cs_print_info",
"(",
"\"CoSimTools\"",
",",
"'Created ModelPart \"{}\" for solver \"{}\"'",
".",
"format",
"(",
"main_model_part_name",
",",
"solver_name",
")",
")",
"if",
"len",
"(",
"sub_model_part_names",
")",
">",
"0",
":",
"RecursiveCreateModelParts",
"(",
"main_model_part",
",",
"\".\"",
".",
"join",
"(",
"sub_model_part_names",
")",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/CoSimulationApplication/python_scripts/utilities/model_part_utilities.py#L55-L72 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/numpy/_op.py | python | argmax | (a, axis=None, out=None, keepdims=False) | return _api_internal.argmax(a, axis, keepdims, out) | r"""
Returns the indices of the maximum values along an axis.
Parameters
----------
a : ndarray
Input array. Only support ndarrays of dtype `float16`, `float32`, and `float64`.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
keepdims : bool
If True, the reduced axes (dimensions) must be included in the result as
singleton dimensions, and, accordingly, the result must be compatible with
the input array. Otherwise, if False, the reduced axes (dimensions) must
not be included in the result. Default: False .
Returns
-------
index_array : ndarray of indices whose dtype is same as the input ndarray.
Array of indices into the array. It has the same shape as `a.shape`
with the dimension along `axis` removed.
Notes
-----
``keepdims`` param is part of request in data-api-standard
<https://data-apis.org/array-api/latest/API_specification/generated/signatures.searching_functions.argmax.html>`_,
which is not the parameter in official NumPy
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
This function differs from the original `numpy.argmax
<https://numpy.org/doc/stable/reference/generated/numpy.argmax.html>`_ in
the following aspects:
- Input type does not support Python native iterables(list, tuple, ...).
- ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
Examples
--------
>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10., 11., 12.],
[13., 14., 15.]])
>>> np.argmax(a)
array(5.)
>>> np.argmax(a, axis=0)
array([1., 1., 1.])
>>> np.argmax(a, axis=1)
array([2., 2.])
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0., 5., 2., 3., 4., 5.])
>>> np.argmax(b) # Only the first occurrence is returned.
array(1.)
Specify ``out`` ndarray:
>>> a = np.arange(6).reshape(2,3) + 10
>>> b = np.zeros((2,))
>>> np.argmax(a, axis=1, out=b)
array([2., 2.])
>>> b
array([2., 2.]) | r"""
Returns the indices of the maximum values along an axis. | [
"r",
"Returns",
"the",
"indices",
"of",
"the",
"maximum",
"values",
"along",
"an",
"axis",
"."
] | def argmax(a, axis=None, out=None, keepdims=False):
r"""
Returns the indices of the maximum values along an axis.
Parameters
----------
a : ndarray
Input array. Only support ndarrays of dtype `float16`, `float32`, and `float64`.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : ndarray or None, optional
A location into which the result is stored.
If provided, it must have the same shape and dtype as input ndarray.
If not provided or `None`, a freshly-allocated array is returned.
keepdims : bool
If True, the reduced axes (dimensions) must be included in the result as
singleton dimensions, and, accordingly, the result must be compatible with
the input array. Otherwise, if False, the reduced axes (dimensions) must
not be included in the result. Default: False .
Returns
-------
index_array : ndarray of indices whose dtype is same as the input ndarray.
Array of indices into the array. It has the same shape as `a.shape`
with the dimension along `axis` removed.
Notes
-----
``keepdims`` param is part of request in data-api-standard
<https://data-apis.org/array-api/latest/API_specification/generated/signatures.searching_functions.argmax.html>`_,
which is not the parameter in official NumPy
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
This function differs from the original `numpy.argmax
<https://numpy.org/doc/stable/reference/generated/numpy.argmax.html>`_ in
the following aspects:
- Input type does not support Python native iterables(list, tuple, ...).
- ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
Examples
--------
>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10., 11., 12.],
[13., 14., 15.]])
>>> np.argmax(a)
array(5.)
>>> np.argmax(a, axis=0)
array([1., 1., 1.])
>>> np.argmax(a, axis=1)
array([2., 2.])
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0., 5., 2., 3., 4., 5.])
>>> np.argmax(b) # Only the first occurrence is returned.
array(1.)
Specify ``out`` ndarray:
>>> a = np.arange(6).reshape(2,3) + 10
>>> b = np.zeros((2,))
>>> np.argmax(a, axis=1, out=b)
array([2., 2.])
>>> b
array([2., 2.])
"""
return _api_internal.argmax(a, axis, keepdims, out) | [
"def",
"argmax",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"out",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"return",
"_api_internal",
".",
"argmax",
"(",
"a",
",",
"axis",
",",
"keepdims",
",",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L5447-L5521 | |
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/SU2/io/state.py | python | State.find_files | (self,config) | return | SU2.io.State.find_files(config)
finds mesh and solution files for a given config.
updates state.FILES with filenames.
files already logged in state are not overridden.
will ignore solutions if config.RESTART_SOL == 'NO'. | SU2.io.State.find_files(config)
finds mesh and solution files for a given config.
updates state.FILES with filenames.
files already logged in state are not overridden.
will ignore solutions if config.RESTART_SOL == 'NO'. | [
"SU2",
".",
"io",
".",
"State",
".",
"find_files",
"(",
"config",
")",
"finds",
"mesh",
"and",
"solution",
"files",
"for",
"a",
"given",
"config",
".",
"updates",
"state",
".",
"FILES",
"with",
"filenames",
".",
"files",
"already",
"logged",
"in",
"state",
"are",
"not",
"overridden",
".",
"will",
"ignore",
"solutions",
"if",
"config",
".",
"RESTART_SOL",
"==",
"NO",
"."
] | def find_files(self,config):
""" SU2.io.State.find_files(config)
finds mesh and solution files for a given config.
updates state.FILES with filenames.
files already logged in state are not overridden.
will ignore solutions if config.RESTART_SOL == 'NO'.
"""
files = self.FILES
mesh_name = config.MESH_FILENAME
if config.get('READ_BINARY_RESTART', 'YES') == 'NO':
if not 'RESTART_ASCII' in config.get('OUTPUT_FILES',['RESTART']):
print ('RESTART_ASCII must be in OUTPUT_FILES if READ_BINARY_RESTART is set to NO')
sys.exit()
direct_name = config.SOLUTION_FILENAME
adjoint_name = config.SOLUTION_ADJ_FILENAME
if 'RESTART_ASCII' in config.get('OUTPUT_FILES', ['RESTART']):
direct_name = direct_name.split('.')[0] + '.csv'
adjoint_name = adjoint_name.split('.')[0] + '.csv'
else:
direct_name = direct_name.split('.')[0] + '.dat'
adjoint_name = adjoint_name.split('.')[0] + '.dat'
targetea_name = 'TargetEA.dat'
targetcp_name = 'TargetCp.dat'
targetheatflux_name = 'TargetHeatFlux.dat'
adj_map = get_adjointSuffix()
restart = config.RESTART_SOL == 'YES'
special_cases = get_specialCases(config)
if config.get('OPT_OBJECTIVE'):
def_objs = config['OPT_OBJECTIVE']
objectives = def_objs.keys()
multipoint = any(elem in optnames_multi for elem in objectives)
else:
multipoint = False
def register_file(label,filename):
if not label in files:
if label.split('_')[0] in ['DIRECT', 'ADJOINT']:
names = expand_zones(filename, config)
found = False
for name in names:
if os.path.exists(name):
found = True
else:
found = False
break
if found:
files[label] = filename
print('Found: %s' % filename)
elif label.split('_')[0] in ['MULTIPOINT']:
# if multipoint, list of files needs to be added
file_list= [];
for name in filename:
if os.path.exists(name):
file_list.append(name)
print('Found: %s' % name)
else:
# if file doesn't exist, enter empty string as placeholder
file_list.append('')
# If even one of the multipoint files is found, add the list
if any(file for file in file_list):
files[label] = file_list
else:
if os.path.exists(filename):
files[label] = filename
print('Found: %s' % filename)
else:
if label.split("_")[0] in ['DIRECT', 'ADJOINT']:
for name in expand_zones(files[label], config):
assert os.path.exists(name), 'state expected file: %s' % filename
elif label.split('_')[0] in ['MULTIPOINT']:
for name in expand_zones(files[label], config):
if name:
if not os.path.exists(name):
raise AssertionError('state expected file: %s' % name)
else:
assert os.path.exists(files[label]) , 'state expected file: %s' % filename
#: register_file()
# mesh
if multipoint:
mesh_list = [elem.strip() for elem in config['MULTIPOINT_MESH_FILENAME'].replace("(", "").replace(")", "").split(',')]
if len(set(mesh_list)) > 1:
# Only register MULTIPOINT_MESH_FILENAME if multiple meshes are specified
register_file('MULTIPOINT_MESH_FILENAME', mesh_list)
mesh_name = mesh_list[0]
register_file('MESH',mesh_name)
# old style restart
if not 'RESTART_FILE_1' in files.keys():
# direct solutions
if restart:
register_file('DIRECT',direct_name)
if multipoint:
name_list = expand_multipoint(direct_name,config)
name_list = expand_zones(name_list,config)
register_file('MULTIPOINT_DIRECT',name_list)
# flow meta data file
if restart:
register_file('FLOW_META','flow.meta')
if multipoint:
name_list = expand_multipoint('flow.meta',config)
register_file('MULTIPOINT_FLOW_META',name_list)
# adjoint solutions
if restart:
for obj, suff in adj_map.items():
ADJ_LABEL = 'ADJOINT_' + obj
adjoint_name_suffixed = add_suffix(adjoint_name,suff)
register_file(ADJ_LABEL,adjoint_name_suffixed)
if multipoint:
name_list = expand_zones(add_suffix(expand_multipoint(adjoint_name,config), suff), config)
multipoint_adj_name = 'MULTIPOINT_' + ADJ_LABEL
register_file(multipoint_adj_name, name_list)
# equivalent area
if 'EQUIV_AREA' in special_cases:
register_file('TARGET_EA',targetea_name)
# pressure inverse design
if 'INV_DESIGN_CP' in special_cases:
register_file('TARGET_CP',targetcp_name)
# heat flux inverse design
if 'INV_DESIGN_HEATFLUX' in special_cases:
register_file('TARGET_HEATFLUX',targetheatflux_name)
return | [
"def",
"find_files",
"(",
"self",
",",
"config",
")",
":",
"files",
"=",
"self",
".",
"FILES",
"mesh_name",
"=",
"config",
".",
"MESH_FILENAME",
"if",
"config",
".",
"get",
"(",
"'READ_BINARY_RESTART'",
",",
"'YES'",
")",
"==",
"'NO'",
":",
"if",
"not",
"'RESTART_ASCII'",
"in",
"config",
".",
"get",
"(",
"'OUTPUT_FILES'",
",",
"[",
"'RESTART'",
"]",
")",
":",
"print",
"(",
"'RESTART_ASCII must be in OUTPUT_FILES if READ_BINARY_RESTART is set to NO'",
")",
"sys",
".",
"exit",
"(",
")",
"direct_name",
"=",
"config",
".",
"SOLUTION_FILENAME",
"adjoint_name",
"=",
"config",
".",
"SOLUTION_ADJ_FILENAME",
"if",
"'RESTART_ASCII'",
"in",
"config",
".",
"get",
"(",
"'OUTPUT_FILES'",
",",
"[",
"'RESTART'",
"]",
")",
":",
"direct_name",
"=",
"direct_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'.csv'",
"adjoint_name",
"=",
"adjoint_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'.csv'",
"else",
":",
"direct_name",
"=",
"direct_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'.dat'",
"adjoint_name",
"=",
"adjoint_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'.dat'",
"targetea_name",
"=",
"'TargetEA.dat'",
"targetcp_name",
"=",
"'TargetCp.dat'",
"targetheatflux_name",
"=",
"'TargetHeatFlux.dat'",
"adj_map",
"=",
"get_adjointSuffix",
"(",
")",
"restart",
"=",
"config",
".",
"RESTART_SOL",
"==",
"'YES'",
"special_cases",
"=",
"get_specialCases",
"(",
"config",
")",
"if",
"config",
".",
"get",
"(",
"'OPT_OBJECTIVE'",
")",
":",
"def_objs",
"=",
"config",
"[",
"'OPT_OBJECTIVE'",
"]",
"objectives",
"=",
"def_objs",
".",
"keys",
"(",
")",
"multipoint",
"=",
"any",
"(",
"elem",
"in",
"optnames_multi",
"for",
"elem",
"in",
"objectives",
")",
"else",
":",
"multipoint",
"=",
"False",
"def",
"register_file",
"(",
"label",
",",
"filename",
")",
":",
"if",
"not",
"label",
"in",
"files",
":",
"if",
"label",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"in",
"[",
"'DIRECT'",
",",
"'ADJOINT'",
"]",
":",
"names",
"=",
"expand_zones",
"(",
"filename",
",",
"config",
")",
"found",
"=",
"False",
"for",
"name",
"in",
"names",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"found",
"=",
"True",
"else",
":",
"found",
"=",
"False",
"break",
"if",
"found",
":",
"files",
"[",
"label",
"]",
"=",
"filename",
"print",
"(",
"'Found: %s'",
"%",
"filename",
")",
"elif",
"label",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"in",
"[",
"'MULTIPOINT'",
"]",
":",
"# if multipoint, list of files needs to be added",
"file_list",
"=",
"[",
"]",
"for",
"name",
"in",
"filename",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"file_list",
".",
"append",
"(",
"name",
")",
"print",
"(",
"'Found: %s'",
"%",
"name",
")",
"else",
":",
"# if file doesn't exist, enter empty string as placeholder",
"file_list",
".",
"append",
"(",
"''",
")",
"# If even one of the multipoint files is found, add the list",
"if",
"any",
"(",
"file",
"for",
"file",
"in",
"file_list",
")",
":",
"files",
"[",
"label",
"]",
"=",
"file_list",
"else",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"files",
"[",
"label",
"]",
"=",
"filename",
"print",
"(",
"'Found: %s'",
"%",
"filename",
")",
"else",
":",
"if",
"label",
".",
"split",
"(",
"\"_\"",
")",
"[",
"0",
"]",
"in",
"[",
"'DIRECT'",
",",
"'ADJOINT'",
"]",
":",
"for",
"name",
"in",
"expand_zones",
"(",
"files",
"[",
"label",
"]",
",",
"config",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
",",
"'state expected file: %s'",
"%",
"filename",
"elif",
"label",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"in",
"[",
"'MULTIPOINT'",
"]",
":",
"for",
"name",
"in",
"expand_zones",
"(",
"files",
"[",
"label",
"]",
",",
"config",
")",
":",
"if",
"name",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"raise",
"AssertionError",
"(",
"'state expected file: %s'",
"%",
"name",
")",
"else",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"files",
"[",
"label",
"]",
")",
",",
"'state expected file: %s'",
"%",
"filename",
"#: register_file() ",
"# mesh",
"if",
"multipoint",
":",
"mesh_list",
"=",
"[",
"elem",
".",
"strip",
"(",
")",
"for",
"elem",
"in",
"config",
"[",
"'MULTIPOINT_MESH_FILENAME'",
"]",
".",
"replace",
"(",
"\"(\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\")\"",
",",
"\"\"",
")",
".",
"split",
"(",
"','",
")",
"]",
"if",
"len",
"(",
"set",
"(",
"mesh_list",
")",
")",
">",
"1",
":",
"# Only register MULTIPOINT_MESH_FILENAME if multiple meshes are specified",
"register_file",
"(",
"'MULTIPOINT_MESH_FILENAME'",
",",
"mesh_list",
")",
"mesh_name",
"=",
"mesh_list",
"[",
"0",
"]",
"register_file",
"(",
"'MESH'",
",",
"mesh_name",
")",
"# old style restart",
"if",
"not",
"'RESTART_FILE_1'",
"in",
"files",
".",
"keys",
"(",
")",
":",
"# direct solutions",
"if",
"restart",
":",
"register_file",
"(",
"'DIRECT'",
",",
"direct_name",
")",
"if",
"multipoint",
":",
"name_list",
"=",
"expand_multipoint",
"(",
"direct_name",
",",
"config",
")",
"name_list",
"=",
"expand_zones",
"(",
"name_list",
",",
"config",
")",
"register_file",
"(",
"'MULTIPOINT_DIRECT'",
",",
"name_list",
")",
"# flow meta data file",
"if",
"restart",
":",
"register_file",
"(",
"'FLOW_META'",
",",
"'flow.meta'",
")",
"if",
"multipoint",
":",
"name_list",
"=",
"expand_multipoint",
"(",
"'flow.meta'",
",",
"config",
")",
"register_file",
"(",
"'MULTIPOINT_FLOW_META'",
",",
"name_list",
")",
"# adjoint solutions",
"if",
"restart",
":",
"for",
"obj",
",",
"suff",
"in",
"adj_map",
".",
"items",
"(",
")",
":",
"ADJ_LABEL",
"=",
"'ADJOINT_'",
"+",
"obj",
"adjoint_name_suffixed",
"=",
"add_suffix",
"(",
"adjoint_name",
",",
"suff",
")",
"register_file",
"(",
"ADJ_LABEL",
",",
"adjoint_name_suffixed",
")",
"if",
"multipoint",
":",
"name_list",
"=",
"expand_zones",
"(",
"add_suffix",
"(",
"expand_multipoint",
"(",
"adjoint_name",
",",
"config",
")",
",",
"suff",
")",
",",
"config",
")",
"multipoint_adj_name",
"=",
"'MULTIPOINT_'",
"+",
"ADJ_LABEL",
"register_file",
"(",
"multipoint_adj_name",
",",
"name_list",
")",
"# equivalent area",
"if",
"'EQUIV_AREA'",
"in",
"special_cases",
":",
"register_file",
"(",
"'TARGET_EA'",
",",
"targetea_name",
")",
"# pressure inverse design",
"if",
"'INV_DESIGN_CP'",
"in",
"special_cases",
":",
"register_file",
"(",
"'TARGET_CP'",
",",
"targetcp_name",
")",
"# heat flux inverse design",
"if",
"'INV_DESIGN_HEATFLUX'",
"in",
"special_cases",
":",
"register_file",
"(",
"'TARGET_HEATFLUX'",
",",
"targetheatflux_name",
")",
"return"
] | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/io/state.py#L232-L369 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/internetcontent/nv_python_libs/vimeo/oauth/oauth_api.py | python | OAuthServer.fetch_access_token | (self, oauth_request) | return new_token | Processes an access_token request and returns the
access token on success. | Processes an access_token request and returns the
access token on success. | [
"Processes",
"an",
"access_token",
"request",
"and",
"returns",
"the",
"access",
"token",
"on",
"success",
"."
] | def fetch_access_token(self, oauth_request):
"""Processes an access_token request and returns the
access token on success.
"""
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
verifier = self._get_verifier(oauth_request)
except OAuthError:
verifier = None
# Get the request token.
token = self._get_token(oauth_request, 'request')
self._check_signature(oauth_request, consumer, token)
new_token = self.data_store.fetch_access_token(consumer, token, verifier)
return new_token | [
"def",
"fetch_access_token",
"(",
"self",
",",
"oauth_request",
")",
":",
"version",
"=",
"self",
".",
"_get_version",
"(",
"oauth_request",
")",
"consumer",
"=",
"self",
".",
"_get_consumer",
"(",
"oauth_request",
")",
"try",
":",
"verifier",
"=",
"self",
".",
"_get_verifier",
"(",
"oauth_request",
")",
"except",
"OAuthError",
":",
"verifier",
"=",
"None",
"# Get the request token.",
"token",
"=",
"self",
".",
"_get_token",
"(",
"oauth_request",
",",
"'request'",
")",
"self",
".",
"_check_signature",
"(",
"oauth_request",
",",
"consumer",
",",
"token",
")",
"new_token",
"=",
"self",
".",
"data_store",
".",
"fetch_access_token",
"(",
"consumer",
",",
"token",
",",
"verifier",
")",
"return",
"new_token"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/vimeo/oauth/oauth_api.py#L409-L423 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/build/android/pylib/device_stats_monitor.py | python | DeviceStatsMonitor.StopAndCollect | (self, output_path) | return 'file://%s?results=file://%s' % (
DeviceStatsMonitor.RESULT_VIEWER_PATH, urllib.quote(output_path)) | Stops monitoring and saves results.
Args:
output_path: Path to save results.
Returns:
String of URL to load results in browser. | Stops monitoring and saves results. | [
"Stops",
"monitoring",
"and",
"saves",
"results",
"."
] | def StopAndCollect(self, output_path):
"""Stops monitoring and saves results.
Args:
output_path: Path to save results.
Returns:
String of URL to load results in browser.
"""
assert self._process
self._adb.KillAll(DeviceStatsMonitor.DEVICE_PATH)
self._process.wait()
profile = self._adb.GetFileContents(DeviceStatsMonitor.PROFILE_PATH)
results = collections.defaultdict(list)
last_io_stats = None
last_cpu_stats = None
for line in profile:
if ' mmcblk0 ' in line:
stats = io_stats_parser.ParseIoStatsLine(line)
if last_io_stats:
results['sectors_read'].append(stats.num_sectors_read -
last_io_stats.num_sectors_read)
results['sectors_written'].append(stats.num_sectors_written -
last_io_stats.num_sectors_written)
last_io_stats = stats
elif line.startswith('cpu '):
stats = self._ParseCpuStatsLine(line)
if last_cpu_stats:
results['user'].append(stats.user - last_cpu_stats.user)
results['nice'].append(stats.nice - last_cpu_stats.nice)
results['system'].append(stats.system - last_cpu_stats.system)
results['idle'].append(stats.idle - last_cpu_stats.idle)
results['iowait'].append(stats.iowait - last_cpu_stats.iowait)
results['irq'].append(stats.irq - last_cpu_stats.irq)
results['softirq'].append(stats.softirq- last_cpu_stats.softirq)
last_cpu_stats = stats
units = {
'sectors_read': 'sectors',
'sectors_written': 'sectors',
'user': 'jiffies',
'nice': 'jiffies',
'system': 'jiffies',
'idle': 'jiffies',
'iowait': 'jiffies',
'irq': 'jiffies',
'softirq': 'jiffies',
}
with open(output_path, 'w') as f:
f.write('display(%d, %s, %s);' % (self._hz, json.dumps(results), units))
return 'file://%s?results=file://%s' % (
DeviceStatsMonitor.RESULT_VIEWER_PATH, urllib.quote(output_path)) | [
"def",
"StopAndCollect",
"(",
"self",
",",
"output_path",
")",
":",
"assert",
"self",
".",
"_process",
"self",
".",
"_adb",
".",
"KillAll",
"(",
"DeviceStatsMonitor",
".",
"DEVICE_PATH",
")",
"self",
".",
"_process",
".",
"wait",
"(",
")",
"profile",
"=",
"self",
".",
"_adb",
".",
"GetFileContents",
"(",
"DeviceStatsMonitor",
".",
"PROFILE_PATH",
")",
"results",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"last_io_stats",
"=",
"None",
"last_cpu_stats",
"=",
"None",
"for",
"line",
"in",
"profile",
":",
"if",
"' mmcblk0 '",
"in",
"line",
":",
"stats",
"=",
"io_stats_parser",
".",
"ParseIoStatsLine",
"(",
"line",
")",
"if",
"last_io_stats",
":",
"results",
"[",
"'sectors_read'",
"]",
".",
"append",
"(",
"stats",
".",
"num_sectors_read",
"-",
"last_io_stats",
".",
"num_sectors_read",
")",
"results",
"[",
"'sectors_written'",
"]",
".",
"append",
"(",
"stats",
".",
"num_sectors_written",
"-",
"last_io_stats",
".",
"num_sectors_written",
")",
"last_io_stats",
"=",
"stats",
"elif",
"line",
".",
"startswith",
"(",
"'cpu '",
")",
":",
"stats",
"=",
"self",
".",
"_ParseCpuStatsLine",
"(",
"line",
")",
"if",
"last_cpu_stats",
":",
"results",
"[",
"'user'",
"]",
".",
"append",
"(",
"stats",
".",
"user",
"-",
"last_cpu_stats",
".",
"user",
")",
"results",
"[",
"'nice'",
"]",
".",
"append",
"(",
"stats",
".",
"nice",
"-",
"last_cpu_stats",
".",
"nice",
")",
"results",
"[",
"'system'",
"]",
".",
"append",
"(",
"stats",
".",
"system",
"-",
"last_cpu_stats",
".",
"system",
")",
"results",
"[",
"'idle'",
"]",
".",
"append",
"(",
"stats",
".",
"idle",
"-",
"last_cpu_stats",
".",
"idle",
")",
"results",
"[",
"'iowait'",
"]",
".",
"append",
"(",
"stats",
".",
"iowait",
"-",
"last_cpu_stats",
".",
"iowait",
")",
"results",
"[",
"'irq'",
"]",
".",
"append",
"(",
"stats",
".",
"irq",
"-",
"last_cpu_stats",
".",
"irq",
")",
"results",
"[",
"'softirq'",
"]",
".",
"append",
"(",
"stats",
".",
"softirq",
"-",
"last_cpu_stats",
".",
"softirq",
")",
"last_cpu_stats",
"=",
"stats",
"units",
"=",
"{",
"'sectors_read'",
":",
"'sectors'",
",",
"'sectors_written'",
":",
"'sectors'",
",",
"'user'",
":",
"'jiffies'",
",",
"'nice'",
":",
"'jiffies'",
",",
"'system'",
":",
"'jiffies'",
",",
"'idle'",
":",
"'jiffies'",
",",
"'iowait'",
":",
"'jiffies'",
",",
"'irq'",
":",
"'jiffies'",
",",
"'softirq'",
":",
"'jiffies'",
",",
"}",
"with",
"open",
"(",
"output_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'display(%d, %s, %s);'",
"%",
"(",
"self",
".",
"_hz",
",",
"json",
".",
"dumps",
"(",
"results",
")",
",",
"units",
")",
")",
"return",
"'file://%s?results=file://%s'",
"%",
"(",
"DeviceStatsMonitor",
".",
"RESULT_VIEWER_PATH",
",",
"urllib",
".",
"quote",
"(",
"output_path",
")",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/pylib/device_stats_monitor.py#L47-L98 | |
alexozer/jankdrone | c4b403eb254b41b832ab2bdfade12ba59c99e5dc | shm/lib/nanopb/generator/nanopb_generator.py | python | iterate_extensions | (desc, names = Names()) | Recursively find all extensions.
For each, yield name, FieldDescriptorProto. | Recursively find all extensions.
For each, yield name, FieldDescriptorProto. | [
"Recursively",
"find",
"all",
"extensions",
".",
"For",
"each",
"yield",
"name",
"FieldDescriptorProto",
"."
] | def iterate_extensions(desc, names = Names()):
'''Recursively find all extensions.
For each, yield name, FieldDescriptorProto.
'''
for extension in desc.extension:
yield names, extension
for subname, subdesc in iterate_messages(desc, names):
for extension in subdesc.extension:
yield subname, extension | [
"def",
"iterate_extensions",
"(",
"desc",
",",
"names",
"=",
"Names",
"(",
")",
")",
":",
"for",
"extension",
"in",
"desc",
".",
"extension",
":",
"yield",
"names",
",",
"extension",
"for",
"subname",
",",
"subdesc",
"in",
"iterate_messages",
"(",
"desc",
",",
"names",
")",
":",
"for",
"extension",
"in",
"subdesc",
".",
"extension",
":",
"yield",
"subname",
",",
"extension"
] | https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/shm/lib/nanopb/generator/nanopb_generator.py#L947-L956 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/vis/visualization.py | python | VisAppearance.transparent | (self) | Returns true if the item is entirely transparent, None if mixed transparency, and False otherwise | Returns true if the item is entirely transparent, None if mixed transparency, and False otherwise | [
"Returns",
"true",
"if",
"the",
"item",
"is",
"entirely",
"transparent",
"None",
"if",
"mixed",
"transparency",
"and",
"False",
"otherwise"
] | def transparent(self):
"""Returns true if the item is entirely transparent, None if mixed transparency, and False otherwise"""
if len(self.subAppearances)!=0:
anyTransp = False
anyOpaque = False
for n,app in self.subAppearances.iteritems():
if app.transparent():
anyTransp = True
else:
anyOpaque = True
if anyTransp and anyOpaque:
return None
else:
return anyTransp
if hasattr(self.item,'appearance'):
if self.useDefaultAppearance or 'color' not in self.attributes:
if isinstance(self.item,WorldModel):
#corner case: empty world
return False
else:
return self.item.appearance().getColor()[3] < 1.0
try:
return (self.attributes['color'][3] < 1.0)
except:
return False | [
"def",
"transparent",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"subAppearances",
")",
"!=",
"0",
":",
"anyTransp",
"=",
"False",
"anyOpaque",
"=",
"False",
"for",
"n",
",",
"app",
"in",
"self",
".",
"subAppearances",
".",
"iteritems",
"(",
")",
":",
"if",
"app",
".",
"transparent",
"(",
")",
":",
"anyTransp",
"=",
"True",
"else",
":",
"anyOpaque",
"=",
"True",
"if",
"anyTransp",
"and",
"anyOpaque",
":",
"return",
"None",
"else",
":",
"return",
"anyTransp",
"if",
"hasattr",
"(",
"self",
".",
"item",
",",
"'appearance'",
")",
":",
"if",
"self",
".",
"useDefaultAppearance",
"or",
"'color'",
"not",
"in",
"self",
".",
"attributes",
":",
"if",
"isinstance",
"(",
"self",
".",
"item",
",",
"WorldModel",
")",
":",
"#corner case: empty world",
"return",
"False",
"else",
":",
"return",
"self",
".",
"item",
".",
"appearance",
"(",
")",
".",
"getColor",
"(",
")",
"[",
"3",
"]",
"<",
"1.0",
"try",
":",
"return",
"(",
"self",
".",
"attributes",
"[",
"'color'",
"]",
"[",
"3",
"]",
"<",
"1.0",
")",
"except",
":",
"return",
"False"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/vis/visualization.py#L1914-L1938 | ||
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | support/cpplint.py | python | CleanseComments | (line) | return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed. | Removes //-comments and single-line C-style /* */ comments. | [
"Removes",
"//",
"-",
"comments",
"and",
"single",
"-",
"line",
"C",
"-",
"style",
"/",
"*",
"*",
"/",
"comments",
"."
] | def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | [
"def",
"CleanseComments",
"(",
"line",
")",
":",
"commentpos",
"=",
"line",
".",
"find",
"(",
"'//'",
")",
"if",
"commentpos",
"!=",
"-",
"1",
"and",
"not",
"IsCppString",
"(",
"line",
"[",
":",
"commentpos",
"]",
")",
":",
"line",
"=",
"line",
"[",
":",
"commentpos",
"]",
".",
"rstrip",
"(",
")",
"# get rid of /* ... */",
"return",
"_RE_PATTERN_CLEANSE_LINE_C_COMMENTS",
".",
"sub",
"(",
"''",
",",
"line",
")"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L1413-L1426 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/profiler/option_builder.py | python | ProfileOptionBuilder.with_file_output | (self, outfile) | return self | Print the result to a file. | Print the result to a file. | [
"Print",
"the",
"result",
"to",
"a",
"file",
"."
] | def with_file_output(self, outfile):
"""Print the result to a file."""
self._options['output'] = 'file:outfile=%s' % outfile
return self | [
"def",
"with_file_output",
"(",
"self",
",",
"outfile",
")",
":",
"self",
".",
"_options",
"[",
"'output'",
"]",
"=",
"'file:outfile=%s'",
"%",
"outfile",
"return",
"self"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/profiler/option_builder.py#L346-L349 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/mapmatching/wxgui.py | python | WxGui.on_select_mode | (self, event=None) | Select GPS traces of a specific mode.
The mode is selected only among the currently selected trips. | Select GPS traces of a specific mode.
The mode is selected only among the currently selected trips. | [
"Select",
"GPS",
"traces",
"of",
"a",
"specific",
"mode",
".",
"The",
"mode",
"is",
"selected",
"only",
"among",
"the",
"currently",
"selected",
"trips",
"."
] | def on_select_mode(self, event=None):
"""
Select GPS traces of a specific mode.
The mode is selected only among the currently selected trips.
"""
p = mapmatching.ModeSelector(self._mapmatching, logger=self._mainframe.get_logger())
dlg = ProcessDialog(self._mainframe, p, immediate_apply=True)
dlg.CenterOnScreen()
# this does not return until the dialog is closed.
val = dlg.ShowModal()
# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
# print ' status =',dlg.get_status()
if dlg.get_status() != 'success': # val == wx.ID_CANCEL:
# print ">>>>>>>>>Unsuccessful\n"
dlg.Destroy()
if dlg.get_status() == 'success':
# print ">>>>>>>>>successful\n"
# apply current widget values to scenario instance
dlg.apply()
dlg.Destroy()
self._mainframe.browse_obj(self._mapmatching.trips)
self._is_needs_refresh = True
self.refresh_widgets() | [
"def",
"on_select_mode",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"p",
"=",
"mapmatching",
".",
"ModeSelector",
"(",
"self",
".",
"_mapmatching",
",",
"logger",
"=",
"self",
".",
"_mainframe",
".",
"get_logger",
"(",
")",
")",
"dlg",
"=",
"ProcessDialog",
"(",
"self",
".",
"_mainframe",
",",
"p",
",",
"immediate_apply",
"=",
"True",
")",
"dlg",
".",
"CenterOnScreen",
"(",
")",
"# this does not return until the dialog is closed.",
"val",
"=",
"dlg",
".",
"ShowModal",
"(",
")",
"# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL",
"# print ' status =',dlg.get_status()",
"if",
"dlg",
".",
"get_status",
"(",
")",
"!=",
"'success'",
":",
"# val == wx.ID_CANCEL:",
"# print \">>>>>>>>>Unsuccessful\\n\"",
"dlg",
".",
"Destroy",
"(",
")",
"if",
"dlg",
".",
"get_status",
"(",
")",
"==",
"'success'",
":",
"# print \">>>>>>>>>successful\\n\"",
"# apply current widget values to scenario instance",
"dlg",
".",
"apply",
"(",
")",
"dlg",
".",
"Destroy",
"(",
")",
"self",
".",
"_mainframe",
".",
"browse_obj",
"(",
"self",
".",
"_mapmatching",
".",
"trips",
")",
"self",
".",
"_is_needs_refresh",
"=",
"True",
"self",
".",
"refresh_widgets",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/mapmatching/wxgui.py#L1201-L1226 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/find_change_points.py | python | _FindSplit | (values) | return min(range(1, len(values)), key=StdDevOfTwoNormalizedSides) | Finds the index of the "most interesting" split of a sample of data.
Currently, the most interesting split is considered to be the split that
minimizes the standard deviation of the two sides concatenated together
(after modifying both sides by shifting all the numbers in the left and
right sides by the median of the left and right sides respectively).
The reason why this is done is that normalizing the two segments on either
side of a point so that both have the same center essentially removes any
jump or step that occurs at that point.
Args:
values: A list of numbers.
Returns:
The index of the "most interesting" point. | Finds the index of the "most interesting" split of a sample of data. | [
"Finds",
"the",
"index",
"of",
"the",
"most",
"interesting",
"split",
"of",
"a",
"sample",
"of",
"data",
"."
] | def _FindSplit(values):
"""Finds the index of the "most interesting" split of a sample of data.
Currently, the most interesting split is considered to be the split that
minimizes the standard deviation of the two sides concatenated together
(after modifying both sides by shifting all the numbers in the left and
right sides by the median of the left and right sides respectively).
The reason why this is done is that normalizing the two segments on either
side of a point so that both have the same center essentially removes any
jump or step that occurs at that point.
Args:
values: A list of numbers.
Returns:
The index of the "most interesting" point.
"""
def StdDevOfTwoNormalizedSides(index):
left, right = values[:index], values[index:]
return math_utils.StandardDeviation(_ZeroMedian(left) + _ZeroMedian(right))
return min(range(1, len(values)), key=StdDevOfTwoNormalizedSides) | [
"def",
"_FindSplit",
"(",
"values",
")",
":",
"def",
"StdDevOfTwoNormalizedSides",
"(",
"index",
")",
":",
"left",
",",
"right",
"=",
"values",
"[",
":",
"index",
"]",
",",
"values",
"[",
"index",
":",
"]",
"return",
"math_utils",
".",
"StandardDeviation",
"(",
"_ZeroMedian",
"(",
"left",
")",
"+",
"_ZeroMedian",
"(",
"right",
")",
")",
"return",
"min",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"values",
")",
")",
",",
"key",
"=",
"StdDevOfTwoNormalizedSides",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/find_change_points.py#L148-L169 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Environment.add | (self, dist) | Add `dist` if we ``can_add()`` it and it has not already been added | Add `dist` if we ``can_add()`` it and it has not already been added | [
"Add",
"dist",
"if",
"we",
"can_add",
"()",
"it",
"and",
"it",
"has",
"not",
"already",
"been",
"added"
] | def add(self, dist):
"""Add `dist` if we ``can_add()`` it and it has not already been added
"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True) | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"self",
".",
"can_add",
"(",
"dist",
")",
"and",
"dist",
".",
"has_version",
"(",
")",
":",
"dists",
"=",
"self",
".",
"_distmap",
".",
"setdefault",
"(",
"dist",
".",
"key",
",",
"[",
"]",
")",
"if",
"dist",
"not",
"in",
"dists",
":",
"dists",
".",
"append",
"(",
"dist",
")",
"dists",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'hashcmp'",
")",
",",
"reverse",
"=",
"True",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L1034-L1041 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.MakeFromTimezone | (*args, **kwargs) | return _misc_.DateTime_MakeFromTimezone(*args, **kwargs) | MakeFromTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime | MakeFromTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime | [
"MakeFromTimezone",
"(",
"self",
"wxDateTime",
"::",
"TimeZone",
"tz",
"bool",
"noDST",
"=",
"False",
")",
"-",
">",
"DateTime"
] | def MakeFromTimezone(*args, **kwargs):
"""MakeFromTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime"""
return _misc_.DateTime_MakeFromTimezone(*args, **kwargs) | [
"def",
"MakeFromTimezone",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_MakeFromTimezone",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3934-L3936 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/xlsgrid.py | python | Excel.GetText | (self, row, col) | Returns the WYSIWYG text contained in a cell.
:param `row`: the row in which the cell lives;
:param `col`: the column in which the cell lives.
:note: The `row` and `col` parameters are not real Python index, as they
use the Excel indexing mode (i.e., first index is 1 and not 0). | Returns the WYSIWYG text contained in a cell. | [
"Returns",
"the",
"WYSIWYG",
"text",
"contained",
"in",
"a",
"cell",
"."
] | def GetText(self, row, col):
"""
Returns the WYSIWYG text contained in a cell.
:param `row`: the row in which the cell lives;
:param `col`: the column in which the cell lives.
:note: The `row` and `col` parameters are not real Python index, as they
use the Excel indexing mode (i.e., first index is 1 and not 0).
"""
cell = self.sheet.Cells(row, col)
if cell:
return cell.Text | [
"def",
"GetText",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"cell",
"=",
"self",
".",
"sheet",
".",
"Cells",
"(",
"row",
",",
"col",
")",
"if",
"cell",
":",
"return",
"cell",
".",
"Text"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/xlsgrid.py#L580-L594 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISPreprocess.py | python | ReflectometryISISPreprocess.seeAlso | (self) | return ['ReflectometryISISLoadAndProcess', 'ReflectometryReductionOneAuto'] | Return a list of related algorithm names. | Return a list of related algorithm names. | [
"Return",
"a",
"list",
"of",
"related",
"algorithm",
"names",
"."
] | def seeAlso(self):
"""Return a list of related algorithm names."""
return ['ReflectometryISISLoadAndProcess', 'ReflectometryReductionOneAuto'] | [
"def",
"seeAlso",
"(",
"self",
")",
":",
"return",
"[",
"'ReflectometryISISLoadAndProcess'",
",",
"'ReflectometryReductionOneAuto'",
"]"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISPreprocess.py#L37-L39 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/pty.py | python | _copy | (master_fd, master_read=_read, stdin_read=_read) | Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read) | Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read) | [
"Parent",
"copy",
"loop",
".",
"Copies",
"pty",
"master",
"-",
">",
"standard",
"output",
"(",
"master_read",
")",
"standard",
"input",
"-",
">",
"pty",
"master",
"(",
"stdin_read",
")"
] | def _copy(master_fd, master_read=_read, stdin_read=_read):
"""Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read)"""
fds = [master_fd, STDIN_FILENO]
while True:
rfds, wfds, xfds = select(fds, [], [])
if master_fd in rfds:
data = master_read(master_fd)
if not data: # Reached EOF.
fds.remove(master_fd)
else:
os.write(STDOUT_FILENO, data)
if STDIN_FILENO in rfds:
data = stdin_read(STDIN_FILENO)
if not data:
fds.remove(STDIN_FILENO)
else:
_writen(master_fd, data) | [
"def",
"_copy",
"(",
"master_fd",
",",
"master_read",
"=",
"_read",
",",
"stdin_read",
"=",
"_read",
")",
":",
"fds",
"=",
"[",
"master_fd",
",",
"STDIN_FILENO",
"]",
"while",
"True",
":",
"rfds",
",",
"wfds",
",",
"xfds",
"=",
"select",
"(",
"fds",
",",
"[",
"]",
",",
"[",
"]",
")",
"if",
"master_fd",
"in",
"rfds",
":",
"data",
"=",
"master_read",
"(",
"master_fd",
")",
"if",
"not",
"data",
":",
"# Reached EOF.",
"fds",
".",
"remove",
"(",
"master_fd",
")",
"else",
":",
"os",
".",
"write",
"(",
"STDOUT_FILENO",
",",
"data",
")",
"if",
"STDIN_FILENO",
"in",
"rfds",
":",
"data",
"=",
"stdin_read",
"(",
"STDIN_FILENO",
")",
"if",
"not",
"data",
":",
"fds",
".",
"remove",
"(",
"STDIN_FILENO",
")",
"else",
":",
"_writen",
"(",
"master_fd",
",",
"data",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pty.py#L130-L149 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/compiler.py | python | source_to_entity | (source, delete_on_exit) | return imp.load_source(module_name, f.name), f.name | Loads the given source code as a Python module. | Loads the given source code as a Python module. | [
"Loads",
"the",
"given",
"source",
"code",
"as",
"a",
"Python",
"module",
"."
] | def source_to_entity(source, delete_on_exit):
"""Loads the given source code as a Python module."""
if six.PY2:
source = source.encode('utf-8')
f = tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False)
else:
f = tempfile.NamedTemporaryFile( # pylint:disable=unexpected-keyword-arg
mode='w', suffix='.py', delete=False, encoding='utf-8')
with f:
module_name = os.path.basename(f.name[:-3])
f.write(source)
if delete_on_exit and ag_logging.get_verbosity() < 3:
atexit.register(lambda: os.remove(f.name))
return imp.load_source(module_name, f.name), f.name | [
"def",
"source_to_entity",
"(",
"source",
",",
"delete_on_exit",
")",
":",
"if",
"six",
".",
"PY2",
":",
"source",
"=",
"source",
".",
"encode",
"(",
"'utf-8'",
")",
"f",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"suffix",
"=",
"'.py'",
",",
"delete",
"=",
"False",
")",
"else",
":",
"f",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"# pylint:disable=unexpected-keyword-arg",
"mode",
"=",
"'w'",
",",
"suffix",
"=",
"'.py'",
",",
"delete",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
")",
"with",
"f",
":",
"module_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"f",
".",
"name",
"[",
":",
"-",
"3",
"]",
")",
"f",
".",
"write",
"(",
"source",
")",
"if",
"delete_on_exit",
"and",
"ag_logging",
".",
"get_verbosity",
"(",
")",
"<",
"3",
":",
"atexit",
".",
"register",
"(",
"lambda",
":",
"os",
".",
"remove",
"(",
"f",
".",
"name",
")",
")",
"return",
"imp",
".",
"load_source",
"(",
"module_name",
",",
"f",
".",
"name",
")",
",",
"f",
".",
"name"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/compiler.py#L89-L104 | |
chuckcho/video-caffe | fc232b3e3a90ea22dd041b9fc5c542f170581f20 | tools/extra/resize_and_crop_images.py | python | OpenCVResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256) | Takes an image name, resize it and crop the center square | Takes an image name, resize it and crop the center square | [
"Takes",
"an",
"image",
"name",
"resize",
"it",
"and",
"crop",
"the",
"center",
"square"
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256):
'''Takes an image name, resize it and crop the center square
'''
img = cv2.imread(input_file)
height, width, depth = img.shape
new_height = output_side_length
new_width = output_side_length
if height > width:
new_height = output_side_length * height / width
else:
new_width = output_side_length * width / height
resized_img = cv2.resize(img, (new_width, new_height))
height_offset = (new_height - output_side_length) / 2
width_offset = (new_width - output_side_length) / 2
cropped_img = resized_img[height_offset:height_offset + output_side_length,
width_offset:width_offset + output_side_length]
cv2.imwrite(output_file, cropped_img) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"input_file",
")",
"height",
",",
"width",
",",
"depth",
"=",
"img",
".",
"shape",
"new_height",
"=",
"output_side_length",
"new_width",
"=",
"output_side_length",
"if",
"height",
">",
"width",
":",
"new_height",
"=",
"output_side_length",
"*",
"height",
"/",
"width",
"else",
":",
"new_width",
"=",
"output_side_length",
"*",
"width",
"/",
"height",
"resized_img",
"=",
"cv2",
".",
"resize",
"(",
"img",
",",
"(",
"new_width",
",",
"new_height",
")",
")",
"height_offset",
"=",
"(",
"new_height",
"-",
"output_side_length",
")",
"/",
"2",
"width_offset",
"=",
"(",
"new_width",
"-",
"output_side_length",
")",
"/",
"2",
"cropped_img",
"=",
"resized_img",
"[",
"height_offset",
":",
"height_offset",
"+",
"output_side_length",
",",
"width_offset",
":",
"width_offset",
"+",
"output_side_length",
"]",
"cv2",
".",
"imwrite",
"(",
"output_file",
",",
"cropped_img",
")"
] | https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/tools/extra/resize_and_crop_images.py#L20-L36 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/powercycle/powercycle.py | python | new_resmoke_config | (config_file, new_config_file, test_data, eval_str="") | Create 'new_config_file', from 'config_file', with an update from 'test_data'. | Create 'new_config_file', from 'config_file', with an update from 'test_data'. | [
"Create",
"new_config_file",
"from",
"config_file",
"with",
"an",
"update",
"from",
"test_data",
"."
] | def new_resmoke_config(config_file, new_config_file, test_data, eval_str=""):
"""Create 'new_config_file', from 'config_file', with an update from 'test_data'."""
new_config = {
"executor": {
"config": {"shell_options": {"eval": eval_str, "global_vars": {"TestData": test_data}}}
}
}
with open(config_file, "r") as yaml_stream:
config = yaml.safe_load(yaml_stream)
config.update(new_config)
with open(new_config_file, "w") as yaml_stream:
yaml.safe_dump(config, yaml_stream) | [
"def",
"new_resmoke_config",
"(",
"config_file",
",",
"new_config_file",
",",
"test_data",
",",
"eval_str",
"=",
"\"\"",
")",
":",
"new_config",
"=",
"{",
"\"executor\"",
":",
"{",
"\"config\"",
":",
"{",
"\"shell_options\"",
":",
"{",
"\"eval\"",
":",
"eval_str",
",",
"\"global_vars\"",
":",
"{",
"\"TestData\"",
":",
"test_data",
"}",
"}",
"}",
"}",
"}",
"with",
"open",
"(",
"config_file",
",",
"\"r\"",
")",
"as",
"yaml_stream",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"yaml_stream",
")",
"config",
".",
"update",
"(",
"new_config",
")",
"with",
"open",
"(",
"new_config_file",
",",
"\"w\"",
")",
"as",
"yaml_stream",
":",
"yaml",
".",
"safe_dump",
"(",
"config",
",",
"yaml_stream",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/powercycle/powercycle.py#L1257-L1268 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/joblib/joblib/compressor.py | python | BinaryZlibFile.writable | (self) | return self._mode == _MODE_WRITE | Return whether the file was opened for writing. | Return whether the file was opened for writing. | [
"Return",
"whether",
"the",
"file",
"was",
"opened",
"for",
"writing",
"."
] | def writable(self):
"""Return whether the file was opened for writing."""
self._check_not_closed()
return self._mode == _MODE_WRITE | [
"def",
"writable",
"(",
"self",
")",
":",
"self",
".",
"_check_not_closed",
"(",
")",
"return",
"self",
".",
"_mode",
"==",
"_MODE_WRITE"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/compressor.py#L340-L343 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/transforms/references.py | python | Footnotes.resolve_footnotes_and_citations | (self) | Link manually-labeled footnotes and citations to/from their
references. | Link manually-labeled footnotes and citations to/from their
references. | [
"Link",
"manually",
"-",
"labeled",
"footnotes",
"and",
"citations",
"to",
"/",
"from",
"their",
"references",
"."
] | def resolve_footnotes_and_citations(self):
"""
Link manually-labeled footnotes and citations to/from their
references.
"""
for footnote in self.document.footnotes:
for label in footnote['names']:
if label in self.document.footnote_refs:
reflist = self.document.footnote_refs[label]
self.resolve_references(footnote, reflist)
for citation in self.document.citations:
for label in citation['names']:
if label in self.document.citation_refs:
reflist = self.document.citation_refs[label]
self.resolve_references(citation, reflist) | [
"def",
"resolve_footnotes_and_citations",
"(",
"self",
")",
":",
"for",
"footnote",
"in",
"self",
".",
"document",
".",
"footnotes",
":",
"for",
"label",
"in",
"footnote",
"[",
"'names'",
"]",
":",
"if",
"label",
"in",
"self",
".",
"document",
".",
"footnote_refs",
":",
"reflist",
"=",
"self",
".",
"document",
".",
"footnote_refs",
"[",
"label",
"]",
"self",
".",
"resolve_references",
"(",
"footnote",
",",
"reflist",
")",
"for",
"citation",
"in",
"self",
".",
"document",
".",
"citations",
":",
"for",
"label",
"in",
"citation",
"[",
"'names'",
"]",
":",
"if",
"label",
"in",
"self",
".",
"document",
".",
"citation_refs",
":",
"reflist",
"=",
"self",
".",
"document",
".",
"citation_refs",
"[",
"label",
"]",
"self",
".",
"resolve_references",
"(",
"citation",
",",
"reflist",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/transforms/references.py#L598-L612 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/path-in-zigzag-labelled-binary-tree.py | python | Solution.pathInZigZagTree | (self, label) | return result | :type label: int
:rtype: List[int] | :type label: int
:rtype: List[int] | [
":",
"type",
"label",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def pathInZigZagTree(self, label):
"""
:type label: int
:rtype: List[int]
"""
count = 2**label.bit_length()
result = []
while label >= 1:
result.append(label)
label = ((count//2) + ((count-1)-label)) // 2
count //= 2
result.reverse()
return result | [
"def",
"pathInZigZagTree",
"(",
"self",
",",
"label",
")",
":",
"count",
"=",
"2",
"**",
"label",
".",
"bit_length",
"(",
")",
"result",
"=",
"[",
"]",
"while",
"label",
">=",
"1",
":",
"result",
".",
"append",
"(",
"label",
")",
"label",
"=",
"(",
"(",
"count",
"//",
"2",
")",
"+",
"(",
"(",
"count",
"-",
"1",
")",
"-",
"label",
")",
")",
"//",
"2",
"count",
"//=",
"2",
"result",
".",
"reverse",
"(",
")",
"return",
"result"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/path-in-zigzag-labelled-binary-tree.py#L5-L17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.