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
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baidu/AnyQ | d94d450d2aaa5f7ed73424b10aa4539835b97527 | tools/common/utils.py | python | import_class | (module_path, module_name, class_name) | return getattr(module, class_name) | Load class dynamically
Args:
module_path: The current path of the module
module_name: The module name
class_name: The name of class in the import module
Return:
Return the attribute value of the class object | Load class dynamically
Args:
module_path: The current path of the module
module_name: The module name
class_name: The name of class in the import module
Return:
Return the attribute value of the class object | [
"Load",
"class",
"dynamically",
"Args",
":",
"module_path",
":",
"The",
"current",
"path",
"of",
"the",
"module",
"module_name",
":",
"The",
"module",
"name",
"class_name",
":",
"The",
"name",
"of",
"class",
"in",
"the",
"import",
"module",
"Return",
":",
"Return",
"the",
"attribute",
"value",
"of",
"the",
"class",
"object"
] | def import_class(module_path, module_name, class_name):
"""
Load class dynamically
Args:
module_path: The current path of the module
module_name: The module name
class_name: The name of class in the import module
Return:
Return the attribute value of the class object
"""
if module_path:
sys.path.append(module_path)
module = __import__(module_name)
return getattr(module, class_name) | [
"def",
"import_class",
"(",
"module_path",
",",
"module_name",
",",
"class_name",
")",
":",
"if",
"module_path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"module_path",
")",
"module",
"=",
"__import__",
"(",
"module_name",
")",
"return",
"getattr",
"(",
"module",
",",
"class_name",
")"
] | https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/common/utils.py#L142-L155 |
|
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/converters/mil/backend/nn/passes/mlmodel_passes.py | python | transform_conv_crop | (spec) | Transforms Conv -> Crop -> BN (if present) -> Activation (if present) into
Conv -> BN (if present) -> Activation (if present) -> Crop
This transformation will allow Conv -> BN -> Activation fusion by changing
the position of the crop layer, which does not affect the computation | Transforms Conv -> Crop -> BN (if present) -> Activation (if present) into
Conv -> BN (if present) -> Activation (if present) -> Crop
This transformation will allow Conv -> BN -> Activation fusion by changing
the position of the crop layer, which does not affect the computation | [
"Transforms",
"Conv",
"-",
">",
"Crop",
"-",
">",
"BN",
"(",
"if",
"present",
")",
"-",
">",
"Activation",
"(",
"if",
"present",
")",
"into",
"Conv",
"-",
">",
"BN",
"(",
"if",
"present",
")",
"-",
">",
"Activation",
"(",
"if",
"present",
")",
"-",
">",
"Crop",
"This",
"transformation",
"will",
"allow",
"Conv",
"-",
">",
"BN",
"-",
">",
"Activation",
"fusion",
"by",
"changing",
"the",
"position",
"of",
"the",
"crop",
"layer",
"which",
"does",
"not",
"affect",
"the",
"computation"
] | def transform_conv_crop(spec):
"""
Transforms Conv -> Crop -> BN (if present) -> Activation (if present) into
Conv -> BN (if present) -> Activation (if present) -> Crop
This transformation will allow Conv -> BN -> Activation fusion by changing
the position of the crop layer, which does not affect the computation
"""
# Collect metadata
out_degree = _get_blob_out_degree(spec)
network_output_names = _get_network_output(spec)
nn_spec = _get_nn_spec(spec)
nn_layers = nn_spec.layers
for i in range(0, len(nn_layers) - 2):
# If Convolution output is being using as a network output or more than one layers
# that's acceptable
if not _is_layer(nn_layers[i], "convolution"):
continue
# Output of Crop layer must not be network output or used by more than one layer
if not (
_is_layer(nn_layers[i + 1], "crop")
and _get_input(nn_layers[i + 1]) not in network_output_names
and out_degree[_get_output(nn_layers[i + 1])] == 1
):
continue
layer_to_shuffle_with = -1
# Output of Batchnorm layer must not be network output or used by more than one layer
if (
_is_layer(nn_layers[i + 2], "batchnorm")
and out_degree[_get_output(nn_layers[i + 2])] == 1
):
layer_to_shuffle_with = i + 2
# Output of Activation layer must not be network output or used by more than one layer
if (
i + 3 < len(nn_layers)
and _is_layer(nn_layers[i + 3], "activation")
and out_degree[_get_output(nn_layers[i + 3])] == 1
):
layer_to_shuffle_with = i + 3
if layer_to_shuffle_with == -1:
continue
# restructure crop layer
# Conv ---> Crop ---> BN ---> Activation ---> Layer1
# In following three steps
# 1. Conv --------------> BN ---> Activation ---> Layer1
# \ /
# ---> Crop --
nn_layers[i].output[0] = nn_layers[i + 1].output[0]
# 2. Conv ---> BN ---> Activation ---> Layer1
# \ /
# -----------------Crop ----
nn_layers[i + 1].output[0] = nn_layers[layer_to_shuffle_with].output[0]
# 3. Conv ---> BN ---> Activation ---> Crop ---> Layer1
nn_layers[layer_to_shuffle_with].output[0] = nn_layers[i + 1].input[0]
# Add Crop layer at new position and remove from current position
crop_layer = nn_layers[i + 1]
nn_layers.remove(crop_layer)
nn_layers.insert(layer_to_shuffle_with, crop_layer) | [
"def",
"transform_conv_crop",
"(",
"spec",
")",
":",
"# Collect metadata",
"out_degree",
"=",
"_get_blob_out_degree",
"(",
"spec",
")",
"network_output_names",
"=",
"_get_network_output",
"(",
"spec",
")",
"nn_spec",
"=",
"_get_nn_spec",
"(",
"spec",
")",
"nn_layers",
"=",
"nn_spec",
".",
"layers",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"nn_layers",
")",
"-",
"2",
")",
":",
"# If Convolution output is being using as a network output or more than one layers",
"# that's acceptable",
"if",
"not",
"_is_layer",
"(",
"nn_layers",
"[",
"i",
"]",
",",
"\"convolution\"",
")",
":",
"continue",
"# Output of Crop layer must not be network output or used by more than one layer",
"if",
"not",
"(",
"_is_layer",
"(",
"nn_layers",
"[",
"i",
"+",
"1",
"]",
",",
"\"crop\"",
")",
"and",
"_get_input",
"(",
"nn_layers",
"[",
"i",
"+",
"1",
"]",
")",
"not",
"in",
"network_output_names",
"and",
"out_degree",
"[",
"_get_output",
"(",
"nn_layers",
"[",
"i",
"+",
"1",
"]",
")",
"]",
"==",
"1",
")",
":",
"continue",
"layer_to_shuffle_with",
"=",
"-",
"1",
"# Output of Batchnorm layer must not be network output or used by more than one layer",
"if",
"(",
"_is_layer",
"(",
"nn_layers",
"[",
"i",
"+",
"2",
"]",
",",
"\"batchnorm\"",
")",
"and",
"out_degree",
"[",
"_get_output",
"(",
"nn_layers",
"[",
"i",
"+",
"2",
"]",
")",
"]",
"==",
"1",
")",
":",
"layer_to_shuffle_with",
"=",
"i",
"+",
"2",
"# Output of Activation layer must not be network output or used by more than one layer",
"if",
"(",
"i",
"+",
"3",
"<",
"len",
"(",
"nn_layers",
")",
"and",
"_is_layer",
"(",
"nn_layers",
"[",
"i",
"+",
"3",
"]",
",",
"\"activation\"",
")",
"and",
"out_degree",
"[",
"_get_output",
"(",
"nn_layers",
"[",
"i",
"+",
"3",
"]",
")",
"]",
"==",
"1",
")",
":",
"layer_to_shuffle_with",
"=",
"i",
"+",
"3",
"if",
"layer_to_shuffle_with",
"==",
"-",
"1",
":",
"continue",
"# restructure crop layer",
"# Conv ---> Crop ---> BN ---> Activation ---> Layer1",
"# In following three steps",
"# 1. Conv --------------> BN ---> Activation ---> Layer1",
"# \\ /",
"# ---> Crop --",
"nn_layers",
"[",
"i",
"]",
".",
"output",
"[",
"0",
"]",
"=",
"nn_layers",
"[",
"i",
"+",
"1",
"]",
".",
"output",
"[",
"0",
"]",
"# 2. Conv ---> BN ---> Activation ---> Layer1",
"# \\ /",
"# -----------------Crop ----",
"nn_layers",
"[",
"i",
"+",
"1",
"]",
".",
"output",
"[",
"0",
"]",
"=",
"nn_layers",
"[",
"layer_to_shuffle_with",
"]",
".",
"output",
"[",
"0",
"]",
"# 3. Conv ---> BN ---> Activation ---> Crop ---> Layer1",
"nn_layers",
"[",
"layer_to_shuffle_with",
"]",
".",
"output",
"[",
"0",
"]",
"=",
"nn_layers",
"[",
"i",
"+",
"1",
"]",
".",
"input",
"[",
"0",
"]",
"# Add Crop layer at new position and remove from current position",
"crop_layer",
"=",
"nn_layers",
"[",
"i",
"+",
"1",
"]",
"nn_layers",
".",
"remove",
"(",
"crop_layer",
")",
"nn_layers",
".",
"insert",
"(",
"layer_to_shuffle_with",
",",
"crop_layer",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/backend/nn/passes/mlmodel_passes.py#L105-L169 |
||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | clang/bindings/python/clang/cindex.py | python | Config.set_library_path | (path) | Set the path in which to search for libclang | Set the path in which to search for libclang | [
"Set",
"the",
"path",
"in",
"which",
"to",
"search",
"for",
"libclang"
] | def set_library_path(path):
"""Set the path in which to search for libclang"""
if Config.loaded:
raise Exception("library path must be set before before using " \
"any other functionalities in libclang.")
Config.library_path = fspath(path) | [
"def",
"set_library_path",
"(",
"path",
")",
":",
"if",
"Config",
".",
"loaded",
":",
"raise",
"Exception",
"(",
"\"library path must be set before before using \"",
"\"any other functionalities in libclang.\"",
")",
"Config",
".",
"library_path",
"=",
"fspath",
"(",
"path",
")"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/bindings/python/clang/cindex.py#L4105-L4111 |
||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecManifestToRc | (self, arch, *args) | Creates a resource file pointing a SxS assembly manifest.
|args| is tuple containing path to resource file, path to manifest file
and resource name which can be "1" (for executables) or "2" (for DLLs). | Creates a resource file pointing a SxS assembly manifest.
|args| is tuple containing path to resource file, path to manifest file
and resource name which can be "1" (for executables) or "2" (for DLLs). | [
"Creates",
"a",
"resource",
"file",
"pointing",
"a",
"SxS",
"assembly",
"manifest",
".",
"|args|",
"is",
"tuple",
"containing",
"path",
"to",
"resource",
"file",
"path",
"to",
"manifest",
"file",
"and",
"resource",
"name",
"which",
"can",
"be",
"1",
"(",
"for",
"executables",
")",
"or",
"2",
"(",
"for",
"DLLs",
")",
"."
] | def ExecManifestToRc(self, arch, *args):
"""Creates a resource file pointing a SxS assembly manifest.
|args| is tuple containing path to resource file, path to manifest file
and resource name which can be "1" (for executables) or "2" (for DLLs)."""
manifest_path, resource_path, resource_name = args
with open(resource_path, 'wb') as output:
output.write('#include <windows.h>\n%s RT_MANIFEST "%s"' % (
resource_name,
os.path.abspath(manifest_path).replace('\\', '/'))) | [
"def",
"ExecManifestToRc",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"manifest_path",
",",
"resource_path",
",",
"resource_name",
"=",
"args",
"with",
"open",
"(",
"resource_path",
",",
"'wb'",
")",
"as",
"output",
":",
"output",
".",
"write",
"(",
"'#include <windows.h>\\n%s RT_MANIFEST \"%s\"'",
"%",
"(",
"resource_name",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"manifest_path",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
")",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/win_tool.py#L229-L237 |
||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/bindings/python/clang/cindex.py | python | TranslationUnit.save | (self, filename) | Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to (str or PathLike). | Saves the TranslationUnit to a file. | [
"Saves",
"the",
"TranslationUnit",
"to",
"a",
"file",
"."
] | def save(self, filename):
"""Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to (str or PathLike).
"""
options = conf.lib.clang_defaultSaveOptions(self)
result = int(conf.lib.clang_saveTranslationUnit(self, fspath(filename),
options))
if result != 0:
raise TranslationUnitSaveError(result,
'Error saving TranslationUnit.') | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"options",
"=",
"conf",
".",
"lib",
".",
"clang_defaultSaveOptions",
"(",
"self",
")",
"result",
"=",
"int",
"(",
"conf",
".",
"lib",
".",
"clang_saveTranslationUnit",
"(",
"self",
",",
"fspath",
"(",
"filename",
")",
",",
"options",
")",
")",
"if",
"result",
"!=",
"0",
":",
"raise",
"TranslationUnitSaveError",
"(",
"result",
",",
"'Error saving TranslationUnit.'",
")"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L3011-L3031 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/monkey.py | python | get_unpatched_class | (cls) | return base | Protect against re-patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first. | Protect against re-patching the distutils if reloaded | [
"Protect",
"against",
"re",
"-",
"patching",
"the",
"distutils",
"if",
"reloaded"
] | def get_unpatched_class(cls):
"""Protect against re-patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first.
"""
external_bases = (
cls
for cls in _get_mro(cls)
if not cls.__module__.startswith('setuptools')
)
base = next(external_bases)
if not base.__module__.startswith('distutils'):
msg = "distutils has already been patched by %r" % cls
raise AssertionError(msg)
return base | [
"def",
"get_unpatched_class",
"(",
"cls",
")",
":",
"external_bases",
"=",
"(",
"cls",
"for",
"cls",
"in",
"_get_mro",
"(",
"cls",
")",
"if",
"not",
"cls",
".",
"__module__",
".",
"startswith",
"(",
"'setuptools'",
")",
")",
"base",
"=",
"next",
"(",
"external_bases",
")",
"if",
"not",
"base",
".",
"__module__",
".",
"startswith",
"(",
"'distutils'",
")",
":",
"msg",
"=",
"\"distutils has already been patched by %r\"",
"%",
"cls",
"raise",
"AssertionError",
"(",
"msg",
")",
"return",
"base"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/monkey.py#L47-L62 |
|
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TChA.SaveTxt | (self, *args) | return _snap.TChA_SaveTxt(self, *args) | SaveTxt(TChA self, PSOut const & SOut)
Parameters:
SOut: PSOut const & | SaveTxt(TChA self, PSOut const & SOut) | [
"SaveTxt",
"(",
"TChA",
"self",
"PSOut",
"const",
"&",
"SOut",
")"
] | def SaveTxt(self, *args):
"""
SaveTxt(TChA self, PSOut const & SOut)
Parameters:
SOut: PSOut const &
"""
return _snap.TChA_SaveTxt(self, *args) | [
"def",
"SaveTxt",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TChA_SaveTxt",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L9072-L9080 |
|
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/FlowGraph.py | python | FlowGraph.export_data | (self) | return data | Export this flow graph to nested data.
Export all block and connection data.
Returns:
a nested data odict | Export this flow graph to nested data.
Export all block and connection data. | [
"Export",
"this",
"flow",
"graph",
"to",
"nested",
"data",
".",
"Export",
"all",
"block",
"and",
"connection",
"data",
"."
] | def export_data(self):
"""
Export this flow graph to nested data.
Export all block and connection data.
Returns:
a nested data odict
"""
def block_order(b):
return not b.is_variable, b.name # todo: vars still first ?!?
data = collections.OrderedDict()
data['options'] = self.options_block.export_data()
data['blocks'] = [b.export_data() for b in sorted(self.blocks, key=block_order)
if b is not self.options_block]
data['connections'] = sorted(c.export_data() for c in self.connections)
data['metadata'] = {'file_format': FLOW_GRAPH_FILE_FORMAT_VERSION}
return data | [
"def",
"export_data",
"(",
"self",
")",
":",
"def",
"block_order",
"(",
"b",
")",
":",
"return",
"not",
"b",
".",
"is_variable",
",",
"b",
".",
"name",
"# todo: vars still first ?!?",
"data",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"data",
"[",
"'options'",
"]",
"=",
"self",
".",
"options_block",
".",
"export_data",
"(",
")",
"data",
"[",
"'blocks'",
"]",
"=",
"[",
"b",
".",
"export_data",
"(",
")",
"for",
"b",
"in",
"sorted",
"(",
"self",
".",
"blocks",
",",
"key",
"=",
"block_order",
")",
"if",
"b",
"is",
"not",
"self",
".",
"options_block",
"]",
"data",
"[",
"'connections'",
"]",
"=",
"sorted",
"(",
"c",
".",
"export_data",
"(",
")",
"for",
"c",
"in",
"self",
".",
"connections",
")",
"data",
"[",
"'metadata'",
"]",
"=",
"{",
"'file_format'",
":",
"FLOW_GRAPH_FILE_FORMAT_VERSION",
"}",
"return",
"data"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/FlowGraph.py#L382-L399 |
|
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/clip_ops.py | python | clip_by_global_norm | (t_list, clip_norm, use_norm=None, name=None) | return list_clipped, use_norm | Clips values of multiple tensors by the ratio of the sum of their norms.
Given a tuple or list of tensors `t_list`, and a clipping ratio `clip_norm`,
this operation returns a list of clipped tensors `list_clipped`
and the global norm (`global_norm`) of all tensors in `t_list`. Optionally,
if you've already computed the global norm for `t_list`, you can specify
the global norm with `use_norm`.
To perform the clipping, the values `t_list[i]` are set to:
t_list[i] * clip_norm / max(global_norm, clip_norm)
where:
global_norm = sqrt(sum([l2norm(t)**2 for t in t_list]))
If `clip_norm > global_norm` then the entries in `t_list` remain as they are,
otherwise they're all shrunk by the global ratio.
Any of the entries of `t_list` that are of type `None` are ignored.
This is the correct way to perform gradient clipping (for example, see
[Pascanu et al., 2012](http://arxiv.org/abs/1211.5063)
([pdf](http://arxiv.org/pdf/1211.5063.pdf))).
However, it is slower than `clip_by_norm()` because all the parameters must be
ready before the clipping operation can be performed.
Args:
t_list: A tuple or list of mixed `Tensors`, `IndexedSlices`, or None.
clip_norm: A 0-D (scalar) `Tensor` > 0. The clipping ratio.
use_norm: A 0-D (scalar) `Tensor` of type `float` (optional). The global
norm to use. If not provided, `global_norm()` is used to compute the norm.
name: A name for the operation (optional).
Returns:
list_clipped: A list of `Tensors` of the same type as `list_t`.
global_norm: A 0-D (scalar) `Tensor` representing the global norm.
Raises:
TypeError: If `t_list` is not a sequence. | Clips values of multiple tensors by the ratio of the sum of their norms. | [
"Clips",
"values",
"of",
"multiple",
"tensors",
"by",
"the",
"ratio",
"of",
"the",
"sum",
"of",
"their",
"norms",
"."
] | def clip_by_global_norm(t_list, clip_norm, use_norm=None, name=None):
"""Clips values of multiple tensors by the ratio of the sum of their norms.
Given a tuple or list of tensors `t_list`, and a clipping ratio `clip_norm`,
this operation returns a list of clipped tensors `list_clipped`
and the global norm (`global_norm`) of all tensors in `t_list`. Optionally,
if you've already computed the global norm for `t_list`, you can specify
the global norm with `use_norm`.
To perform the clipping, the values `t_list[i]` are set to:
t_list[i] * clip_norm / max(global_norm, clip_norm)
where:
global_norm = sqrt(sum([l2norm(t)**2 for t in t_list]))
If `clip_norm > global_norm` then the entries in `t_list` remain as they are,
otherwise they're all shrunk by the global ratio.
Any of the entries of `t_list` that are of type `None` are ignored.
This is the correct way to perform gradient clipping (for example, see
[Pascanu et al., 2012](http://arxiv.org/abs/1211.5063)
([pdf](http://arxiv.org/pdf/1211.5063.pdf))).
However, it is slower than `clip_by_norm()` because all the parameters must be
ready before the clipping operation can be performed.
Args:
t_list: A tuple or list of mixed `Tensors`, `IndexedSlices`, or None.
clip_norm: A 0-D (scalar) `Tensor` > 0. The clipping ratio.
use_norm: A 0-D (scalar) `Tensor` of type `float` (optional). The global
norm to use. If not provided, `global_norm()` is used to compute the norm.
name: A name for the operation (optional).
Returns:
list_clipped: A list of `Tensors` of the same type as `list_t`.
global_norm: A 0-D (scalar) `Tensor` representing the global norm.
Raises:
TypeError: If `t_list` is not a sequence.
"""
if (not isinstance(t_list, collections.Sequence)
or isinstance(t_list, six.string_types)):
raise TypeError("t_list should be a sequence")
t_list = list(t_list)
if use_norm is None:
use_norm = global_norm(t_list, name)
with ops.name_scope(name, "clip_by_global_norm",
t_list + [clip_norm]) as name:
# Calculate L2-norm, clip elements by ratio of clip_norm to L2-norm
scale = clip_norm * math_ops.minimum(
1.0 / use_norm,
constant_op.constant(1.0, dtype=use_norm.dtype) / clip_norm)
values = [
ops.convert_to_tensor(
t.values if isinstance(t, ops.IndexedSlices) else t,
name="t_%d" % i)
if t is not None else t
for i, t in enumerate(t_list)]
values_clipped = []
for i, v in enumerate(values):
if v is None:
values_clipped.append(None)
else:
with ops.colocate_with(v):
values_clipped.append(
array_ops.identity(v * scale, name="%s_%d" % (name, i)))
list_clipped = [
ops.IndexedSlices(c_v, t.indices, t.dense_shape)
if isinstance(t, ops.IndexedSlices)
else c_v
for (c_v, t) in zip(values_clipped, t_list)]
return list_clipped, use_norm | [
"def",
"clip_by_global_norm",
"(",
"t_list",
",",
"clip_norm",
",",
"use_norm",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"t_list",
",",
"collections",
".",
"Sequence",
")",
"or",
"isinstance",
"(",
"t_list",
",",
"six",
".",
"string_types",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"t_list should be a sequence\"",
")",
"t_list",
"=",
"list",
"(",
"t_list",
")",
"if",
"use_norm",
"is",
"None",
":",
"use_norm",
"=",
"global_norm",
"(",
"t_list",
",",
"name",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"clip_by_global_norm\"",
",",
"t_list",
"+",
"[",
"clip_norm",
"]",
")",
"as",
"name",
":",
"# Calculate L2-norm, clip elements by ratio of clip_norm to L2-norm",
"scale",
"=",
"clip_norm",
"*",
"math_ops",
".",
"minimum",
"(",
"1.0",
"/",
"use_norm",
",",
"constant_op",
".",
"constant",
"(",
"1.0",
",",
"dtype",
"=",
"use_norm",
".",
"dtype",
")",
"/",
"clip_norm",
")",
"values",
"=",
"[",
"ops",
".",
"convert_to_tensor",
"(",
"t",
".",
"values",
"if",
"isinstance",
"(",
"t",
",",
"ops",
".",
"IndexedSlices",
")",
"else",
"t",
",",
"name",
"=",
"\"t_%d\"",
"%",
"i",
")",
"if",
"t",
"is",
"not",
"None",
"else",
"t",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"t_list",
")",
"]",
"values_clipped",
"=",
"[",
"]",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"if",
"v",
"is",
"None",
":",
"values_clipped",
".",
"append",
"(",
"None",
")",
"else",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"v",
")",
":",
"values_clipped",
".",
"append",
"(",
"array_ops",
".",
"identity",
"(",
"v",
"*",
"scale",
",",
"name",
"=",
"\"%s_%d\"",
"%",
"(",
"name",
",",
"i",
")",
")",
")",
"list_clipped",
"=",
"[",
"ops",
".",
"IndexedSlices",
"(",
"c_v",
",",
"t",
".",
"indices",
",",
"t",
".",
"dense_shape",
")",
"if",
"isinstance",
"(",
"t",
",",
"ops",
".",
"IndexedSlices",
")",
"else",
"c_v",
"for",
"(",
"c_v",
",",
"t",
")",
"in",
"zip",
"(",
"values_clipped",
",",
"t_list",
")",
"]",
"return",
"list_clipped",
",",
"use_norm"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/clip_ops.py#L167-L246 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Window_UnreserveControlId | (*args, **kwargs) | return _core_.Window_UnreserveControlId(*args, **kwargs) | Window_UnreserveControlId(int id, int count=1)
If an ID generated from NewControlId is not assigned to a wxWindowIDRef,
it must be unreserved. | Window_UnreserveControlId(int id, int count=1) | [
"Window_UnreserveControlId",
"(",
"int",
"id",
"int",
"count",
"=",
"1",
")"
] | def Window_UnreserveControlId(*args, **kwargs):
"""
Window_UnreserveControlId(int id, int count=1)
If an ID generated from NewControlId is not assigned to a wxWindowIDRef,
it must be unreserved.
"""
return _core_.Window_UnreserveControlId(*args, **kwargs) | [
"def",
"Window_UnreserveControlId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_UnreserveControlId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L11738-L11745 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/ide/activegrid/tool/STCTextEditor.py | python | TextCtrl.MarkerDefineDefault | (self) | This must be called after the textcontrol is instantiated | This must be called after the textcontrol is instantiated | [
"This",
"must",
"be",
"called",
"after",
"the",
"textcontrol",
"is",
"instantiated"
] | def MarkerDefineDefault(self):
""" This must be called after the textcontrol is instantiated """
self.MarkerDefine(TextView.MARKER_NUM, wx.stc.STC_MARK_ROUNDRECT, wx.BLACK, wx.BLUE) | [
"def",
"MarkerDefineDefault",
"(",
"self",
")",
":",
"self",
".",
"MarkerDefine",
"(",
"TextView",
".",
"MARKER_NUM",
",",
"wx",
".",
"stc",
".",
"STC_MARK_ROUNDRECT",
",",
"wx",
".",
"BLACK",
",",
"wx",
".",
"BLUE",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/tool/STCTextEditor.py#L1190-L1192 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/xml/sax/xmlreader.py | python | XMLReader.setFeature | (self, name, state) | Sets the state of a SAX2 feature. | Sets the state of a SAX2 feature. | [
"Sets",
"the",
"state",
"of",
"a",
"SAX2",
"feature",
"."
] | def setFeature(self, name, state):
"Sets the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name) | [
"def",
"setFeature",
"(",
"self",
",",
"name",
",",
"state",
")",
":",
"raise",
"SAXNotRecognizedException",
"(",
"\"Feature '%s' not recognized\"",
"%",
"name",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/sax/xmlreader.py#L79-L81 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/lib2to3/fixer_util.py | python | is_import | (node) | return node.type in (syms.import_name, syms.import_from) | Returns true if the node is an import statement. | Returns true if the node is an import statement. | [
"Returns",
"true",
"if",
"the",
"node",
"is",
"an",
"import",
"statement",
"."
] | def is_import(node):
"""Returns true if the node is an import statement."""
return node.type in (syms.import_name, syms.import_from) | [
"def",
"is_import",
"(",
"node",
")",
":",
"return",
"node",
".",
"type",
"in",
"(",
"syms",
".",
"import_name",
",",
"syms",
".",
"import_from",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lib2to3/fixer_util.py#L311-L313 |
|
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/mrecords.py | python | fromarrays | (arraylist, dtype=None, shape=None, formats=None,
names=None, titles=None, aligned=False, byteorder=None,
fill_value=None) | return _array | Creates a mrecarray from a (flat) list of masked arrays.
Parameters
----------
arraylist : sequence
A list of (masked) arrays. Each element of the sequence is first converted
to a masked array if needed. If a 2D array is passed as argument, it is
processed line by line
dtype : {None, dtype}, optional
Data type descriptor.
shape : {None, integer}, optional
Number of records. If None, shape is defined from the shape of the
first array in the list.
formats : {None, sequence}, optional
Sequence of formats for each individual field. If None, the formats will
be autodetected by inspecting the fields and selecting the highest dtype
possible.
names : {None, sequence}, optional
Sequence of the names of each field.
fill_value : {None, sequence}, optional
Sequence of data to be used as filling values.
Notes
-----
Lists of tuples should be preferred over lists of lists for faster processing. | Creates a mrecarray from a (flat) list of masked arrays. | [
"Creates",
"a",
"mrecarray",
"from",
"a",
"(",
"flat",
")",
"list",
"of",
"masked",
"arrays",
"."
] | def fromarrays(arraylist, dtype=None, shape=None, formats=None,
names=None, titles=None, aligned=False, byteorder=None,
fill_value=None):
"""Creates a mrecarray from a (flat) list of masked arrays.
Parameters
----------
arraylist : sequence
A list of (masked) arrays. Each element of the sequence is first converted
to a masked array if needed. If a 2D array is passed as argument, it is
processed line by line
dtype : {None, dtype}, optional
Data type descriptor.
shape : {None, integer}, optional
Number of records. If None, shape is defined from the shape of the
first array in the list.
formats : {None, sequence}, optional
Sequence of formats for each individual field. If None, the formats will
be autodetected by inspecting the fields and selecting the highest dtype
possible.
names : {None, sequence}, optional
Sequence of the names of each field.
fill_value : {None, sequence}, optional
Sequence of data to be used as filling values.
Notes
-----
Lists of tuples should be preferred over lists of lists for faster processing.
"""
datalist = [getdata(x) for x in arraylist]
masklist = [np.atleast_1d(getmaskarray(x)) for x in arraylist]
_array = recfromarrays(datalist,
dtype=dtype, shape=shape, formats=formats,
names=names, titles=titles, aligned=aligned,
byteorder=byteorder).view(mrecarray)
_array._mask.flat = list(zip(*masklist))
if fill_value is not None:
_array.fill_value = fill_value
return _array | [
"def",
"fromarrays",
"(",
"arraylist",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"formats",
"=",
"None",
",",
"names",
"=",
"None",
",",
"titles",
"=",
"None",
",",
"aligned",
"=",
"False",
",",
"byteorder",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"datalist",
"=",
"[",
"getdata",
"(",
"x",
")",
"for",
"x",
"in",
"arraylist",
"]",
"masklist",
"=",
"[",
"np",
".",
"atleast_1d",
"(",
"getmaskarray",
"(",
"x",
")",
")",
"for",
"x",
"in",
"arraylist",
"]",
"_array",
"=",
"recfromarrays",
"(",
"datalist",
",",
"dtype",
"=",
"dtype",
",",
"shape",
"=",
"shape",
",",
"formats",
"=",
"formats",
",",
"names",
"=",
"names",
",",
"titles",
"=",
"titles",
",",
"aligned",
"=",
"aligned",
",",
"byteorder",
"=",
"byteorder",
")",
".",
"view",
"(",
"mrecarray",
")",
"_array",
".",
"_mask",
".",
"flat",
"=",
"list",
"(",
"zip",
"(",
"*",
"masklist",
")",
")",
"if",
"fill_value",
"is",
"not",
"None",
":",
"_array",
".",
"fill_value",
"=",
"fill_value",
"return",
"_array"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/mrecords.py#L479-L517 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | PreBitmapButton | (*args, **kwargs) | return val | PreBitmapButton() -> BitmapButton
Precreate a BitmapButton for 2-phase creation. | PreBitmapButton() -> BitmapButton | [
"PreBitmapButton",
"()",
"-",
">",
"BitmapButton"
] | def PreBitmapButton(*args, **kwargs):
"""
PreBitmapButton() -> BitmapButton
Precreate a BitmapButton for 2-phase creation.
"""
val = _controls_.new_PreBitmapButton(*args, **kwargs)
return val | [
"def",
"PreBitmapButton",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_controls_",
".",
"new_PreBitmapButton",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L320-L327 |
|
limbo018/DREAMPlace | 146c3b9fd003d1acd52c96d9fd02e3f0a05154e4 | dreamplace/BasicPlace.py | python | BasicPlace.validate | (self, placedb, pos, iteration) | return hpwl, overflow, max_density | @brief validate placement
@param placedb placement database
@param pos locations of cells
@param iteration optimization step | [] | def validate(self, placedb, pos, iteration):
"""
@brief validate placement
@param placedb placement database
@param pos locations of cells
@param iteration optimization step
"""
pos = torch.from_numpy(pos).to(self.device)
hpwl = self.op_collections.hpwl_op(pos)
#rmst_wls = self.rmst_wl_op(pos)
#rmst_wl = rmst_wls.sum()
overflow, max_density = self.op_collections.density_overflow_op(pos)
#return hpwl, rmst_wl, overflow, max_density
return hpwl, overflow, max_density | [
"def",
"validate",
"(",
"self",
",",
"placedb",
",",
"pos",
",",
"iteration",
")",
":",
"pos",
"=",
"torch",
".",
"from_numpy",
"(",
"pos",
")",
".",
"to",
"(",
"self",
".",
"device",
")",
"hpwl",
"=",
"self",
".",
"op_collections",
".",
"hpwl_op",
"(",
"pos",
")",
"#rmst_wls = self.rmst_wl_op(pos)",
"#rmst_wl = rmst_wls.sum()",
"overflow",
",",
"max_density",
"=",
"self",
".",
"op_collections",
".",
"density_overflow_op",
"(",
"pos",
")",
"#return hpwl, rmst_wl, overflow, max_density",
"return",
"hpwl",
",",
"overflow",
",",
"max_density"
] | https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/BasicPlace.py#L1003-L1017 |
||
olliw42/storm32bgc | 99d62a6130ae2950514022f50eb669c45a8cc1ba | old/betacopter/old/betacopter36dev-v005/modules/uavcan/libuavcan/dsdl_compiler/pyuavcan/uavcan/dsdl/signature.py | python | Signature.add | (self, data_bytes) | Feed ASCII string or bytes to the signature function | Feed ASCII string or bytes to the signature function | [
"Feed",
"ASCII",
"string",
"or",
"bytes",
"to",
"the",
"signature",
"function"
] | def add(self, data_bytes):
'''Feed ASCII string or bytes to the signature function'''
try:
if isinstance(data_bytes, basestring): # Python 2.7 compatibility
data_bytes = map(ord, data_bytes)
except NameError:
if isinstance(data_bytes, str): # This branch will be taken on Python 3
data_bytes = map(ord, data_bytes)
for b in data_bytes:
self._crc ^= (b << 56) & Signature.MASK64
for _ in range(8):
if self._crc & (1 << 63):
self._crc = ((self._crc << 1) & Signature.MASK64) ^ Signature.POLY
else:
self._crc <<= 1 | [
"def",
"add",
"(",
"self",
",",
"data_bytes",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"data_bytes",
",",
"basestring",
")",
":",
"# Python 2.7 compatibility",
"data_bytes",
"=",
"map",
"(",
"ord",
",",
"data_bytes",
")",
"except",
"NameError",
":",
"if",
"isinstance",
"(",
"data_bytes",
",",
"str",
")",
":",
"# This branch will be taken on Python 3",
"data_bytes",
"=",
"map",
"(",
"ord",
",",
"data_bytes",
")",
"for",
"b",
"in",
"data_bytes",
":",
"self",
".",
"_crc",
"^=",
"(",
"b",
"<<",
"56",
")",
"&",
"Signature",
".",
"MASK64",
"for",
"_",
"in",
"range",
"(",
"8",
")",
":",
"if",
"self",
".",
"_crc",
"&",
"(",
"1",
"<<",
"63",
")",
":",
"self",
".",
"_crc",
"=",
"(",
"(",
"self",
".",
"_crc",
"<<",
"1",
")",
"&",
"Signature",
".",
"MASK64",
")",
"^",
"Signature",
".",
"POLY",
"else",
":",
"self",
".",
"_crc",
"<<=",
"1"
] | https://github.com/olliw42/storm32bgc/blob/99d62a6130ae2950514022f50eb669c45a8cc1ba/old/betacopter/old/betacopter36dev-v005/modules/uavcan/libuavcan/dsdl_compiler/pyuavcan/uavcan/dsdl/signature.py#L34-L49 |
||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/opt/python/training/drop_stale_gradient_optimizer.py | python | DropStaleGradientOptimizer.__init__ | (self,
opt,
staleness,
use_locking=False,
name="DropStaleGradient") | Constructs a new DropStaleGradientOptimizer.
Args:
opt: The actual optimizer that will be used to compute and apply the
gradients. Must be one of the Optimizer classes.
staleness: The maximum staleness allowed for the optimizer.
use_locking: If `True` use locks for clip update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "DropStaleGradient". | Constructs a new DropStaleGradientOptimizer. | [
"Constructs",
"a",
"new",
"DropStaleGradientOptimizer",
"."
] | def __init__(self,
opt,
staleness,
use_locking=False,
name="DropStaleGradient"):
"""Constructs a new DropStaleGradientOptimizer.
Args:
opt: The actual optimizer that will be used to compute and apply the
gradients. Must be one of the Optimizer classes.
staleness: The maximum staleness allowed for the optimizer.
use_locking: If `True` use locks for clip update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "DropStaleGradient".
"""
super(DropStaleGradientOptimizer, self).__init__(use_locking, name)
self._opt = opt
self._staleness = staleness | [
"def",
"__init__",
"(",
"self",
",",
"opt",
",",
"staleness",
",",
"use_locking",
"=",
"False",
",",
"name",
"=",
"\"DropStaleGradient\"",
")",
":",
"super",
"(",
"DropStaleGradientOptimizer",
",",
"self",
")",
".",
"__init__",
"(",
"use_locking",
",",
"name",
")",
"self",
".",
"_opt",
"=",
"opt",
"self",
".",
"_staleness",
"=",
"staleness"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/opt/python/training/drop_stale_gradient_optimizer.py#L44-L61 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_txt.py | python | EdFile.FireModified | (self) | Fire the modified callback(s) | Fire the modified callback(s) | [
"Fire",
"the",
"modified",
"callback",
"(",
"s",
")"
] | def FireModified(self):
"""Fire the modified callback(s)"""
remove = list()
for idx, mcallback in enumerate(self._mcallback):
try:
mcallback()
except:
remove.append(idx)
# Cleanup any bad callbacks
if len(remove):
remove.reverse()
for idx in remove:
self._mcallback.pop(idx) | [
"def",
"FireModified",
"(",
"self",
")",
":",
"remove",
"=",
"list",
"(",
")",
"for",
"idx",
",",
"mcallback",
"in",
"enumerate",
"(",
"self",
".",
"_mcallback",
")",
":",
"try",
":",
"mcallback",
"(",
")",
"except",
":",
"remove",
".",
"append",
"(",
"idx",
")",
"# Cleanup any bad callbacks",
"if",
"len",
"(",
"remove",
")",
":",
"remove",
".",
"reverse",
"(",
")",
"for",
"idx",
"in",
"remove",
":",
"self",
".",
"_mcallback",
".",
"pop",
"(",
"idx",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_txt.py#L329-L342 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pyclbr.py | python | readmodule | (module, path=None) | return res | Return Class objects for the top-level classes in module.
This is the original interface, before Functions were added. | Return Class objects for the top-level classes in module. | [
"Return",
"Class",
"objects",
"for",
"the",
"top",
"-",
"level",
"classes",
"in",
"module",
"."
] | def readmodule(module, path=None):
"""Return Class objects for the top-level classes in module.
This is the original interface, before Functions were added.
"""
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
return res | [
"def",
"readmodule",
"(",
"module",
",",
"path",
"=",
"None",
")",
":",
"res",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"_readmodule",
"(",
"module",
",",
"path",
"or",
"[",
"]",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Class",
")",
":",
"res",
"[",
"key",
"]",
"=",
"value",
"return",
"res"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pyclbr.py#L97-L107 |
|
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | cmake/developer_package/cpplint/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.
match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
if match:
include_state.ResetSection(match.group(1))
# Perform other checks now that we are sure that this is not an include line
CheckCasts(filename, clean_lines, linenum, error)
CheckGlobalStatic(filename, clean_lines, linenum, error)
CheckPrintf(filename, clean_lines, linenum, error)
if IsHeaderExtension(file_extension):
# 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 declare or disable copy/assign
# (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', 4,
'Use int16/int64/etc, rather than the C type %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(unknown): 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):
if Search(r'\bliterals\b', line):
error(filename, linenum, 'build/namespaces_literals', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
else:
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.")
# 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 (IsHeaderExtension(file_extension)
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.') | [
"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.",
"match",
"=",
"Match",
"(",
"r'^\\s*#\\s*(if|ifdef|ifndef|elif|else|endif)\\b'",
",",
"line",
")",
"if",
"match",
":",
"include_state",
".",
"ResetSection",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"# Perform other checks now that we are sure that this is not an include line",
"CheckCasts",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"CheckGlobalStatic",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"CheckPrintf",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"if",
"IsHeaderExtension",
"(",
"file_extension",
")",
":",
"# 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 declare or disable copy/assign",
"# (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'",
",",
"4",
",",
"'Use int16/int64/etc, rather than the C type %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(unknown): 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",
")",
":",
"if",
"Search",
"(",
"r'\\bliterals\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces_literals'",
",",
"5",
",",
"'Do not use namespace using-directives. '",
"'Use using-declarations instead.'",
")",
"else",
":",
"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.\"",
")",
"# 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",
"(",
"IsHeaderExtension",
"(",
"file_extension",
")",
"and",
"Search",
"(",
"r'\\bnamespace\\s*{'",
",",
"line",
")",
"and",
"line",
"[",
"-",
"1",
"]",
"!=",
"'\\\\'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces'",
",",
"4",
",",
"'Do not use unnamed namespaces in header files. See '",
"'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'",
"' for more information.'",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/cmake/developer_package/cpplint/cpplint.py#L4954-L5112 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py | python | Message.__str__ | (self) | return self.as_string() | Return the entire formatted message as a string. | Return the entire formatted message as a string. | [
"Return",
"the",
"entire",
"formatted",
"message",
"as",
"a",
"string",
"."
] | def __str__(self):
"""Return the entire formatted message as a string.
"""
return self.as_string() | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"as_string",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py#L132-L135 |
|
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/software/scene_retrieving/src/nlohmann_json/benchmarks/thirdparty/benchmark/tools/gbench/util.py | python | remove_benchmark_flags | (prefix, benchmark_flags) | return [f for f in benchmark_flags if not f.startswith(prefix)] | Return a new list containing the specified benchmark_flags except those
with the specified prefix. | Return a new list containing the specified benchmark_flags except those
with the specified prefix. | [
"Return",
"a",
"new",
"list",
"containing",
"the",
"specified",
"benchmark_flags",
"except",
"those",
"with",
"the",
"specified",
"prefix",
"."
] | def remove_benchmark_flags(prefix, benchmark_flags):
"""
Return a new list containing the specified benchmark_flags except those
with the specified prefix.
"""
assert prefix.startswith('--') and prefix.endswith('=')
return [f for f in benchmark_flags if not f.startswith(prefix)] | [
"def",
"remove_benchmark_flags",
"(",
"prefix",
",",
"benchmark_flags",
")",
":",
"assert",
"prefix",
".",
"startswith",
"(",
"'--'",
")",
"and",
"prefix",
".",
"endswith",
"(",
"'='",
")",
"return",
"[",
"f",
"for",
"f",
"in",
"benchmark_flags",
"if",
"not",
"f",
".",
"startswith",
"(",
"prefix",
")",
"]"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/software/scene_retrieving/src/nlohmann_json/benchmarks/thirdparty/benchmark/tools/gbench/util.py#L100-L106 |
|
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/data_flow_ops.py | python | Barrier.take_many | (self,
num_elements,
allow_small_batch=False,
timeout=None,
name=None) | return ret | Takes the given number of completed elements from this barrier.
This operation concatenates completed-element component tensors along
the 0th dimension to make a single component tensor.
If barrier has no completed elements, this operation will block
until there are 'num_elements' elements to take.
TODO(b/25743580): the semantics of `allow_small_batch` are experimental
and may be extended to other cases in the future.
TODO(ebrevdo): If a take_many(allow_small_batch=True) is blocking
already when the barrier is closed, it will block for ever. Fix this
by using asynchronous operations.
Args:
num_elements: The number of elements to take.
allow_small_batch: If the barrier is closed, don't block if there are less
completed elements than requested, but instead return all available
completed elements.
timeout: This specifies the number of milliseconds to block
before returning with DEADLINE_EXCEEDED. (This option is not
supported yet.)
name: A name for the operation (optional).
Returns:
A tuple of (index, key, value_list).
"index" is a int64 tensor of length num_elements containing the
index of the insert_many call for which the very first component of
the given element was inserted into the Barrier, starting with
the value -2**63. Note, this value is different from the
index of the insert_many call for which the element was completed.
"key" is a string tensor of length num_elements containing the keys.
"value_list" is a tuple of tensors, each one with size num_elements
in the 0th dimension for each component in the barrier's values. | Takes the given number of completed elements from this barrier. | [
"Takes",
"the",
"given",
"number",
"of",
"completed",
"elements",
"from",
"this",
"barrier",
"."
] | def take_many(self,
num_elements,
allow_small_batch=False,
timeout=None,
name=None):
"""Takes the given number of completed elements from this barrier.
This operation concatenates completed-element component tensors along
the 0th dimension to make a single component tensor.
If barrier has no completed elements, this operation will block
until there are 'num_elements' elements to take.
TODO(b/25743580): the semantics of `allow_small_batch` are experimental
and may be extended to other cases in the future.
TODO(ebrevdo): If a take_many(allow_small_batch=True) is blocking
already when the barrier is closed, it will block for ever. Fix this
by using asynchronous operations.
Args:
num_elements: The number of elements to take.
allow_small_batch: If the barrier is closed, don't block if there are less
completed elements than requested, but instead return all available
completed elements.
timeout: This specifies the number of milliseconds to block
before returning with DEADLINE_EXCEEDED. (This option is not
supported yet.)
name: A name for the operation (optional).
Returns:
A tuple of (index, key, value_list).
"index" is a int64 tensor of length num_elements containing the
index of the insert_many call for which the very first component of
the given element was inserted into the Barrier, starting with
the value -2**63. Note, this value is different from the
index of the insert_many call for which the element was completed.
"key" is a string tensor of length num_elements containing the keys.
"value_list" is a tuple of tensors, each one with size num_elements
in the 0th dimension for each component in the barrier's values.
"""
if name is None:
name = "%s_BarrierTakeMany" % self._name
ret = gen_data_flow_ops._barrier_take_many(self._barrier_ref,
num_elements,
self._types,
allow_small_batch,
timeout,
name=name)
# NOTE(mrry): Not using a shape function because we need access to
# the Barrier object.
if context.in_graph_mode():
op = ret[0].op
if allow_small_batch:
batch_dim = None
else:
batch_dim = tensor_shape.Dimension(
tensor_util.constant_value(op.inputs[1]))
op.outputs[0].set_shape(tensor_shape.vector(batch_dim)) # indices
op.outputs[1].set_shape(tensor_shape.vector(batch_dim)) # keys
for output, shape in zip(op.outputs[2:], self._shapes): # value_list
output.set_shape(
tensor_shape.TensorShape([batch_dim]).concatenate(
shape))
return ret | [
"def",
"take_many",
"(",
"self",
",",
"num_elements",
",",
"allow_small_batch",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"%s_BarrierTakeMany\"",
"%",
"self",
".",
"_name",
"ret",
"=",
"gen_data_flow_ops",
".",
"_barrier_take_many",
"(",
"self",
".",
"_barrier_ref",
",",
"num_elements",
",",
"self",
".",
"_types",
",",
"allow_small_batch",
",",
"timeout",
",",
"name",
"=",
"name",
")",
"# NOTE(mrry): Not using a shape function because we need access to",
"# the Barrier object.",
"if",
"context",
".",
"in_graph_mode",
"(",
")",
":",
"op",
"=",
"ret",
"[",
"0",
"]",
".",
"op",
"if",
"allow_small_batch",
":",
"batch_dim",
"=",
"None",
"else",
":",
"batch_dim",
"=",
"tensor_shape",
".",
"Dimension",
"(",
"tensor_util",
".",
"constant_value",
"(",
"op",
".",
"inputs",
"[",
"1",
"]",
")",
")",
"op",
".",
"outputs",
"[",
"0",
"]",
".",
"set_shape",
"(",
"tensor_shape",
".",
"vector",
"(",
"batch_dim",
")",
")",
"# indices",
"op",
".",
"outputs",
"[",
"1",
"]",
".",
"set_shape",
"(",
"tensor_shape",
".",
"vector",
"(",
"batch_dim",
")",
")",
"# keys",
"for",
"output",
",",
"shape",
"in",
"zip",
"(",
"op",
".",
"outputs",
"[",
"2",
":",
"]",
",",
"self",
".",
"_shapes",
")",
":",
"# value_list",
"output",
".",
"set_shape",
"(",
"tensor_shape",
".",
"TensorShape",
"(",
"[",
"batch_dim",
"]",
")",
".",
"concatenate",
"(",
"shape",
")",
")",
"return",
"ret"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L955-L1022 |
|
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | acquisition/tomviz/acquisition/vendors/passive/filesystem.py | python | Monitor.get | (self) | return None | Returns the first pending file available. If there are pending files in
the queue the first in the queue is return, otherwise the path if check
for new files.
:returns: The first pending file, None if no file is available. | Returns the first pending file available. If there are pending files in
the queue the first in the queue is return, otherwise the path if check
for new files. | [
"Returns",
"the",
"first",
"pending",
"file",
"available",
".",
"If",
"there",
"are",
"pending",
"files",
"in",
"the",
"queue",
"the",
"first",
"in",
"the",
"queue",
"is",
"return",
"otherwise",
"the",
"path",
"if",
"check",
"for",
"new",
"files",
"."
] | def get(self):
"""
Returns the first pending file available. If there are pending files in
the queue the first in the queue is return, otherwise the path if check
for new files.
:returns: The first pending file, None if no file is available.
"""
if self._files.empty():
self._check()
try:
return self._files.get(block=False)
except queue.Empty:
pass
return None | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"_files",
".",
"empty",
"(",
")",
":",
"self",
".",
"_check",
"(",
")",
"try",
":",
"return",
"self",
".",
"_files",
".",
"get",
"(",
"block",
"=",
"False",
")",
"except",
"queue",
".",
"Empty",
":",
"pass",
"return",
"None"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/acquisition/tomviz/acquisition/vendors/passive/filesystem.py#L46-L63 |
|
genn-team/genn | 75e1eb218cafa228bf36ae4613d1ce26e877b12c | pygenn/genn_groups.py | python | SynapseGroup.is_dense | (self) | return (self.matrix_type & SynapseMatrixConnectivity_DENSE) != 0 | Tests whether synaptic connectivity uses dense format | Tests whether synaptic connectivity uses dense format | [
"Tests",
"whether",
"synaptic",
"connectivity",
"uses",
"dense",
"format"
] | def is_dense(self):
"""Tests whether synaptic connectivity uses dense format"""
return (self.matrix_type & SynapseMatrixConnectivity_DENSE) != 0 | [
"def",
"is_dense",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"matrix_type",
"&",
"SynapseMatrixConnectivity_DENSE",
")",
"!=",
"0"
] | https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_groups.py#L906-L908 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py | python | real_valued_column | (column_name,
dimension=1,
default_value=None,
dtype=dtypes.float32) | Creates a _RealValuedColumn.
Args:
column_name: A string defining real valued column name.
dimension: An integer specifying dimension of the real valued column.
The default is 1. The Tensor representing the _RealValuedColumn
will have the shape of [batch_size, dimension].
default_value: A single value compatible with dtype or a list of values
compatible with dtype which the column takes on if data is missing. If
None, then tf.parse_example will fail if an example does not contain
this column. If a single value is provided, the same value will be
applied as the default value for every dimension. If a list of values
is provided, the length of the list should be equal to the value of
`dimension`.
dtype: defines the type of values. Default value is tf.float32.
Returns:
A _RealValuedColumn.
Raises:
TypeError: if dimension is not an int
ValueError: if dimension is not a positive integer
TypeError: if default_value is a list but its length is not equal to the
value of `dimension`.
TypeError: if default_value is not compatible with dtype.
ValueError: if dtype is not convertable to tf.float32. | Creates a _RealValuedColumn. | [
"Creates",
"a",
"_RealValuedColumn",
"."
] | def real_valued_column(column_name,
dimension=1,
default_value=None,
dtype=dtypes.float32):
"""Creates a _RealValuedColumn.
Args:
column_name: A string defining real valued column name.
dimension: An integer specifying dimension of the real valued column.
The default is 1. The Tensor representing the _RealValuedColumn
will have the shape of [batch_size, dimension].
default_value: A single value compatible with dtype or a list of values
compatible with dtype which the column takes on if data is missing. If
None, then tf.parse_example will fail if an example does not contain
this column. If a single value is provided, the same value will be
applied as the default value for every dimension. If a list of values
is provided, the length of the list should be equal to the value of
`dimension`.
dtype: defines the type of values. Default value is tf.float32.
Returns:
A _RealValuedColumn.
Raises:
TypeError: if dimension is not an int
ValueError: if dimension is not a positive integer
TypeError: if default_value is a list but its length is not equal to the
value of `dimension`.
TypeError: if default_value is not compatible with dtype.
ValueError: if dtype is not convertable to tf.float32.
"""
if not isinstance(dimension, int):
raise TypeError("dimension must be an integer. "
"dimension: {}, column_name: {}".format(dimension,
column_name))
if dimension < 1:
raise ValueError("dimension must be greater than 0. "
"dimension: {}, column_name: {}".format(dimension,
column_name))
if not (dtype.is_integer or dtype.is_floating):
raise ValueError("dtype must be convertible to float. "
"dtype: {}, column_name: {}".format(dtype, column_name))
if default_value is None:
return _RealValuedColumn(column_name, dimension, default_value, dtype)
if isinstance(default_value, int):
if dtype.is_integer:
default_value = [default_value for _ in range(dimension)]
return _RealValuedColumn(column_name, dimension, default_value, dtype)
if dtype.is_floating:
default_value = float(default_value)
default_value = [default_value for _ in range(dimension)]
return _RealValuedColumn(column_name, dimension, default_value, dtype)
if isinstance(default_value, float):
if dtype.is_floating and (not dtype.is_integer):
default_value = [default_value for _ in range(dimension)]
return _RealValuedColumn(column_name, dimension, default_value, dtype)
if isinstance(default_value, list):
if len(default_value) != dimension:
raise ValueError(
"The length of default_value must be equal to dimension. "
"default_value: {}, dimension: {}, column_name: {}".format(
default_value, dimension, column_name))
# Check if the values in the list are all integers or are convertible to
# floats.
is_list_all_int = True
is_list_all_float = True
for v in default_value:
if not isinstance(v, int):
is_list_all_int = False
if not (isinstance(v, float) or isinstance(v, int)):
is_list_all_float = False
if is_list_all_int:
if dtype.is_integer:
return _RealValuedColumn(column_name, dimension, default_value, dtype)
elif dtype.is_floating:
default_value = [float(v) for v in default_value]
return _RealValuedColumn(column_name, dimension, default_value, dtype)
if is_list_all_float:
if dtype.is_floating and (not dtype.is_integer):
default_value = [float(v) for v in default_value]
return _RealValuedColumn(column_name, dimension, default_value, dtype)
raise TypeError("default_value must be compatible with dtype. "
"default_value: {}, dtype: {}, column_name: {}".format(
default_value, dtype, column_name)) | [
"def",
"real_valued_column",
"(",
"column_name",
",",
"dimension",
"=",
"1",
",",
"default_value",
"=",
"None",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
":",
"if",
"not",
"isinstance",
"(",
"dimension",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"dimension must be an integer. \"",
"\"dimension: {}, column_name: {}\"",
".",
"format",
"(",
"dimension",
",",
"column_name",
")",
")",
"if",
"dimension",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"dimension must be greater than 0. \"",
"\"dimension: {}, column_name: {}\"",
".",
"format",
"(",
"dimension",
",",
"column_name",
")",
")",
"if",
"not",
"(",
"dtype",
".",
"is_integer",
"or",
"dtype",
".",
"is_floating",
")",
":",
"raise",
"ValueError",
"(",
"\"dtype must be convertible to float. \"",
"\"dtype: {}, column_name: {}\"",
".",
"format",
"(",
"dtype",
",",
"column_name",
")",
")",
"if",
"default_value",
"is",
"None",
":",
"return",
"_RealValuedColumn",
"(",
"column_name",
",",
"dimension",
",",
"default_value",
",",
"dtype",
")",
"if",
"isinstance",
"(",
"default_value",
",",
"int",
")",
":",
"if",
"dtype",
".",
"is_integer",
":",
"default_value",
"=",
"[",
"default_value",
"for",
"_",
"in",
"range",
"(",
"dimension",
")",
"]",
"return",
"_RealValuedColumn",
"(",
"column_name",
",",
"dimension",
",",
"default_value",
",",
"dtype",
")",
"if",
"dtype",
".",
"is_floating",
":",
"default_value",
"=",
"float",
"(",
"default_value",
")",
"default_value",
"=",
"[",
"default_value",
"for",
"_",
"in",
"range",
"(",
"dimension",
")",
"]",
"return",
"_RealValuedColumn",
"(",
"column_name",
",",
"dimension",
",",
"default_value",
",",
"dtype",
")",
"if",
"isinstance",
"(",
"default_value",
",",
"float",
")",
":",
"if",
"dtype",
".",
"is_floating",
"and",
"(",
"not",
"dtype",
".",
"is_integer",
")",
":",
"default_value",
"=",
"[",
"default_value",
"for",
"_",
"in",
"range",
"(",
"dimension",
")",
"]",
"return",
"_RealValuedColumn",
"(",
"column_name",
",",
"dimension",
",",
"default_value",
",",
"dtype",
")",
"if",
"isinstance",
"(",
"default_value",
",",
"list",
")",
":",
"if",
"len",
"(",
"default_value",
")",
"!=",
"dimension",
":",
"raise",
"ValueError",
"(",
"\"The length of default_value must be equal to dimension. \"",
"\"default_value: {}, dimension: {}, column_name: {}\"",
".",
"format",
"(",
"default_value",
",",
"dimension",
",",
"column_name",
")",
")",
"# Check if the values in the list are all integers or are convertible to",
"# floats.",
"is_list_all_int",
"=",
"True",
"is_list_all_float",
"=",
"True",
"for",
"v",
"in",
"default_value",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"int",
")",
":",
"is_list_all_int",
"=",
"False",
"if",
"not",
"(",
"isinstance",
"(",
"v",
",",
"float",
")",
"or",
"isinstance",
"(",
"v",
",",
"int",
")",
")",
":",
"is_list_all_float",
"=",
"False",
"if",
"is_list_all_int",
":",
"if",
"dtype",
".",
"is_integer",
":",
"return",
"_RealValuedColumn",
"(",
"column_name",
",",
"dimension",
",",
"default_value",
",",
"dtype",
")",
"elif",
"dtype",
".",
"is_floating",
":",
"default_value",
"=",
"[",
"float",
"(",
"v",
")",
"for",
"v",
"in",
"default_value",
"]",
"return",
"_RealValuedColumn",
"(",
"column_name",
",",
"dimension",
",",
"default_value",
",",
"dtype",
")",
"if",
"is_list_all_float",
":",
"if",
"dtype",
".",
"is_floating",
"and",
"(",
"not",
"dtype",
".",
"is_integer",
")",
":",
"default_value",
"=",
"[",
"float",
"(",
"v",
")",
"for",
"v",
"in",
"default_value",
"]",
"return",
"_RealValuedColumn",
"(",
"column_name",
",",
"dimension",
",",
"default_value",
",",
"dtype",
")",
"raise",
"TypeError",
"(",
"\"default_value must be compatible with dtype. \"",
"\"default_value: {}, dtype: {}, column_name: {}\"",
".",
"format",
"(",
"default_value",
",",
"dtype",
",",
"column_name",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py#L909-L998 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlLinkEvent.__init__ | (self, *args, **kwargs) | __init__(self, int id, HtmlLinkInfo linkinfo) -> HtmlLinkEvent | __init__(self, int id, HtmlLinkInfo linkinfo) -> HtmlLinkEvent | [
"__init__",
"(",
"self",
"int",
"id",
"HtmlLinkInfo",
"linkinfo",
")",
"-",
">",
"HtmlLinkEvent"
] | def __init__(self, *args, **kwargs):
"""__init__(self, int id, HtmlLinkInfo linkinfo) -> HtmlLinkEvent"""
_html.HtmlLinkEvent_swiginit(self,_html.new_HtmlLinkEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_html",
".",
"HtmlLinkEvent_swiginit",
"(",
"self",
",",
"_html",
".",
"new_HtmlLinkEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1716-L1718 |
||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py | python | Base.Detect | (self, progs) | return None | Return the first available program in progs. | Return the first available program in progs. | [
"Return",
"the",
"first",
"available",
"program",
"in",
"progs",
"."
] | def Detect(self, progs):
"""Return the first available program in progs.
"""
if not SCons.Util.is_List(progs):
progs = [ progs ]
for prog in progs:
path = self.WhereIs(prog)
if path: return prog
return None | [
"def",
"Detect",
"(",
"self",
",",
"progs",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"progs",
")",
":",
"progs",
"=",
"[",
"progs",
"]",
"for",
"prog",
"in",
"progs",
":",
"path",
"=",
"self",
".",
"WhereIs",
"(",
"prog",
")",
"if",
"path",
":",
"return",
"prog",
"return",
"None"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py#L1486-L1494 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | PickerBase.IsTextCtrlGrowable | (*args, **kwargs) | return _controls_.PickerBase_IsTextCtrlGrowable(*args, **kwargs) | IsTextCtrlGrowable(self) -> bool | IsTextCtrlGrowable(self) -> bool | [
"IsTextCtrlGrowable",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsTextCtrlGrowable(*args, **kwargs):
"""IsTextCtrlGrowable(self) -> bool"""
return _controls_.PickerBase_IsTextCtrlGrowable(*args, **kwargs) | [
"def",
"IsTextCtrlGrowable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"PickerBase_IsTextCtrlGrowable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L6790-L6792 |