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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | prj/app/prj.py | python | valid_entity_name | (name) | return not any([bad_char in name for bad_char in '/\\']) | Return true if the name is a valid entity name.
Entity names can not contain forward slash or backslash characters. | Return true if the name is a valid entity name. | [
"Return",
"true",
"if",
"the",
"name",
"is",
"a",
"valid",
"entity",
"name",
"."
] | def valid_entity_name(name):
"""Return true if the name is a valid entity name.
Entity names can not contain forward slash or backslash characters.
"""
return not any([bad_char in name for bad_char in '/\\']) | [
"def",
"valid_entity_name",
"(",
"name",
")",
":",
"return",
"not",
"any",
"(",
"[",
"bad_char",
"in",
"name",
"for",
"bad_char",
"in",
"'/\\\\'",
"]",
")"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/prj/app/prj.py#L187-L193 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/distribute_lookup_table.py | python | find_distributed_lookup_table_inputs | (program, table_name) | return inputs | Find input variable of distribute lookup table in program.
We only support one distribute table now.
Args:
program(Program): given program, locate distributed lookup table
table_name(str): given table name that is found beforehand
Returns:
inputs | Find input variable of distribute lookup table in program.
We only support one distribute table now.
Args:
program(Program): given program, locate distributed lookup table
table_name(str): given table name that is found beforehand
Returns:
inputs | [
"Find",
"input",
"variable",
"of",
"distribute",
"lookup",
"table",
"in",
"program",
".",
"We",
"only",
"support",
"one",
"distribute",
"table",
"now",
".",
"Args",
":",
"program",
"(",
"Program",
")",
":",
"given",
"program",
"locate",
"distributed",
"lookup",
"table",
"table_name",
"(",
"str",
")",
":",
"given",
"table",
"name",
"that",
"is",
"found",
"beforehand",
"Returns",
":",
"inputs"
] | def find_distributed_lookup_table_inputs(program, table_name):
"""
Find input variable of distribute lookup table in program.
We only support one distribute table now.
Args:
program(Program): given program, locate distributed lookup table
table_name(str): given table name that is found beforehand
Returns:
inputs
"""
local_vars = program.current_block().vars
inputs = []
for op in program.global_block().ops:
if op.type == LOOKUP_TABLE_TYPE:
if table_name == op.input("W")[0]:
inputs.extend([local_vars[name] for name in op.input("Ids")])
return inputs | [
"def",
"find_distributed_lookup_table_inputs",
"(",
"program",
",",
"table_name",
")",
":",
"local_vars",
"=",
"program",
".",
"current_block",
"(",
")",
".",
"vars",
"inputs",
"=",
"[",
"]",
"for",
"op",
"in",
"program",
".",
"global_block",
"(",
")",
".",
"ops",
":",
"if",
"op",
".",
"type",
"==",
"LOOKUP_TABLE_TYPE",
":",
"if",
"table_name",
"==",
"op",
".",
"input",
"(",
"\"W\"",
")",
"[",
"0",
"]",
":",
"inputs",
".",
"extend",
"(",
"[",
"local_vars",
"[",
"name",
"]",
"for",
"name",
"in",
"op",
".",
"input",
"(",
"\"Ids\"",
")",
"]",
")",
"return",
"inputs"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/distribute_lookup_table.py#L18-L34 | |
HackWebRTC/webrtc | 7abfc990c00ab35090fff285fcf635d1d7892433 | tools_webrtc/android/build_aar.py | python | _GetOutputDirectory | (build_dir, arch) | return os.path.join(build_dir, arch) | Returns the GN output directory for the target architecture. | Returns the GN output directory for the target architecture. | [
"Returns",
"the",
"GN",
"output",
"directory",
"for",
"the",
"target",
"architecture",
"."
] | def _GetOutputDirectory(build_dir, arch):
"""Returns the GN output directory for the target architecture."""
return os.path.join(build_dir, arch) | [
"def",
"_GetOutputDirectory",
"(",
"build_dir",
",",
"arch",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"arch",
")"
] | https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/tools_webrtc/android/build_aar.py#L114-L116 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/opset6/ops.py | python | assign | (new_value: NodeInput, variable_id: str, name: Optional[str] = None) | return _get_node_factory_opset6().create(
"Assign",
[as_node(new_value)],
{"variable_id": variable_id}
) | Return a node which produces the Assign operation.
:param new_value: Node producing a value to be assigned to a variable.
:param variable_id: Id of a variable to be updated.
:param name: Optional name for output node.
:return: Assign node | Return a node which produces the Assign operation. | [
"Return",
"a",
"node",
"which",
"produces",
"the",
"Assign",
"operation",
"."
] | def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -> Node:
"""Return a node which produces the Assign operation.
:param new_value: Node producing a value to be assigned to a variable.
:param variable_id: Id of a variable to be updated.
:param name: Optional name for output node.
:return: Assign node
"""
return _get_node_factory_opset6().create(
"Assign",
[as_node(new_value)],
{"variable_id": variable_id}
) | [
"def",
"assign",
"(",
"new_value",
":",
"NodeInput",
",",
"variable_id",
":",
"str",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Node",
":",
"return",
"_get_node_factory_opset6",
"(",
")",
".",
"create",
"(",
"\"Assign\"",
",",
"[",
"as_node",
"(",
"new_value",
")",
"]",
",",
"{",
"\"variable_id\"",
":",
"variable_id",
"}",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset6/ops.py#L135-L147 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/convert_to_constants.py | python | _get_tensor_name | (name) | return name.split(":")[0] | Returns the name of the input tensor.
Args:
name: str
Returns:
str | Returns the name of the input tensor. | [
"Returns",
"the",
"name",
"of",
"the",
"input",
"tensor",
"."
] | def _get_tensor_name(name):
"""Returns the name of the input tensor.
Args:
name: str
Returns:
str
"""
return name.split(":")[0] | [
"def",
"_get_tensor_name",
"(",
"name",
")",
":",
"return",
"name",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/convert_to_constants.py#L116-L125 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/tools/grokdump.py | python | InspectionShell.do_s | (self, word) | Search for a given word in available memory regions. The given word
is expanded to full pointer size and searched at aligned as well as
un-aligned memory locations. Use 'sa' to search aligned locations
only. | Search for a given word in available memory regions. The given word
is expanded to full pointer size and searched at aligned as well as
un-aligned memory locations. Use 'sa' to search aligned locations
only. | [
"Search",
"for",
"a",
"given",
"word",
"in",
"available",
"memory",
"regions",
".",
"The",
"given",
"word",
"is",
"expanded",
"to",
"full",
"pointer",
"size",
"and",
"searched",
"at",
"aligned",
"as",
"well",
"as",
"un",
"-",
"aligned",
"memory",
"locations",
".",
"Use",
"sa",
"to",
"search",
"aligned",
"locations",
"only",
"."
] | def do_s(self, word):
"""
Search for a given word in available memory regions. The given word
is expanded to full pointer size and searched at aligned as well as
un-aligned memory locations. Use 'sa' to search aligned locations
only.
"""
try:
word = int(word, 0)
except ValueError:
print "Malformed word, prefix with '0x' to use hexadecimal format."
return
print "Searching for word %d/0x%s:" % (word, self.reader.FormatIntPtr(word))
self.reader.FindWord(word) | [
"def",
"do_s",
"(",
"self",
",",
"word",
")",
":",
"try",
":",
"word",
"=",
"int",
"(",
"word",
",",
"0",
")",
"except",
"ValueError",
":",
"print",
"\"Malformed word, prefix with '0x' to use hexadecimal format.\"",
"return",
"print",
"\"Searching for word %d/0x%s:\"",
"%",
"(",
"word",
",",
"self",
".",
"reader",
".",
"FormatIntPtr",
"(",
"word",
")",
")",
"self",
".",
"reader",
".",
"FindWord",
"(",
"word",
")"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/tools/grokdump.py#L2013-L2026 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site.py | python | enablerlcompleter | () | Enable default readline configuration on interactive prompts, by
registering a sys.__interactivehook__.
If the readline module can be imported, the hook will set the Tab key
as completion key and register ~/.python_history as history file.
This can be overridden in the sitecustomize or usercustomize module,
or in a PYTHONSTARTUP file. | Enable default readline configuration on interactive prompts, by
registering a sys.__interactivehook__. | [
"Enable",
"default",
"readline",
"configuration",
"on",
"interactive",
"prompts",
"by",
"registering",
"a",
"sys",
".",
"__interactivehook__",
"."
] | def enablerlcompleter():
"""Enable default readline configuration on interactive prompts, by
registering a sys.__interactivehook__.
If the readline module can be imported, the hook will set the Tab key
as completion key and register ~/.python_history as history file.
This can be overridden in the sitecustomize or usercustomize module,
or in a PYTHONSTARTUP file.
"""
def register_readline():
import atexit
try:
import readline
import rlcompleter
except ImportError:
return
# Reading the initialization (config) file may not be enough to set a
# completion key, so we set one first and then read the file.
readline_doc = getattr(readline, '__doc__', '')
if readline_doc is not None and 'libedit' in readline_doc:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
try:
readline.read_init_file()
except OSError:
# An OSError here could have many causes, but the most likely one
# is that there's no .inputrc file (or .editrc file in the case of
# Mac OS X + libedit) in the expected location. In that case, we
# want to ignore the exception.
pass
if readline.get_current_history_length() == 0:
# If no history was loaded, default to .python_history.
# The guard is necessary to avoid doubling history size at
# each interpreter exit when readline was already configured
# through a PYTHONSTARTUP hook, see:
# http://bugs.python.org/issue5845#msg198636
history = os.path.join(os.path.expanduser('~'),
'.python_history')
try:
readline.read_history_file(history)
except OSError:
pass
def write_history():
try:
readline.write_history_file(history)
except (FileNotFoundError, PermissionError):
# home directory does not exist or is not writable
# https://bugs.python.org/issue19891
pass
atexit.register(write_history)
sys.__interactivehook__ = register_readline | [
"def",
"enablerlcompleter",
"(",
")",
":",
"def",
"register_readline",
"(",
")",
":",
"import",
"atexit",
"try",
":",
"import",
"readline",
"import",
"rlcompleter",
"except",
"ImportError",
":",
"return",
"# Reading the initialization (config) file may not be enough to set a",
"# completion key, so we set one first and then read the file.",
"readline_doc",
"=",
"getattr",
"(",
"readline",
",",
"'__doc__'",
",",
"''",
")",
"if",
"readline_doc",
"is",
"not",
"None",
"and",
"'libedit'",
"in",
"readline_doc",
":",
"readline",
".",
"parse_and_bind",
"(",
"'bind ^I rl_complete'",
")",
"else",
":",
"readline",
".",
"parse_and_bind",
"(",
"'tab: complete'",
")",
"try",
":",
"readline",
".",
"read_init_file",
"(",
")",
"except",
"OSError",
":",
"# An OSError here could have many causes, but the most likely one",
"# is that there's no .inputrc file (or .editrc file in the case of",
"# Mac OS X + libedit) in the expected location. In that case, we",
"# want to ignore the exception.",
"pass",
"if",
"readline",
".",
"get_current_history_length",
"(",
")",
"==",
"0",
":",
"# If no history was loaded, default to .python_history.",
"# The guard is necessary to avoid doubling history size at",
"# each interpreter exit when readline was already configured",
"# through a PYTHONSTARTUP hook, see:",
"# http://bugs.python.org/issue5845#msg198636",
"history",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.python_history'",
")",
"try",
":",
"readline",
".",
"read_history_file",
"(",
"history",
")",
"except",
"OSError",
":",
"pass",
"def",
"write_history",
"(",
")",
":",
"try",
":",
"readline",
".",
"write_history_file",
"(",
"history",
")",
"except",
"(",
"FileNotFoundError",
",",
"PermissionError",
")",
":",
"# home directory does not exist or is not writable",
"# https://bugs.python.org/issue19891",
"pass",
"atexit",
".",
"register",
"(",
"write_history",
")",
"sys",
".",
"__interactivehook__",
"=",
"register_readline"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site.py#L396-L453 | ||
etternagame/etterna | 8775f74ac9c353320128609d4b4150672e9a6d04 | extern/crashpad/buildtools/checkdeps/proto_checker.py | python | ProtoChecker.IsProtoFile | (file_path) | return os.path.splitext(file_path)[1] in ProtoChecker.EXTENSIONS | Returns True iff the given path ends in one of the extensions
handled by this checker. | Returns True iff the given path ends in one of the extensions
handled by this checker. | [
"Returns",
"True",
"iff",
"the",
"given",
"path",
"ends",
"in",
"one",
"of",
"the",
"extensions",
"handled",
"by",
"this",
"checker",
"."
] | def IsProtoFile(file_path):
"""Returns True iff the given path ends in one of the extensions
handled by this checker.
"""
return os.path.splitext(file_path)[1] in ProtoChecker.EXTENSIONS | [
"def",
"IsProtoFile",
"(",
"file_path",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"file_path",
")",
"[",
"1",
"]",
"in",
"ProtoChecker",
".",
"EXTENSIONS"
] | https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/buildtools/checkdeps/proto_checker.py#L110-L114 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/bindings/python/llvm/object.py | python | Section.has_symbol | (self, symbol) | return lib.LLVMGetSectionContainsSymbol(self, symbol) | Returns whether a Symbol instance is present in this Section. | Returns whether a Symbol instance is present in this Section. | [
"Returns",
"whether",
"a",
"Symbol",
"instance",
"is",
"present",
"in",
"this",
"Section",
"."
] | def has_symbol(self, symbol):
"""Returns whether a Symbol instance is present in this Section."""
if self.expired:
raise Exception('Section instance has expired.')
assert isinstance(symbol, Symbol)
return lib.LLVMGetSectionContainsSymbol(self, symbol) | [
"def",
"has_symbol",
"(",
"self",
",",
"symbol",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Section instance has expired.'",
")",
"assert",
"isinstance",
"(",
"symbol",
",",
"Symbol",
")",
"return",
"lib",
".",
"LLVMGetSectionContainsSymbol",
"(",
"self",
",",
"symbol",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/bindings/python/llvm/object.py#L231-L237 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Misc._grid_configure | (self, command, index, cnf, kw) | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def _grid_configure(self, command, index, cnf, kw):
"""Internal function."""
if isinstance(cnf, str) and not kw:
if cnf[-1:] == '_':
cnf = cnf[:-1]
if cnf[:1] != '-':
cnf = '-'+cnf
options = (cnf,)
else:
options = self._options(cnf, kw)
if not options:
return _splitdict(
self.tk,
self.tk.call('grid', command, self._w, index),
conv=self._gridconvvalue)
res = self.tk.call(
('grid', command, self._w, index)
+ options)
if len(options) == 1:
return self._gridconvvalue(res) | [
"def",
"_grid_configure",
"(",
"self",
",",
"command",
",",
"index",
",",
"cnf",
",",
"kw",
")",
":",
"if",
"isinstance",
"(",
"cnf",
",",
"str",
")",
"and",
"not",
"kw",
":",
"if",
"cnf",
"[",
"-",
"1",
":",
"]",
"==",
"'_'",
":",
"cnf",
"=",
"cnf",
"[",
":",
"-",
"1",
"]",
"if",
"cnf",
"[",
":",
"1",
"]",
"!=",
"'-'",
":",
"cnf",
"=",
"'-'",
"+",
"cnf",
"options",
"=",
"(",
"cnf",
",",
")",
"else",
":",
"options",
"=",
"self",
".",
"_options",
"(",
"cnf",
",",
"kw",
")",
"if",
"not",
"options",
":",
"return",
"_splitdict",
"(",
"self",
".",
"tk",
",",
"self",
".",
"tk",
".",
"call",
"(",
"'grid'",
",",
"command",
",",
"self",
".",
"_w",
",",
"index",
")",
",",
"conv",
"=",
"self",
".",
"_gridconvvalue",
")",
"res",
"=",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"'grid'",
",",
"command",
",",
"self",
".",
"_w",
",",
"index",
")",
"+",
"options",
")",
"if",
"len",
"(",
"options",
")",
"==",
"1",
":",
"return",
"self",
".",
"_gridconvvalue",
"(",
"res",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L1578-L1597 | ||
bilibili/biliobs | 573613dc3b2b63fe7c1506cc94717609a2c52c0c | base/android/jni_generator/jni_generator.py | python | JniParams.SetJarJarMappings | (mappings) | Parse jarjar mappings from a string. | Parse jarjar mappings from a string. | [
"Parse",
"jarjar",
"mappings",
"from",
"a",
"string",
"."
] | def SetJarJarMappings(mappings):
"""Parse jarjar mappings from a string."""
JniParams._remappings = []
for line in mappings.splitlines():
rule = line.split()
if rule[0] != 'rule':
continue
_, src, dest = rule
src = src.replace('.', '/')
dest = dest.replace('.', '/')
if src.endswith('**'):
src_real_name = src[:-2]
else:
assert not '*' in src
src_real_name = src
if dest.endswith('@0'):
JniParams._remappings.append((src, dest[:-2] + src_real_name))
elif dest.endswith('@1'):
assert '**' in src
JniParams._remappings.append((src, dest[:-2]))
else:
assert not '@' in dest
JniParams._remappings.append((src, dest)) | [
"def",
"SetJarJarMappings",
"(",
"mappings",
")",
":",
"JniParams",
".",
"_remappings",
"=",
"[",
"]",
"for",
"line",
"in",
"mappings",
".",
"splitlines",
"(",
")",
":",
"rule",
"=",
"line",
".",
"split",
"(",
")",
"if",
"rule",
"[",
"0",
"]",
"!=",
"'rule'",
":",
"continue",
"_",
",",
"src",
",",
"dest",
"=",
"rule",
"src",
"=",
"src",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"dest",
"=",
"dest",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"if",
"src",
".",
"endswith",
"(",
"'**'",
")",
":",
"src_real_name",
"=",
"src",
"[",
":",
"-",
"2",
"]",
"else",
":",
"assert",
"not",
"'*'",
"in",
"src",
"src_real_name",
"=",
"src",
"if",
"dest",
".",
"endswith",
"(",
"'@0'",
")",
":",
"JniParams",
".",
"_remappings",
".",
"append",
"(",
"(",
"src",
",",
"dest",
"[",
":",
"-",
"2",
"]",
"+",
"src_real_name",
")",
")",
"elif",
"dest",
".",
"endswith",
"(",
"'@1'",
")",
":",
"assert",
"'**'",
"in",
"src",
"JniParams",
".",
"_remappings",
".",
"append",
"(",
"(",
"src",
",",
"dest",
"[",
":",
"-",
"2",
"]",
")",
")",
"else",
":",
"assert",
"not",
"'@'",
"in",
"dest",
"JniParams",
".",
"_remappings",
".",
"append",
"(",
"(",
"src",
",",
"dest",
")",
")"
] | https://github.com/bilibili/biliobs/blob/573613dc3b2b63fe7c1506cc94717609a2c52c0c/base/android/jni_generator/jni_generator.py#L379-L402 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/internal/wire_format.py | python | TagByteSize | (field_number) | return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) | Returns the bytes required to serialize a tag with this field number. | Returns the bytes required to serialize a tag with this field number. | [
"Returns",
"the",
"bytes",
"required",
"to",
"serialize",
"a",
"tag",
"with",
"this",
"field",
"number",
"."
] | def TagByteSize(field_number):
"""Returns the bytes required to serialize a tag with this field number."""
# Just pass in type 0, since the type won't affect the tag+type size.
return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) | [
"def",
"TagByteSize",
"(",
"field_number",
")",
":",
"# Just pass in type 0, since the type won't affect the tag+type size.",
"return",
"_VarUInt64ByteSizeNoTag",
"(",
"PackTag",
"(",
"field_number",
",",
"0",
")",
")"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/wire_format.py#L224-L227 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/struct_types.py | python | _CommandWithNamespaceTypeInfo.__init__ | (self, command) | Create a _CommandWithNamespaceTypeInfo instance. | Create a _CommandWithNamespaceTypeInfo instance. | [
"Create",
"a",
"_CommandWithNamespaceTypeInfo",
"instance",
"."
] | def __init__(self, command):
# type: (ast.Command) -> None
"""Create a _CommandWithNamespaceTypeInfo instance."""
self._command = command
super(_CommandWithNamespaceTypeInfo, self).__init__(command) | [
"def",
"__init__",
"(",
"self",
",",
"command",
")",
":",
"# type: (ast.Command) -> None",
"self",
".",
"_command",
"=",
"command",
"super",
"(",
"_CommandWithNamespaceTypeInfo",
",",
"self",
")",
".",
"__init__",
"(",
"command",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/struct_types.py#L367-L372 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/tabart.py | python | AuiSimpleTabArt.SetSizingInfo | (self, tab_ctrl_size, tab_count, minMaxTabWidth) | Sets the tab sizing information.
:param Size `tab_ctrl_size`: the size of the tab control area;
:param integer `tab_count`: the number of tabs;
:param tuple `minMaxTabWidth`: a tuple containing the minimum and maximum tab widths
to be used when the ``AUI_NB_TAB_FIXED_WIDTH`` style is active. | Sets the tab sizing information.
:param Size `tab_ctrl_size`: the size of the tab control area;
:param integer `tab_count`: the number of tabs;
:param tuple `minMaxTabWidth`: a tuple containing the minimum and maximum tab widths
to be used when the ``AUI_NB_TAB_FIXED_WIDTH`` style is active. | [
"Sets",
"the",
"tab",
"sizing",
"information",
".",
":",
"param",
"Size",
"tab_ctrl_size",
":",
"the",
"size",
"of",
"the",
"tab",
"control",
"area",
";",
":",
"param",
"integer",
"tab_count",
":",
"the",
"number",
"of",
"tabs",
";",
":",
"param",
"tuple",
"minMaxTabWidth",
":",
"a",
"tuple",
"containing",
"the",
"minimum",
"and",
"maximum",
"tab",
"widths",
"to",
"be",
"used",
"when",
"the",
"AUI_NB_TAB_FIXED_WIDTH",
"style",
"is",
"active",
"."
] | def SetSizingInfo(self, tab_ctrl_size, tab_count, minMaxTabWidth):
"""
Sets the tab sizing information.
:param Size `tab_ctrl_size`: the size of the tab control area;
:param integer `tab_count`: the number of tabs;
:param tuple `minMaxTabWidth`: a tuple containing the minimum and maximum tab widths
to be used when the ``AUI_NB_TAB_FIXED_WIDTH`` style is active.
"""
self._fixed_tab_width = 100
minTabWidth, maxTabWidth = minMaxTabWidth
tot_width = tab_ctrl_size.x - self.GetIndentSize() - 4
if self._agwFlags & AUI_NB_CLOSE_BUTTON:
tot_width -= self._active_close_bmp.GetWidth()
if self._agwFlags & AUI_NB_WINDOWLIST_BUTTON:
tot_width -= self._active_windowlist_bmp.GetWidth()
if tab_count > 0:
self._fixed_tab_width = tot_width/tab_count
if self._fixed_tab_width < 100:
self._fixed_tab_width = 100
if self._fixed_tab_width > tot_width/2:
self._fixed_tab_width = tot_width/2
if self._fixed_tab_width > 220:
self._fixed_tab_width = 220
if minTabWidth > -1:
self._fixed_tab_width = max(self._fixed_tab_width, minTabWidth)
if maxTabWidth > -1:
self._fixed_tab_width = min(self._fixed_tab_width, maxTabWidth)
self._tab_ctrl_height = tab_ctrl_size.y | [
"def",
"SetSizingInfo",
"(",
"self",
",",
"tab_ctrl_size",
",",
"tab_count",
",",
"minMaxTabWidth",
")",
":",
"self",
".",
"_fixed_tab_width",
"=",
"100",
"minTabWidth",
",",
"maxTabWidth",
"=",
"minMaxTabWidth",
"tot_width",
"=",
"tab_ctrl_size",
".",
"x",
"-",
"self",
".",
"GetIndentSize",
"(",
")",
"-",
"4",
"if",
"self",
".",
"_agwFlags",
"&",
"AUI_NB_CLOSE_BUTTON",
":",
"tot_width",
"-=",
"self",
".",
"_active_close_bmp",
".",
"GetWidth",
"(",
")",
"if",
"self",
".",
"_agwFlags",
"&",
"AUI_NB_WINDOWLIST_BUTTON",
":",
"tot_width",
"-=",
"self",
".",
"_active_windowlist_bmp",
".",
"GetWidth",
"(",
")",
"if",
"tab_count",
">",
"0",
":",
"self",
".",
"_fixed_tab_width",
"=",
"tot_width",
"/",
"tab_count",
"if",
"self",
".",
"_fixed_tab_width",
"<",
"100",
":",
"self",
".",
"_fixed_tab_width",
"=",
"100",
"if",
"self",
".",
"_fixed_tab_width",
">",
"tot_width",
"/",
"2",
":",
"self",
".",
"_fixed_tab_width",
"=",
"tot_width",
"/",
"2",
"if",
"self",
".",
"_fixed_tab_width",
">",
"220",
":",
"self",
".",
"_fixed_tab_width",
"=",
"220",
"if",
"minTabWidth",
">",
"-",
"1",
":",
"self",
".",
"_fixed_tab_width",
"=",
"max",
"(",
"self",
".",
"_fixed_tab_width",
",",
"minTabWidth",
")",
"if",
"maxTabWidth",
">",
"-",
"1",
":",
"self",
".",
"_fixed_tab_width",
"=",
"min",
"(",
"self",
".",
"_fixed_tab_width",
",",
"maxTabWidth",
")",
"self",
".",
"_tab_ctrl_height",
"=",
"tab_ctrl_size",
".",
"y"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/tabart.py#L1090-L1127 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/tools/grokdump.py | python | InspectionShell.do_lm | (self, arg) | return self.do_list_modules(arg) | see list_modules | see list_modules | [
"see",
"list_modules"
] | def do_lm(self, arg):
""" see list_modules """
return self.do_list_modules(arg) | [
"def",
"do_lm",
"(",
"self",
",",
"arg",
")",
":",
"return",
"self",
".",
"do_list_modules",
"(",
"arg",
")"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/tools/grokdump.py#L3523-L3525 | |
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | CursorKind.is_attribute | (self) | return conf.lib.clang_isAttribute(self) | Test if this is an attribute kind. | Test if this is an attribute kind. | [
"Test",
"if",
"this",
"is",
"an",
"attribute",
"kind",
"."
] | def is_attribute(self):
"""Test if this is an attribute kind."""
return conf.lib.clang_isAttribute(self) | [
"def",
"is_attribute",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isAttribute",
"(",
"self",
")"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L535-L537 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsCatCs | (code) | return ret | Check whether the character is part of Cs UCS Category | Check whether the character is part of Cs UCS Category | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Cs",
"UCS",
"Category"
] | def uCSIsCatCs(code):
"""Check whether the character is part of Cs UCS Category """
ret = libxml2mod.xmlUCSIsCatCs(code)
return ret | [
"def",
"uCSIsCatCs",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCatCs",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1478-L1481 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/ignite/python/ops/ignite_dataset_ops.py | python | TcpClient.read_data | (self, length) | return data_buffer | Reads the specified number of bytes and returns them as a buffer. | Reads the specified number of bytes and returns them as a buffer. | [
"Reads",
"the",
"specified",
"number",
"of",
"bytes",
"and",
"returns",
"them",
"as",
"a",
"buffer",
"."
] | def read_data(self, length):
"""Reads the specified number of bytes and returns them as a buffer."""
data_buffer = None
rem = length
while rem > 0:
buf = self.sock.recv(rem)
rem = rem - len(buf)
if data_buffer is None:
data_buffer = buf
else:
data_buffer += buf
return data_buffer | [
"def",
"read_data",
"(",
"self",
",",
"length",
")",
":",
"data_buffer",
"=",
"None",
"rem",
"=",
"length",
"while",
"rem",
">",
"0",
":",
"buf",
"=",
"self",
".",
"sock",
".",
"recv",
"(",
"rem",
")",
"rem",
"=",
"rem",
"-",
"len",
"(",
"buf",
")",
"if",
"data_buffer",
"is",
"None",
":",
"data_buffer",
"=",
"buf",
"else",
":",
"data_buffer",
"+=",
"buf",
"return",
"data_buffer"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/ignite/python/ops/ignite_dataset_ops.py#L163-L174 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/jedi/jedi/parser_utils.py | python | get_following_comment_same_line | (node) | return comment | returns (as string) any comment that appears on the same line,
after the node, including the # | returns (as string) any comment that appears on the same line,
after the node, including the # | [
"returns",
"(",
"as",
"string",
")",
"any",
"comment",
"that",
"appears",
"on",
"the",
"same",
"line",
"after",
"the",
"node",
"including",
"the",
"#"
] | def get_following_comment_same_line(node):
"""
returns (as string) any comment that appears on the same line,
after the node, including the #
"""
try:
if node.type == 'for_stmt':
whitespace = node.children[5].get_first_leaf().prefix
elif node.type == 'with_stmt':
whitespace = node.children[3].get_first_leaf().prefix
elif node.type == 'funcdef':
# actually on the next line
whitespace = node.children[4].get_first_leaf().get_next_leaf().prefix
else:
whitespace = node.get_last_leaf().get_next_leaf().prefix
except AttributeError:
return None
except ValueError:
# TODO in some particular cases, the tree doesn't seem to be linked
# correctly
return None
if "#" not in whitespace:
return None
comment = whitespace[whitespace.index("#"):]
if "\r" in comment:
comment = comment[:comment.index("\r")]
if "\n" in comment:
comment = comment[:comment.index("\n")]
return comment | [
"def",
"get_following_comment_same_line",
"(",
"node",
")",
":",
"try",
":",
"if",
"node",
".",
"type",
"==",
"'for_stmt'",
":",
"whitespace",
"=",
"node",
".",
"children",
"[",
"5",
"]",
".",
"get_first_leaf",
"(",
")",
".",
"prefix",
"elif",
"node",
".",
"type",
"==",
"'with_stmt'",
":",
"whitespace",
"=",
"node",
".",
"children",
"[",
"3",
"]",
".",
"get_first_leaf",
"(",
")",
".",
"prefix",
"elif",
"node",
".",
"type",
"==",
"'funcdef'",
":",
"# actually on the next line",
"whitespace",
"=",
"node",
".",
"children",
"[",
"4",
"]",
".",
"get_first_leaf",
"(",
")",
".",
"get_next_leaf",
"(",
")",
".",
"prefix",
"else",
":",
"whitespace",
"=",
"node",
".",
"get_last_leaf",
"(",
")",
".",
"get_next_leaf",
"(",
")",
".",
"prefix",
"except",
"AttributeError",
":",
"return",
"None",
"except",
"ValueError",
":",
"# TODO in some particular cases, the tree doesn't seem to be linked",
"# correctly",
"return",
"None",
"if",
"\"#\"",
"not",
"in",
"whitespace",
":",
"return",
"None",
"comment",
"=",
"whitespace",
"[",
"whitespace",
".",
"index",
"(",
"\"#\"",
")",
":",
"]",
"if",
"\"\\r\"",
"in",
"comment",
":",
"comment",
"=",
"comment",
"[",
":",
"comment",
".",
"index",
"(",
"\"\\r\"",
")",
"]",
"if",
"\"\\n\"",
"in",
"comment",
":",
"comment",
"=",
"comment",
"[",
":",
"comment",
".",
"index",
"(",
"\"\\n\"",
")",
"]",
"return",
"comment"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/parser_utils.py#L206-L234 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/protobuf/python/google/protobuf/internal/python_message.py | python | _ExtensionDict.__init__ | (self, extended_message) | extended_message: Message instance for which we are the Extensions dict. | extended_message: Message instance for which we are the Extensions dict. | [
"extended_message",
":",
"Message",
"instance",
"for",
"which",
"we",
"are",
"the",
"Extensions",
"dict",
"."
] | def __init__(self, extended_message):
"""extended_message: Message instance for which we are the Extensions dict.
"""
self._extended_message = extended_message | [
"def",
"__init__",
"(",
"self",
",",
"extended_message",
")",
":",
"self",
".",
"_extended_message",
"=",
"extended_message"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/python_message.py#L1058-L1062 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/install.py | python | install._called_from_setup | (run_frame) | return (
caller_module == 'distutils.dist'
and info.function == 'run_commands'
) | Attempt to detect whether run() was called from setup() or by another
command. If called by setup(), the parent caller will be the
'run_command' method in 'distutils.dist', and *its* caller will be
the 'run_commands' method. If called any other way, the
immediate caller *might* be 'run_command', but it won't have been
called by 'run_commands'. Return True in that case or if a call stack
is unavailable. Return False otherwise. | Attempt to detect whether run() was called from setup() or by another
command. If called by setup(), the parent caller will be the
'run_command' method in 'distutils.dist', and *its* caller will be
the 'run_commands' method. If called any other way, the
immediate caller *might* be 'run_command', but it won't have been
called by 'run_commands'. Return True in that case or if a call stack
is unavailable. Return False otherwise. | [
"Attempt",
"to",
"detect",
"whether",
"run",
"()",
"was",
"called",
"from",
"setup",
"()",
"or",
"by",
"another",
"command",
".",
"If",
"called",
"by",
"setup",
"()",
"the",
"parent",
"caller",
"will",
"be",
"the",
"run_command",
"method",
"in",
"distutils",
".",
"dist",
"and",
"*",
"its",
"*",
"caller",
"will",
"be",
"the",
"run_commands",
"method",
".",
"If",
"called",
"any",
"other",
"way",
"the",
"immediate",
"caller",
"*",
"might",
"*",
"be",
"run_command",
"but",
"it",
"won",
"t",
"have",
"been",
"called",
"by",
"run_commands",
".",
"Return",
"True",
"in",
"that",
"case",
"or",
"if",
"a",
"call",
"stack",
"is",
"unavailable",
".",
"Return",
"False",
"otherwise",
"."
] | def _called_from_setup(run_frame):
"""
Attempt to detect whether run() was called from setup() or by another
command. If called by setup(), the parent caller will be the
'run_command' method in 'distutils.dist', and *its* caller will be
the 'run_commands' method. If called any other way, the
immediate caller *might* be 'run_command', but it won't have been
called by 'run_commands'. Return True in that case or if a call stack
is unavailable. Return False otherwise.
"""
if run_frame is None:
msg = "Call stack not available. bdist_* commands may fail."
warnings.warn(msg)
if platform.python_implementation() == 'IronPython':
msg = "For best results, pass -X:Frames to enable call stack."
warnings.warn(msg)
return True
res = inspect.getouterframes(run_frame)[2]
caller, = res[:1]
info = inspect.getframeinfo(caller)
caller_module = caller.f_globals.get('__name__', '')
return (
caller_module == 'distutils.dist'
and info.function == 'run_commands'
) | [
"def",
"_called_from_setup",
"(",
"run_frame",
")",
":",
"if",
"run_frame",
"is",
"None",
":",
"msg",
"=",
"\"Call stack not available. bdist_* commands may fail.\"",
"warnings",
".",
"warn",
"(",
"msg",
")",
"if",
"platform",
".",
"python_implementation",
"(",
")",
"==",
"'IronPython'",
":",
"msg",
"=",
"\"For best results, pass -X:Frames to enable call stack.\"",
"warnings",
".",
"warn",
"(",
"msg",
")",
"return",
"True",
"res",
"=",
"inspect",
".",
"getouterframes",
"(",
"run_frame",
")",
"[",
"2",
"]",
"caller",
",",
"=",
"res",
"[",
":",
"1",
"]",
"info",
"=",
"inspect",
".",
"getframeinfo",
"(",
"caller",
")",
"caller_module",
"=",
"caller",
".",
"f_globals",
".",
"get",
"(",
"'__name__'",
",",
"''",
")",
"return",
"(",
"caller_module",
"==",
"'distutils.dist'",
"and",
"info",
".",
"function",
"==",
"'run_commands'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/install.py#L70-L94 | |
ucla-vision/xivo | 1b97bf5a3124e62bf4920429af5bb91c7a6de876 | scripts/tum_rgbd_benchmark_tools/evaluate_rpe.py | python | find_closest_index | (L,t) | return best | Find the index of the closest value in a list.
Input:
L -- the list
t -- value to be found
Output:
index of the closest element | Find the index of the closest value in a list. | [
"Find",
"the",
"index",
"of",
"the",
"closest",
"value",
"in",
"a",
"list",
"."
] | def find_closest_index(L,t):
"""
Find the index of the closest value in a list.
Input:
L -- the list
t -- value to be found
Output:
index of the closest element
"""
beginning = 0
difference = abs(L[0] - t)
best = 0
end = len(L)
while beginning < end:
middle = int((end+beginning)/2)
if abs(L[middle] - t) < difference:
difference = abs(L[middle] - t)
best = middle
if t == L[middle]:
return middle
elif L[middle] > t:
end = middle
else:
beginning = middle + 1
return best | [
"def",
"find_closest_index",
"(",
"L",
",",
"t",
")",
":",
"beginning",
"=",
"0",
"difference",
"=",
"abs",
"(",
"L",
"[",
"0",
"]",
"-",
"t",
")",
"best",
"=",
"0",
"end",
"=",
"len",
"(",
"L",
")",
"while",
"beginning",
"<",
"end",
":",
"middle",
"=",
"int",
"(",
"(",
"end",
"+",
"beginning",
")",
"/",
"2",
")",
"if",
"abs",
"(",
"L",
"[",
"middle",
"]",
"-",
"t",
")",
"<",
"difference",
":",
"difference",
"=",
"abs",
"(",
"L",
"[",
"middle",
"]",
"-",
"t",
")",
"best",
"=",
"middle",
"if",
"t",
"==",
"L",
"[",
"middle",
"]",
":",
"return",
"middle",
"elif",
"L",
"[",
"middle",
"]",
">",
"t",
":",
"end",
"=",
"middle",
"else",
":",
"beginning",
"=",
"middle",
"+",
"1",
"return",
"best"
] | https://github.com/ucla-vision/xivo/blob/1b97bf5a3124e62bf4920429af5bb91c7a6de876/scripts/tum_rgbd_benchmark_tools/evaluate_rpe.py#L114-L140 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _ConvertSourcesToFilterHierarchy | (sources, prefix=None, excluded=None,
list_excluded=True, msvs_version=None) | return result | Converts a list split source file paths into a vcproj folder hierarchy.
Arguments:
sources: A list of source file paths split.
prefix: A list of source file path layers meant to apply to each of sources.
excluded: A set of excluded files.
msvs_version: A MSVSVersion object.
Returns:
A hierarchy of filenames and MSVSProject.Filter objects that matches the
layout of the source tree.
For example:
_ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']],
prefix=['joe'])
-->
[MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']),
MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])] | Converts a list split source file paths into a vcproj folder hierarchy. | [
"Converts",
"a",
"list",
"split",
"source",
"file",
"paths",
"into",
"a",
"vcproj",
"folder",
"hierarchy",
"."
] | def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None,
list_excluded=True, msvs_version=None):
"""Converts a list split source file paths into a vcproj folder hierarchy.
Arguments:
sources: A list of source file paths split.
prefix: A list of source file path layers meant to apply to each of sources.
excluded: A set of excluded files.
msvs_version: A MSVSVersion object.
Returns:
A hierarchy of filenames and MSVSProject.Filter objects that matches the
layout of the source tree.
For example:
_ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']],
prefix=['joe'])
-->
[MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']),
MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])]
"""
if not prefix: prefix = []
result = []
excluded_result = []
folders = OrderedDict()
# Gather files into the final result, excluded, or folders.
for s in sources:
if len(s) == 1:
filename = _NormalizedSource('\\'.join(prefix + s))
if filename in excluded:
excluded_result.append(filename)
else:
result.append(filename)
elif msvs_version and not msvs_version.UsesVcxproj():
# For MSVS 2008 and earlier, we need to process all files before walking
# the sub folders.
if not folders.get(s[0]):
folders[s[0]] = []
folders[s[0]].append(s[1:])
else:
contents = _ConvertSourcesToFilterHierarchy([s[1:]], prefix + [s[0]],
excluded=excluded,
list_excluded=list_excluded,
msvs_version=msvs_version)
contents = MSVSProject.Filter(s[0], contents=contents)
result.append(contents)
# Add a folder for excluded files.
if excluded_result and list_excluded:
excluded_folder = MSVSProject.Filter('_excluded_files',
contents=excluded_result)
result.append(excluded_folder)
if msvs_version and msvs_version.UsesVcxproj():
return result
# Populate all the folders.
for f in folders:
contents = _ConvertSourcesToFilterHierarchy(folders[f], prefix=prefix + [f],
excluded=excluded,
list_excluded=list_excluded,
msvs_version=msvs_version)
contents = MSVSProject.Filter(f, contents=contents)
result.append(contents)
return result | [
"def",
"_ConvertSourcesToFilterHierarchy",
"(",
"sources",
",",
"prefix",
"=",
"None",
",",
"excluded",
"=",
"None",
",",
"list_excluded",
"=",
"True",
",",
"msvs_version",
"=",
"None",
")",
":",
"if",
"not",
"prefix",
":",
"prefix",
"=",
"[",
"]",
"result",
"=",
"[",
"]",
"excluded_result",
"=",
"[",
"]",
"folders",
"=",
"OrderedDict",
"(",
")",
"# Gather files into the final result, excluded, or folders.",
"for",
"s",
"in",
"sources",
":",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"filename",
"=",
"_NormalizedSource",
"(",
"'\\\\'",
".",
"join",
"(",
"prefix",
"+",
"s",
")",
")",
"if",
"filename",
"in",
"excluded",
":",
"excluded_result",
".",
"append",
"(",
"filename",
")",
"else",
":",
"result",
".",
"append",
"(",
"filename",
")",
"elif",
"msvs_version",
"and",
"not",
"msvs_version",
".",
"UsesVcxproj",
"(",
")",
":",
"# For MSVS 2008 and earlier, we need to process all files before walking",
"# the sub folders.",
"if",
"not",
"folders",
".",
"get",
"(",
"s",
"[",
"0",
"]",
")",
":",
"folders",
"[",
"s",
"[",
"0",
"]",
"]",
"=",
"[",
"]",
"folders",
"[",
"s",
"[",
"0",
"]",
"]",
".",
"append",
"(",
"s",
"[",
"1",
":",
"]",
")",
"else",
":",
"contents",
"=",
"_ConvertSourcesToFilterHierarchy",
"(",
"[",
"s",
"[",
"1",
":",
"]",
"]",
",",
"prefix",
"+",
"[",
"s",
"[",
"0",
"]",
"]",
",",
"excluded",
"=",
"excluded",
",",
"list_excluded",
"=",
"list_excluded",
",",
"msvs_version",
"=",
"msvs_version",
")",
"contents",
"=",
"MSVSProject",
".",
"Filter",
"(",
"s",
"[",
"0",
"]",
",",
"contents",
"=",
"contents",
")",
"result",
".",
"append",
"(",
"contents",
")",
"# Add a folder for excluded files.",
"if",
"excluded_result",
"and",
"list_excluded",
":",
"excluded_folder",
"=",
"MSVSProject",
".",
"Filter",
"(",
"'_excluded_files'",
",",
"contents",
"=",
"excluded_result",
")",
"result",
".",
"append",
"(",
"excluded_folder",
")",
"if",
"msvs_version",
"and",
"msvs_version",
".",
"UsesVcxproj",
"(",
")",
":",
"return",
"result",
"# Populate all the folders.",
"for",
"f",
"in",
"folders",
":",
"contents",
"=",
"_ConvertSourcesToFilterHierarchy",
"(",
"folders",
"[",
"f",
"]",
",",
"prefix",
"=",
"prefix",
"+",
"[",
"f",
"]",
",",
"excluded",
"=",
"excluded",
",",
"list_excluded",
"=",
"list_excluded",
",",
"msvs_version",
"=",
"msvs_version",
")",
"contents",
"=",
"MSVSProject",
".",
"Filter",
"(",
"f",
",",
"contents",
"=",
"contents",
")",
"result",
".",
"append",
"(",
"contents",
")",
"return",
"result"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L179-L241 | |
p4lang/p4c | 3272e79369f20813cc1a555a5eb26f44432f84a4 | tools/stf/stf_parser.py | python | STFParser.p_match_list_many | (self, p) | match_list : match_list match | match_list : match_list match | [
"match_list",
":",
"match_list",
"match"
] | def p_match_list_many(self, p):
'match_list : match_list match'
p[0] = p[1] + [p[2]] | [
"def",
"p_match_list_many",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"]"
] | https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/stf/stf_parser.py#L225-L227 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/cpplint.py | python | FileInfo.Extension | (self) | return self.Split()[2] | File extension - text following the final period. | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period",
"."
] | def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2] | [
"def",
"Extension",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"2",
"]"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L1315-L1317 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/boost/boost_1_68_0/tools/build/src/build/project.py | python | ProjectRules.conditional | (self, condition, requirements) | Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
<define>DEBUG_EXCEPTION <define>DEBUG_TRACE ] ; | Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example: | [
"Calculates",
"conditional",
"requirements",
"for",
"multiple",
"requirements",
"at",
"once",
".",
"This",
"is",
"a",
"shorthand",
"to",
"be",
"reduce",
"duplication",
"and",
"to",
"keep",
"an",
"inline",
"declarative",
"syntax",
".",
"For",
"example",
":"
] | def conditional(self, condition, requirements):
"""Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
<define>DEBUG_EXCEPTION <define>DEBUG_TRACE ] ;
"""
assert is_iterable_typed(condition, basestring)
assert is_iterable_typed(requirements, basestring)
c = string.join(condition, ",")
if c.find(":") != -1:
return [c + r for r in requirements]
else:
return [c + ":" + r for r in requirements] | [
"def",
"conditional",
"(",
"self",
",",
"condition",
",",
"requirements",
")",
":",
"assert",
"is_iterable_typed",
"(",
"condition",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"requirements",
",",
"basestring",
")",
"c",
"=",
"string",
".",
"join",
"(",
"condition",
",",
"\",\"",
")",
"if",
"c",
".",
"find",
"(",
"\":\"",
")",
"!=",
"-",
"1",
":",
"return",
"[",
"c",
"+",
"r",
"for",
"r",
"in",
"requirements",
"]",
"else",
":",
"return",
"[",
"c",
"+",
"\":\"",
"+",
"r",
"for",
"r",
"in",
"requirements",
"]"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/project.py#L1262-L1276 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Context.divmod | (self, a, b) | Return (a // b, a % b).
>>> ExtendedContext.divmod(Decimal(8), Decimal(3))
(Decimal('2'), Decimal('2'))
>>> ExtendedContext.divmod(Decimal(8), Decimal(4))
(Decimal('2'), Decimal('0'))
>>> ExtendedContext.divmod(8, 4)
(Decimal('2'), Decimal('0'))
>>> ExtendedContext.divmod(Decimal(8), 4)
(Decimal('2'), Decimal('0'))
>>> ExtendedContext.divmod(8, Decimal(4))
(Decimal('2'), Decimal('0')) | Return (a // b, a % b). | [
"Return",
"(",
"a",
"//",
"b",
"a",
"%",
"b",
")",
"."
] | def divmod(self, a, b):
"""Return (a // b, a % b).
>>> ExtendedContext.divmod(Decimal(8), Decimal(3))
(Decimal('2'), Decimal('2'))
>>> ExtendedContext.divmod(Decimal(8), Decimal(4))
(Decimal('2'), Decimal('0'))
>>> ExtendedContext.divmod(8, 4)
(Decimal('2'), Decimal('0'))
>>> ExtendedContext.divmod(Decimal(8), 4)
(Decimal('2'), Decimal('0'))
>>> ExtendedContext.divmod(8, Decimal(4))
(Decimal('2'), Decimal('0'))
"""
a = _convert_other(a, raiseit=True)
r = a.__divmod__(b, context=self)
if r is NotImplemented:
raise TypeError("Unable to convert %s to Decimal" % b)
else:
return r | [
"def",
"divmod",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"r",
"=",
"a",
".",
"__divmod__",
"(",
"b",
",",
"context",
"=",
"self",
")",
"if",
"r",
"is",
"NotImplemented",
":",
"raise",
"TypeError",
"(",
"\"Unable to convert %s to Decimal\"",
"%",
"b",
")",
"else",
":",
"return",
"r"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L4244-L4263 | ||
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/tvm/intrin.py | python | log | (x) | return call_pure_intrin(_get_dtype(x), "log", x) | Take log of input x.
Parameters
----------
x : Expr
Input argument.
Returns
-------
y : Expr
The result. | Take log of input x. | [
"Take",
"log",
"of",
"input",
"x",
"."
] | def log(x):
"""Take log of input x.
Parameters
----------
x : Expr
Input argument.
Returns
-------
y : Expr
The result.
"""
return call_pure_intrin(_get_dtype(x), "log", x) | [
"def",
"log",
"(",
"x",
")",
":",
"return",
"call_pure_intrin",
"(",
"_get_dtype",
"(",
"x",
")",
",",
"\"log\"",
",",
"x",
")"
] | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/intrin.py#L249-L262 | |
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/framebuffer.py | python | Framebuffer.use | (self) | Bind the framebuffer. Sets the target for rendering commands. | Bind the framebuffer. Sets the target for rendering commands. | [
"Bind",
"the",
"framebuffer",
".",
"Sets",
"the",
"target",
"for",
"rendering",
"commands",
"."
] | def use(self) -> None:
'''
Bind the framebuffer. Sets the target for rendering commands.
'''
self.ctx.fbo = self
self.mglo.use() | [
"def",
"use",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"ctx",
".",
"fbo",
"=",
"self",
"self",
".",
"mglo",
".",
"use",
"(",
")"
] | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/framebuffer.py#L266-L272 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/nn_ops.py | python | avg_pool1d | (input, ksize, strides, padding, data_format="NWC", name=None) | Performs the average pooling on the input.
Each entry in `output` is the mean of the corresponding size `ksize`
window in `value`.
Note internally this op reshapes and uses the underlying 2d operation.
Args:
input: A 3-D `Tensor` of the format specified by `data_format`.
ksize: An int or list of `ints` that has length `1` or `3`. The size of the
window for each dimension of the input tensor.
strides: An int or list of `ints` that has length `1` or `3`. The stride of
the sliding window for each dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
[here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
for more information.
data_format: An optional string from: "NWC", "NCW". Defaults to "NWC".
name: A name for the operation (optional).
Returns:
A `Tensor` of format specified by `data_format`.
The max pooled output tensor. | Performs the average pooling on the input. | [
"Performs",
"the",
"average",
"pooling",
"on",
"the",
"input",
"."
] | def avg_pool1d(input, ksize, strides, padding, data_format="NWC", name=None): # pylint: disable=redefined-builtin
"""Performs the average pooling on the input.
Each entry in `output` is the mean of the corresponding size `ksize`
window in `value`.
Note internally this op reshapes and uses the underlying 2d operation.
Args:
input: A 3-D `Tensor` of the format specified by `data_format`.
ksize: An int or list of `ints` that has length `1` or `3`. The size of the
window for each dimension of the input tensor.
strides: An int or list of `ints` that has length `1` or `3`. The stride of
the sliding window for each dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
[here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2)
for more information.
data_format: An optional string from: "NWC", "NCW". Defaults to "NWC".
name: A name for the operation (optional).
Returns:
A `Tensor` of format specified by `data_format`.
The max pooled output tensor.
"""
with ops.name_scope(name, "AvgPool1D", [input]) as name:
if data_format is None:
data_format = "NWC"
channel_index = 1 if data_format.startswith("NC") else 2
ksize = [1] + _get_sequence(ksize, 1, channel_index, "ksize")
strides = [1] + _get_sequence(strides, 1, channel_index, "strides")
expanding_dim = 1 if data_format == "NWC" else 2
data_format = "NHWC" if data_format == "NWC" else "NCHW"
input = array_ops.expand_dims_v2(input, expanding_dim)
result = gen_nn_ops.avg_pool(
input,
ksize=ksize,
strides=strides,
padding=padding,
data_format=data_format,
name=name)
return array_ops.squeeze(result, expanding_dim) | [
"def",
"avg_pool1d",
"(",
"input",
",",
"ksize",
",",
"strides",
",",
"padding",
",",
"data_format",
"=",
"\"NWC\"",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"AvgPool1D\"",
",",
"[",
"input",
"]",
")",
"as",
"name",
":",
"if",
"data_format",
"is",
"None",
":",
"data_format",
"=",
"\"NWC\"",
"channel_index",
"=",
"1",
"if",
"data_format",
".",
"startswith",
"(",
"\"NC\"",
")",
"else",
"2",
"ksize",
"=",
"[",
"1",
"]",
"+",
"_get_sequence",
"(",
"ksize",
",",
"1",
",",
"channel_index",
",",
"\"ksize\"",
")",
"strides",
"=",
"[",
"1",
"]",
"+",
"_get_sequence",
"(",
"strides",
",",
"1",
",",
"channel_index",
",",
"\"strides\"",
")",
"expanding_dim",
"=",
"1",
"if",
"data_format",
"==",
"\"NWC\"",
"else",
"2",
"data_format",
"=",
"\"NHWC\"",
"if",
"data_format",
"==",
"\"NWC\"",
"else",
"\"NCHW\"",
"input",
"=",
"array_ops",
".",
"expand_dims_v2",
"(",
"input",
",",
"expanding_dim",
")",
"result",
"=",
"gen_nn_ops",
".",
"avg_pool",
"(",
"input",
",",
"ksize",
"=",
"ksize",
",",
"strides",
"=",
"strides",
",",
"padding",
"=",
"padding",
",",
"data_format",
"=",
"data_format",
",",
"name",
"=",
"name",
")",
"return",
"array_ops",
".",
"squeeze",
"(",
"result",
",",
"expanding_dim",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/nn_ops.py#L4585-L4627 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/image_similarity/image_similarity.py | python | ImageSimilarityModel.query | (self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64) | return self.similarity_model.query(
extracted_features, label, k, radius, verbose
) | For each image, retrieve the nearest neighbors from the model's stored
data. In general, the query dataset does not need to be the same as
the reference data stored in the model.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
Query data.
If dataset is an SFrame, it must contain columns with the same
names and types as the features used to train the model.
Additional columns are ignored.
label : str, optional
Name of the query SFrame column with row labels. If 'label' is not
specified, row numbers are used to identify query dataset rows in
the output SFrame.
k : int, optional
Number of nearest neighbors to return from the reference set for
each query observation. The default is 5 neighbors, but setting it
to ``None`` will return all neighbors within ``radius`` of the
query point.
radius : float, optional
Only neighbors whose distance to a query point is smaller than this
value are returned. The default is ``None``, in which case the
``k`` nearest neighbors are returned for each query point,
regardless of distance.
verbose: bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : SFrame
An SFrame with the k-nearest neighbors of each query observation.
The result contains four columns: the first is the label of the
query observation, the second is the label of the nearby reference
observation, the third is the distance between the query and
reference observations, and the fourth is the rank of the reference
observation among the query's k-nearest neighbors.
See Also
--------
similarity_graph
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each query point
returns all of the reference set. If the reference dataset has
:math:`n` rows and the query dataset has :math:`m` rows, the output
is an SFrame with :math:`nm` rows.
Examples
--------
>>> model.query(queries, 'label', k=2)
+-------------+-----------------+----------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+----------------+------+
| 0 | 2 | 0.305941170816 | 1 |
| 0 | 1 | 0.771556867638 | 2 |
| 1 | 1 | 0.390128184063 | 1 |
| 1 | 0 | 0.464004310325 | 2 |
| 2 | 0 | 0.170293863659 | 1 |
| 2 | 1 | 0.464004310325 | 2 |
+-------------+-----------------+----------------+------+ | For each image, retrieve the nearest neighbors from the model's stored
data. In general, the query dataset does not need to be the same as
the reference data stored in the model. | [
"For",
"each",
"image",
"retrieve",
"the",
"nearest",
"neighbors",
"from",
"the",
"model",
"s",
"stored",
"data",
".",
"In",
"general",
"the",
"query",
"dataset",
"does",
"not",
"need",
"to",
"be",
"the",
"same",
"as",
"the",
"reference",
"data",
"stored",
"in",
"the",
"model",
"."
] | def query(self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64):
"""
For each image, retrieve the nearest neighbors from the model's stored
data. In general, the query dataset does not need to be the same as
the reference data stored in the model.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
Query data.
If dataset is an SFrame, it must contain columns with the same
names and types as the features used to train the model.
Additional columns are ignored.
label : str, optional
Name of the query SFrame column with row labels. If 'label' is not
specified, row numbers are used to identify query dataset rows in
the output SFrame.
k : int, optional
Number of nearest neighbors to return from the reference set for
each query observation. The default is 5 neighbors, but setting it
to ``None`` will return all neighbors within ``radius`` of the
query point.
radius : float, optional
Only neighbors whose distance to a query point is smaller than this
value are returned. The default is ``None``, in which case the
``k`` nearest neighbors are returned for each query point,
regardless of distance.
verbose: bool, optional
If True, print progress updates and model details.
batch_size : int, optional
If you are getting memory errors, try decreasing this value. If you
have a powerful computer, increasing this value may improve performance.
Returns
-------
out : SFrame
An SFrame with the k-nearest neighbors of each query observation.
The result contains four columns: the first is the label of the
query observation, the second is the label of the nearby reference
observation, the third is the distance between the query and
reference observations, and the fourth is the rank of the reference
observation among the query's k-nearest neighbors.
See Also
--------
similarity_graph
Notes
-----
- If both ``k`` and ``radius`` are set to ``None``, each query point
returns all of the reference set. If the reference dataset has
:math:`n` rows and the query dataset has :math:`m` rows, the output
is an SFrame with :math:`nm` rows.
Examples
--------
>>> model.query(queries, 'label', k=2)
+-------------+-----------------+----------------+------+
| query_label | reference_label | distance | rank |
+-------------+-----------------+----------------+------+
| 0 | 2 | 0.305941170816 | 1 |
| 0 | 1 | 0.771556867638 | 2 |
| 1 | 1 | 0.390128184063 | 1 |
| 1 | 0 | 0.464004310325 | 2 |
| 2 | 0 | 0.170293863659 | 1 |
| 2 | 1 | 0.464004310325 | 2 |
+-------------+-----------------+----------------+------+
"""
from array import array
if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image, array)):
raise TypeError(
"dataset must be either an SFrame, SArray or turicreate.Image"
)
if batch_size < 1:
raise ValueError("'batch_size' must be greater than or equal to 1")
if isinstance(dataset, _tc.SArray):
dataset = _tc.SFrame({self.feature: dataset})
elif isinstance(dataset, (_tc.Image, array)):
dataset = _tc.SFrame({self.feature: [dataset]})
extracted_features = self._extract_features(
dataset, verbose=verbose, batch_size=batch_size
)
if label is not None:
extracted_features[label] = dataset[label]
return self.similarity_model.query(
extracted_features, label, k, radius, verbose
) | [
"def",
"query",
"(",
"self",
",",
"dataset",
",",
"label",
"=",
"None",
",",
"k",
"=",
"5",
",",
"radius",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"batch_size",
"=",
"64",
")",
":",
"from",
"array",
"import",
"array",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"(",
"_tc",
".",
"SFrame",
",",
"_tc",
".",
"SArray",
",",
"_tc",
".",
"Image",
",",
"array",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"dataset must be either an SFrame, SArray or turicreate.Image\"",
")",
"if",
"batch_size",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"'batch_size' must be greater than or equal to 1\"",
")",
"if",
"isinstance",
"(",
"dataset",
",",
"_tc",
".",
"SArray",
")",
":",
"dataset",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"self",
".",
"feature",
":",
"dataset",
"}",
")",
"elif",
"isinstance",
"(",
"dataset",
",",
"(",
"_tc",
".",
"Image",
",",
"array",
")",
")",
":",
"dataset",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"self",
".",
"feature",
":",
"[",
"dataset",
"]",
"}",
")",
"extracted_features",
"=",
"self",
".",
"_extract_features",
"(",
"dataset",
",",
"verbose",
"=",
"verbose",
",",
"batch_size",
"=",
"batch_size",
")",
"if",
"label",
"is",
"not",
"None",
":",
"extracted_features",
"[",
"label",
"]",
"=",
"dataset",
"[",
"label",
"]",
"return",
"self",
".",
"similarity_model",
".",
"query",
"(",
"extracted_features",
",",
"label",
",",
"k",
",",
"radius",
",",
"verbose",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/image_similarity/image_similarity.py#L359-L453 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | NumberCounter.getvalue | (self) | return self.gettext() | Get the current value as configured in the current mode. | Get the current value as configured in the current mode. | [
"Get",
"the",
"current",
"value",
"as",
"configured",
"in",
"the",
"current",
"mode",
"."
] | def getvalue(self):
"Get the current value as configured in the current mode."
if not self.mode or self.mode in ['text', '1']:
return self.gettext()
if self.mode == 'A':
return self.getletter()
if self.mode == 'a':
return self.getletter().lower()
if self.mode == 'I':
return self.getroman()
if self.mode == '*':
return self.getsymbol()
Trace.error('Unknown counter mode ' + self.mode)
return self.gettext() | [
"def",
"getvalue",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mode",
"or",
"self",
".",
"mode",
"in",
"[",
"'text'",
",",
"'1'",
"]",
":",
"return",
"self",
".",
"gettext",
"(",
")",
"if",
"self",
".",
"mode",
"==",
"'A'",
":",
"return",
"self",
".",
"getletter",
"(",
")",
"if",
"self",
".",
"mode",
"==",
"'a'",
":",
"return",
"self",
".",
"getletter",
"(",
")",
".",
"lower",
"(",
")",
"if",
"self",
".",
"mode",
"==",
"'I'",
":",
"return",
"self",
".",
"getroman",
"(",
")",
"if",
"self",
".",
"mode",
"==",
"'*'",
":",
"return",
"self",
".",
"getsymbol",
"(",
")",
"Trace",
".",
"error",
"(",
"'Unknown counter mode '",
"+",
"self",
".",
"mode",
")",
"return",
"self",
".",
"gettext",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L3229-L3242 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py | python | SpawnBase.readline | (self, size=-1) | This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n.
If the size argument is 0 then an empty string is returned. In all
other cases the size argument is ignored, which is not standard
behavior for a file-like object. | This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n. | [
"This",
"reads",
"and",
"returns",
"one",
"entire",
"line",
".",
"The",
"newline",
"at",
"the",
"end",
"of",
"line",
"is",
"returned",
"as",
"part",
"of",
"the",
"string",
"unless",
"the",
"file",
"ends",
"without",
"a",
"newline",
".",
"An",
"empty",
"string",
"is",
"returned",
"if",
"EOF",
"is",
"encountered",
"immediately",
".",
"This",
"looks",
"for",
"a",
"newline",
"as",
"a",
"CR",
"/",
"LF",
"pair",
"(",
"\\\\",
"r",
"\\\\",
"n",
")",
"even",
"on",
"UNIX",
"because",
"this",
"is",
"what",
"the",
"pseudotty",
"device",
"returns",
".",
"So",
"contrary",
"to",
"what",
"you",
"may",
"expect",
"you",
"will",
"receive",
"newlines",
"as",
"\\\\",
"r",
"\\\\",
"n",
"."
] | def readline(self, size=-1):
'''This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
this is what the pseudotty device returns. So contrary to what you may
expect you will receive newlines as \\r\\n.
If the size argument is 0 then an empty string is returned. In all
other cases the size argument is ignored, which is not standard
behavior for a file-like object. '''
if size == 0:
return self.string_type()
# delimiter default is EOF
index = self.expect([self.crlf, self.delimiter])
if index == 0:
return self.before + self.crlf
else:
return self.before | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"==",
"0",
":",
"return",
"self",
".",
"string_type",
"(",
")",
"# delimiter default is EOF",
"index",
"=",
"self",
".",
"expect",
"(",
"[",
"self",
".",
"crlf",
",",
"self",
".",
"delimiter",
"]",
")",
"if",
"index",
"==",
"0",
":",
"return",
"self",
".",
"before",
"+",
"self",
".",
"crlf",
"else",
":",
"return",
"self",
".",
"before"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L459-L478 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/functools.py | python | singledispatch | (func) | return wrapper | Single-dispatch generic function decorator.
Transforms a function into a generic function, which can have different
behaviours depending upon the type of its first argument. The decorated
function acts as the default implementation, and additional
implementations can be registered using the register() attribute of the
generic function. | Single-dispatch generic function decorator. | [
"Single",
"-",
"dispatch",
"generic",
"function",
"decorator",
"."
] | def singledispatch(func):
"""Single-dispatch generic function decorator.
Transforms a function into a generic function, which can have different
behaviours depending upon the type of its first argument. The decorated
function acts as the default implementation, and additional
implementations can be registered using the register() attribute of the
generic function.
"""
# There are many programs that use functools without singledispatch, so we
# trade-off making singledispatch marginally slower for the benefit of
# making start-up of such applications slightly faster.
import types, weakref
registry = {}
dispatch_cache = weakref.WeakKeyDictionary()
cache_token = None
def dispatch(cls):
"""generic_func.dispatch(cls) -> <function implementation>
Runs the dispatch algorithm to return the best available implementation
for the given *cls* registered on *generic_func*.
"""
nonlocal cache_token
if cache_token is not None:
current_token = get_cache_token()
if cache_token != current_token:
dispatch_cache.clear()
cache_token = current_token
try:
impl = dispatch_cache[cls]
except KeyError:
try:
impl = registry[cls]
except KeyError:
impl = _find_impl(cls, registry)
dispatch_cache[cls] = impl
return impl
def register(cls, func=None):
"""generic_func.register(cls, func) -> func
Registers a new implementation for the given *cls* on a *generic_func*.
"""
nonlocal cache_token
if func is None:
if isinstance(cls, type):
return lambda f: register(cls, f)
ann = getattr(cls, '__annotations__', {})
if not ann:
raise TypeError(
f"Invalid first argument to `register()`: {cls!r}. "
f"Use either `@register(some_class)` or plain `@register` "
f"on an annotated function."
)
func = cls
# only import typing if annotation parsing is necessary
from typing import get_type_hints
argname, cls = next(iter(get_type_hints(func).items()))
assert isinstance(cls, type), (
f"Invalid annotation for {argname!r}. {cls!r} is not a class."
)
registry[cls] = func
if cache_token is None and hasattr(cls, '__abstractmethods__'):
cache_token = get_cache_token()
dispatch_cache.clear()
return func
def wrapper(*args, **kw):
if not args:
raise TypeError(f'{funcname} requires at least '
'1 positional argument')
return dispatch(args[0].__class__)(*args, **kw)
funcname = getattr(func, '__name__', 'singledispatch function')
registry[object] = func
wrapper.register = register
wrapper.dispatch = dispatch
wrapper.registry = types.MappingProxyType(registry)
wrapper._clear_cache = dispatch_cache.clear
update_wrapper(wrapper, func)
return wrapper | [
"def",
"singledispatch",
"(",
"func",
")",
":",
"# There are many programs that use functools without singledispatch, so we",
"# trade-off making singledispatch marginally slower for the benefit of",
"# making start-up of such applications slightly faster.",
"import",
"types",
",",
"weakref",
"registry",
"=",
"{",
"}",
"dispatch_cache",
"=",
"weakref",
".",
"WeakKeyDictionary",
"(",
")",
"cache_token",
"=",
"None",
"def",
"dispatch",
"(",
"cls",
")",
":",
"\"\"\"generic_func.dispatch(cls) -> <function implementation>\n\n Runs the dispatch algorithm to return the best available implementation\n for the given *cls* registered on *generic_func*.\n\n \"\"\"",
"nonlocal",
"cache_token",
"if",
"cache_token",
"is",
"not",
"None",
":",
"current_token",
"=",
"get_cache_token",
"(",
")",
"if",
"cache_token",
"!=",
"current_token",
":",
"dispatch_cache",
".",
"clear",
"(",
")",
"cache_token",
"=",
"current_token",
"try",
":",
"impl",
"=",
"dispatch_cache",
"[",
"cls",
"]",
"except",
"KeyError",
":",
"try",
":",
"impl",
"=",
"registry",
"[",
"cls",
"]",
"except",
"KeyError",
":",
"impl",
"=",
"_find_impl",
"(",
"cls",
",",
"registry",
")",
"dispatch_cache",
"[",
"cls",
"]",
"=",
"impl",
"return",
"impl",
"def",
"register",
"(",
"cls",
",",
"func",
"=",
"None",
")",
":",
"\"\"\"generic_func.register(cls, func) -> func\n\n Registers a new implementation for the given *cls* on a *generic_func*.\n\n \"\"\"",
"nonlocal",
"cache_token",
"if",
"func",
"is",
"None",
":",
"if",
"isinstance",
"(",
"cls",
",",
"type",
")",
":",
"return",
"lambda",
"f",
":",
"register",
"(",
"cls",
",",
"f",
")",
"ann",
"=",
"getattr",
"(",
"cls",
",",
"'__annotations__'",
",",
"{",
"}",
")",
"if",
"not",
"ann",
":",
"raise",
"TypeError",
"(",
"f\"Invalid first argument to `register()`: {cls!r}. \"",
"f\"Use either `@register(some_class)` or plain `@register` \"",
"f\"on an annotated function.\"",
")",
"func",
"=",
"cls",
"# only import typing if annotation parsing is necessary",
"from",
"typing",
"import",
"get_type_hints",
"argname",
",",
"cls",
"=",
"next",
"(",
"iter",
"(",
"get_type_hints",
"(",
"func",
")",
".",
"items",
"(",
")",
")",
")",
"assert",
"isinstance",
"(",
"cls",
",",
"type",
")",
",",
"(",
"f\"Invalid annotation for {argname!r}. {cls!r} is not a class.\"",
")",
"registry",
"[",
"cls",
"]",
"=",
"func",
"if",
"cache_token",
"is",
"None",
"and",
"hasattr",
"(",
"cls",
",",
"'__abstractmethods__'",
")",
":",
"cache_token",
"=",
"get_cache_token",
"(",
")",
"dispatch_cache",
".",
"clear",
"(",
")",
"return",
"func",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"args",
":",
"raise",
"TypeError",
"(",
"f'{funcname} requires at least '",
"'1 positional argument'",
")",
"return",
"dispatch",
"(",
"args",
"[",
"0",
"]",
".",
"__class__",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"funcname",
"=",
"getattr",
"(",
"func",
",",
"'__name__'",
",",
"'singledispatch function'",
")",
"registry",
"[",
"object",
"]",
"=",
"func",
"wrapper",
".",
"register",
"=",
"register",
"wrapper",
".",
"dispatch",
"=",
"dispatch",
"wrapper",
".",
"registry",
"=",
"types",
".",
"MappingProxyType",
"(",
"registry",
")",
"wrapper",
".",
"_clear_cache",
"=",
"dispatch_cache",
".",
"clear",
"update_wrapper",
"(",
"wrapper",
",",
"func",
")",
"return",
"wrapper"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/functools.py#L763-L849 | |
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | tools/rdm/setup_patch.py | python | AutoPatcher.__init__ | (self, wrapper, callback, force=False) | Create a new AutoPatcher object.
Args:
wrapper: an ola.ClientWrapper object.
callback: The function to be called when patching is complete (or an
error occurs. The callback is passed three arguments:
(status, ports_found, ports_patched)
force: override the patching for ports which are already patched | Create a new AutoPatcher object. | [
"Create",
"a",
"new",
"AutoPatcher",
"object",
"."
] | def __init__(self, wrapper, callback, force=False):
"""Create a new AutoPatcher object.
Args:
wrapper: an ola.ClientWrapper object.
callback: The function to be called when patching is complete (or an
error occurs. The callback is passed three arguments:
(status, ports_found, ports_patched)
force: override the patching for ports which are already patched
"""
self._wrapper = wrapper
# start from 1 to avoid confusion
self._next_universe = 1
self._callback = callback
self._ports_found = 0
self._ports_patched = 0
self._port_attempts = 0
self._force = force | [
"def",
"__init__",
"(",
"self",
",",
"wrapper",
",",
"callback",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"_wrapper",
"=",
"wrapper",
"# start from 1 to avoid confusion",
"self",
".",
"_next_universe",
"=",
"1",
"self",
".",
"_callback",
"=",
"callback",
"self",
".",
"_ports_found",
"=",
"0",
"self",
".",
"_ports_patched",
"=",
"0",
"self",
".",
"_port_attempts",
"=",
"0",
"self",
".",
"_force",
"=",
"force"
] | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/tools/rdm/setup_patch.py#L33-L50 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_graphs.py | python | is_copy_node | (node_name) | return node_name.startswith("__copy_") | Determine whether a node name is that of a debug Copy node.
Such nodes are inserted by TensorFlow core upon request in
RunOptions.debug_options.debug_tensor_watch_opts.
Args:
node_name: Name of the node.
Returns:
A bool indicating whether the input argument is the name of a debug Copy
node. | Determine whether a node name is that of a debug Copy node. | [
"Determine",
"whether",
"a",
"node",
"name",
"is",
"that",
"of",
"a",
"debug",
"Copy",
"node",
"."
] | def is_copy_node(node_name):
"""Determine whether a node name is that of a debug Copy node.
Such nodes are inserted by TensorFlow core upon request in
RunOptions.debug_options.debug_tensor_watch_opts.
Args:
node_name: Name of the node.
Returns:
A bool indicating whether the input argument is the name of a debug Copy
node.
"""
return node_name.startswith("__copy_") | [
"def",
"is_copy_node",
"(",
"node_name",
")",
":",
"return",
"node_name",
".",
"startswith",
"(",
"\"__copy_\"",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_graphs.py#L70-L83 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/vcs/versioncontrol.py | python | VersionControl.get_src_requirement | (cls, repo_dir, project_name) | return req | Return the requirement string to use to redownload the files
currently at the given repository directory.
Args:
project_name: the (unescaped) project name.
The return value has a form similar to the following:
{repository_url}@{revision}#egg={project_name} | Return the requirement string to use to redownload the files
currently at the given repository directory. | [
"Return",
"the",
"requirement",
"string",
"to",
"use",
"to",
"redownload",
"the",
"files",
"currently",
"at",
"the",
"given",
"repository",
"directory",
"."
] | def get_src_requirement(cls, repo_dir, project_name):
# type: (str, str) -> str
"""
Return the requirement string to use to redownload the files
currently at the given repository directory.
Args:
project_name: the (unescaped) project name.
The return value has a form similar to the following:
{repository_url}@{revision}#egg={project_name}
"""
repo_url = cls.get_remote_url(repo_dir)
if cls.should_add_vcs_url_prefix(repo_url):
repo_url = f'{cls.name}+{repo_url}'
revision = cls.get_requirement_revision(repo_dir)
subdir = cls.get_subdirectory(repo_dir)
req = make_vcs_requirement_url(repo_url, revision, project_name,
subdir=subdir)
return req | [
"def",
"get_src_requirement",
"(",
"cls",
",",
"repo_dir",
",",
"project_name",
")",
":",
"# type: (str, str) -> str",
"repo_url",
"=",
"cls",
".",
"get_remote_url",
"(",
"repo_dir",
")",
"if",
"cls",
".",
"should_add_vcs_url_prefix",
"(",
"repo_url",
")",
":",
"repo_url",
"=",
"f'{cls.name}+{repo_url}'",
"revision",
"=",
"cls",
".",
"get_requirement_revision",
"(",
"repo_dir",
")",
"subdir",
"=",
"cls",
".",
"get_subdirectory",
"(",
"repo_dir",
")",
"req",
"=",
"make_vcs_requirement_url",
"(",
"repo_url",
",",
"revision",
",",
"project_name",
",",
"subdir",
"=",
"subdir",
")",
"return",
"req"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/vcs/versioncontrol.py#L315-L338 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/computation/expr.py | python | tokenize_string | (source) | Tokenize a Python source code string.
Parameters
----------
source : str
A Python source code string | Tokenize a Python source code string. | [
"Tokenize",
"a",
"Python",
"source",
"code",
"string",
"."
] | def tokenize_string(source):
"""Tokenize a Python source code string.
Parameters
----------
source : str
A Python source code string
"""
line_reader = StringIO(source).readline
for toknum, tokval, _, _, _ in tokenize.generate_tokens(line_reader):
yield toknum, tokval | [
"def",
"tokenize_string",
"(",
"source",
")",
":",
"line_reader",
"=",
"StringIO",
"(",
"source",
")",
".",
"readline",
"for",
"toknum",
",",
"tokval",
",",
"_",
",",
"_",
",",
"_",
"in",
"tokenize",
".",
"generate_tokens",
"(",
"line_reader",
")",
":",
"yield",
"toknum",
",",
"tokval"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/computation/expr.py#L25-L35 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/command/egg_info.py | python | FileList.exclude | (self, pattern) | return self._remove_files(match.match) | Exclude files that match 'pattern'. | Exclude files that match 'pattern'. | [
"Exclude",
"files",
"that",
"match",
"pattern",
"."
] | def exclude(self, pattern):
"""Exclude files that match 'pattern'."""
match = translate_pattern(pattern)
return self._remove_files(match.match) | [
"def",
"exclude",
"(",
"self",
",",
"pattern",
")",
":",
"match",
"=",
"translate_pattern",
"(",
"pattern",
")",
"return",
"self",
".",
"_remove_files",
"(",
"match",
".",
"match",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/command/egg_info.py#L417-L420 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/auth.py | python | HmacAuthV4Handler.canonical_headers | (self, headers_to_sign) | return '\n'.join(sorted(canonical)) | Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines. | Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines. | [
"Return",
"the",
"headers",
"that",
"need",
"to",
"be",
"included",
"in",
"the",
"StringToSign",
"in",
"their",
"canonical",
"form",
"by",
"converting",
"all",
"header",
"keys",
"to",
"lower",
"case",
"sorting",
"them",
"in",
"alphabetical",
"order",
"and",
"then",
"joining",
"them",
"into",
"a",
"string",
"separated",
"by",
"newlines",
"."
] | def canonical_headers(self, headers_to_sign):
"""
Return the headers that need to be included in the StringToSign
in their canonical form by converting all header keys to lower
case, sorting them in alphabetical order and then joining
them into a string, separated by newlines.
"""
canonical = []
for header in headers_to_sign:
c_name = header.lower().strip()
raw_value = str(headers_to_sign[header])
if '"' in raw_value:
c_value = raw_value.strip()
else:
c_value = ' '.join(raw_value.strip().split())
canonical.append('%s:%s' % (c_name, c_value))
return '\n'.join(sorted(canonical)) | [
"def",
"canonical_headers",
"(",
"self",
",",
"headers_to_sign",
")",
":",
"canonical",
"=",
"[",
"]",
"for",
"header",
"in",
"headers_to_sign",
":",
"c_name",
"=",
"header",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"raw_value",
"=",
"str",
"(",
"headers_to_sign",
"[",
"header",
"]",
")",
"if",
"'\"'",
"in",
"raw_value",
":",
"c_value",
"=",
"raw_value",
".",
"strip",
"(",
")",
"else",
":",
"c_value",
"=",
"' '",
".",
"join",
"(",
"raw_value",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
")",
"canonical",
".",
"append",
"(",
"'%s:%s'",
"%",
"(",
"c_name",
",",
"c_value",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"sorted",
"(",
"canonical",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/auth.py#L363-L380 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/instruments/interface.py | python | InstrumentInterface._warning | (self, title, message) | Pop up a dialog and warn the user
@param title: dialog box title
@param message: message to be displayed
#TODO: change this to signals and slots mechanism | Pop up a dialog and warn the user
@param title: dialog box title
@param message: message to be displayed | [
"Pop",
"up",
"a",
"dialog",
"and",
"warn",
"the",
"user",
"@param",
"title",
":",
"dialog",
"box",
"title",
"@param",
"message",
":",
"message",
"to",
"be",
"displayed"
] | def _warning(self, title, message):
"""
Pop up a dialog and warn the user
@param title: dialog box title
@param message: message to be displayed
#TODO: change this to signals and slots mechanism
"""
if len(self.widgets)>0:
QMessageBox.warning(self.widgets[0], title, message) | [
"def",
"_warning",
"(",
"self",
",",
"title",
",",
"message",
")",
":",
"if",
"len",
"(",
"self",
".",
"widgets",
")",
">",
"0",
":",
"QMessageBox",
".",
"warning",
"(",
"self",
".",
"widgets",
"[",
"0",
"]",
",",
"title",
",",
"message",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/instruments/interface.py#L72-L81 | ||
NicknineTheEagle/TF2-Base | 20459c5a7fbc995b6bf54fa85c2f62a101e9fb64 | src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py | python | _ExtensionDict.__getitem__ | (self, extension_handle) | return result | Returns the current value of the given extension handle. | Returns the current value of the given extension handle. | [
"Returns",
"the",
"current",
"value",
"of",
"the",
"given",
"extension",
"handle",
"."
] | def __getitem__(self, extension_handle):
"""Returns the current value of the given extension handle."""
_VerifyExtensionHandle(self._extended_message, extension_handle)
result = self._extended_message._fields.get(extension_handle)
if result is not None:
return result
if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:
result = extension_handle._default_constructor(self._extended_message)
elif extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
result = extension_handle.message_type._concrete_class()
try:
result._SetListener(self._extended_message._listener_for_children)
except ReferenceError:
pass
else:
# Singular scalar -- just return the default without inserting into the
# dict.
return extension_handle.default_value
# Atomically check if another thread has preempted us and, if not, swap
# in the new object we just created. If someone has preempted us, we
# take that object and discard ours.
# WARNING: We are relying on setdefault() being atomic. This is true
# in CPython but we haven't investigated others. This warning appears
# in several other locations in this file.
result = self._extended_message._fields.setdefault(
extension_handle, result)
return result | [
"def",
"__getitem__",
"(",
"self",
",",
"extension_handle",
")",
":",
"_VerifyExtensionHandle",
"(",
"self",
".",
"_extended_message",
",",
"extension_handle",
")",
"result",
"=",
"self",
".",
"_extended_message",
".",
"_fields",
".",
"get",
"(",
"extension_handle",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"if",
"extension_handle",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"result",
"=",
"extension_handle",
".",
"_default_constructor",
"(",
"self",
".",
"_extended_message",
")",
"elif",
"extension_handle",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"result",
"=",
"extension_handle",
".",
"message_type",
".",
"_concrete_class",
"(",
")",
"try",
":",
"result",
".",
"_SetListener",
"(",
"self",
".",
"_extended_message",
".",
"_listener_for_children",
")",
"except",
"ReferenceError",
":",
"pass",
"else",
":",
"# Singular scalar -- just return the default without inserting into the",
"# dict.",
"return",
"extension_handle",
".",
"default_value",
"# Atomically check if another thread has preempted us and, if not, swap",
"# in the new object we just created. If someone has preempted us, we",
"# take that object and discard ours.",
"# WARNING: We are relying on setdefault() being atomic. This is true",
"# in CPython but we haven't investigated others. This warning appears",
"# in several other locations in this file.",
"result",
"=",
"self",
".",
"_extended_message",
".",
"_fields",
".",
"setdefault",
"(",
"extension_handle",
",",
"result",
")",
"return",
"result"
] | https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L1065-L1096 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/session_ops.py | python | delete_session_tensor | (handle, name=None) | return (holder, deleter) | Delete the tensor for the given tensor handle.
This is EXPERIMENTAL and subject to change.
Delete the tensor of a given tensor handle. The tensor is produced
in a previous run() and stored in the state of the session.
Args:
handle: The string representation of a persistent tensor handle.
name: Optional name prefix for the return tensor.
Returns:
A pair of graph elements. The first is a placeholder for feeding a
tensor handle and the second is a deletion operation. | Delete the tensor for the given tensor handle. | [
"Delete",
"the",
"tensor",
"for",
"the",
"given",
"tensor",
"handle",
"."
] | def delete_session_tensor(handle, name=None):
"""Delete the tensor for the given tensor handle.
This is EXPERIMENTAL and subject to change.
Delete the tensor of a given tensor handle. The tensor is produced
in a previous run() and stored in the state of the session.
Args:
handle: The string representation of a persistent tensor handle.
name: Optional name prefix for the return tensor.
Returns:
A pair of graph elements. The first is a placeholder for feeding a
tensor handle and the second is a deletion operation.
"""
handle_device = TensorHandle._get_device_name(handle)
with ops.device(handle_device):
holder = array_ops.placeholder(dtypes.string)
deleter = gen_data_flow_ops._delete_session_tensor(holder, name=name)
return (holder, deleter) | [
"def",
"delete_session_tensor",
"(",
"handle",
",",
"name",
"=",
"None",
")",
":",
"handle_device",
"=",
"TensorHandle",
".",
"_get_device_name",
"(",
"handle",
")",
"with",
"ops",
".",
"device",
"(",
"handle_device",
")",
":",
"holder",
"=",
"array_ops",
".",
"placeholder",
"(",
"dtypes",
".",
"string",
")",
"deleter",
"=",
"gen_data_flow_ops",
".",
"_delete_session_tensor",
"(",
"holder",
",",
"name",
"=",
"name",
")",
"return",
"(",
"holder",
",",
"deleter",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/session_ops.py#L202-L222 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/feature_selection/_base.py | python | SelectorMixin.inverse_transform | (self, X) | return Xt | Reverse the transformation operation
Parameters
----------
X : array of shape [n_samples, n_selected_features]
The input samples.
Returns
-------
X_r : array of shape [n_samples, n_original_features]
`X` with columns of zeros inserted where features would have
been removed by :meth:`transform`. | Reverse the transformation operation | [
"Reverse",
"the",
"transformation",
"operation"
] | def inverse_transform(self, X):
"""
Reverse the transformation operation
Parameters
----------
X : array of shape [n_samples, n_selected_features]
The input samples.
Returns
-------
X_r : array of shape [n_samples, n_original_features]
`X` with columns of zeros inserted where features would have
been removed by :meth:`transform`.
"""
if issparse(X):
X = X.tocsc()
# insert additional entries in indptr:
# e.g. if transform changed indptr from [0 2 6 7] to [0 2 3]
# col_nonzeros here will be [2 0 1] so indptr becomes [0 2 2 3]
it = self.inverse_transform(np.diff(X.indptr).reshape(1, -1))
col_nonzeros = it.ravel()
indptr = np.concatenate([[0], np.cumsum(col_nonzeros)])
Xt = csc_matrix((X.data, X.indices, indptr),
shape=(X.shape[0], len(indptr) - 1), dtype=X.dtype)
return Xt
support = self.get_support()
X = check_array(X, dtype=None)
if support.sum() != X.shape[1]:
raise ValueError("X has a different shape than during fitting.")
if X.ndim == 1:
X = X[None, :]
Xt = np.zeros((X.shape[0], support.size), dtype=X.dtype)
Xt[:, support] = X
return Xt | [
"def",
"inverse_transform",
"(",
"self",
",",
"X",
")",
":",
"if",
"issparse",
"(",
"X",
")",
":",
"X",
"=",
"X",
".",
"tocsc",
"(",
")",
"# insert additional entries in indptr:",
"# e.g. if transform changed indptr from [0 2 6 7] to [0 2 3]",
"# col_nonzeros here will be [2 0 1] so indptr becomes [0 2 2 3]",
"it",
"=",
"self",
".",
"inverse_transform",
"(",
"np",
".",
"diff",
"(",
"X",
".",
"indptr",
")",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
")",
"col_nonzeros",
"=",
"it",
".",
"ravel",
"(",
")",
"indptr",
"=",
"np",
".",
"concatenate",
"(",
"[",
"[",
"0",
"]",
",",
"np",
".",
"cumsum",
"(",
"col_nonzeros",
")",
"]",
")",
"Xt",
"=",
"csc_matrix",
"(",
"(",
"X",
".",
"data",
",",
"X",
".",
"indices",
",",
"indptr",
")",
",",
"shape",
"=",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"len",
"(",
"indptr",
")",
"-",
"1",
")",
",",
"dtype",
"=",
"X",
".",
"dtype",
")",
"return",
"Xt",
"support",
"=",
"self",
".",
"get_support",
"(",
")",
"X",
"=",
"check_array",
"(",
"X",
",",
"dtype",
"=",
"None",
")",
"if",
"support",
".",
"sum",
"(",
")",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"X has a different shape than during fitting.\"",
")",
"if",
"X",
".",
"ndim",
"==",
"1",
":",
"X",
"=",
"X",
"[",
"None",
",",
":",
"]",
"Xt",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"support",
".",
"size",
")",
",",
"dtype",
"=",
"X",
".",
"dtype",
")",
"Xt",
"[",
":",
",",
"support",
"]",
"=",
"X",
"return",
"Xt"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_selection/_base.py#L87-L123 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/framework/pr_tools/trilinosprhelpers/gitutility/GitUtility.py | python | GitUtility.check_minimum_version | (self, req_major, req_minor=0) | return 0 | Verify the version of git is greater than req_major.req_minor
Raises:
TypeError if req_major or req_minor are not integers.
SystemExit if detected major < required major version.
or if detected major >= req. major AND det. minor < req. minor.
Returns:
Integer: zero on success. | Verify the version of git is greater than req_major.req_minor | [
"Verify",
"the",
"version",
"of",
"git",
"is",
"greater",
"than",
"req_major",
".",
"req_minor"
] | def check_minimum_version(self, req_major, req_minor=0):
"""
Verify the version of git is greater than req_major.req_minor
Raises:
TypeError if req_major or req_minor are not integers.
SystemExit if detected major < required major version.
or if detected major >= req. major AND det. minor < req. minor.
Returns:
Integer: zero on success.
"""
if not isinstance(req_major, int):
raise TypeError("Required parameter 'req_major' must be an integer.")
if not isinstance(req_minor, int):
raise TypeError("Required parameter 'req_minor' must be an integer.")
det_major = self.version["major"]
det_minor = self.version["minor"]
str_err = "Required Git version must be greater or equal to {}.{}\n".format(req_major, req_minor)
str_err += "but we detected version {}.{}".format(det_major, det_minor)
if det_major < req_major:
raise SystemExit(str_err)
elif det_major == req_major and det_minor < req_minor:
raise SystemExit(str_err)
else:
print("")
print("Git minimum version requirement: OK")
print("")
return 0 | [
"def",
"check_minimum_version",
"(",
"self",
",",
"req_major",
",",
"req_minor",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"req_major",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Required parameter 'req_major' must be an integer.\"",
")",
"if",
"not",
"isinstance",
"(",
"req_minor",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Required parameter 'req_minor' must be an integer.\"",
")",
"det_major",
"=",
"self",
".",
"version",
"[",
"\"major\"",
"]",
"det_minor",
"=",
"self",
".",
"version",
"[",
"\"minor\"",
"]",
"str_err",
"=",
"\"Required Git version must be greater or equal to {}.{}\\n\"",
".",
"format",
"(",
"req_major",
",",
"req_minor",
")",
"str_err",
"+=",
"\"but we detected version {}.{}\"",
".",
"format",
"(",
"det_major",
",",
"det_minor",
")",
"if",
"det_major",
"<",
"req_major",
":",
"raise",
"SystemExit",
"(",
"str_err",
")",
"elif",
"det_major",
"==",
"req_major",
"and",
"det_minor",
"<",
"req_minor",
":",
"raise",
"SystemExit",
"(",
"str_err",
")",
"else",
":",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"Git minimum version requirement: OK\"",
")",
"print",
"(",
"\"\"",
")",
"return",
"0"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/framework/pr_tools/trilinosprhelpers/gitutility/GitUtility.py#L60-L92 | |
bairdzhang/smallhardface | 76fa1d87a9602d9b13d7a7fe693fc7aec91cab80 | caffe/python/caffe/coord_map.py | python | crop | (top_from, top_to) | return L.Crop(top_from, top_to,
crop_param=dict(axis=ax + 1, # +1 for first cropping dim.
offset=list(-np.round(b).astype(int)))) | Define a Crop layer to crop a top (from) to another top (to) by
determining the coordinate mapping between the two and net spec'ing
the axis and shift parameters of the crop. | Define a Crop layer to crop a top (from) to another top (to) by
determining the coordinate mapping between the two and net spec'ing
the axis and shift parameters of the crop. | [
"Define",
"a",
"Crop",
"layer",
"to",
"crop",
"a",
"top",
"(",
"from",
")",
"to",
"another",
"top",
"(",
"to",
")",
"by",
"determining",
"the",
"coordinate",
"mapping",
"between",
"the",
"two",
"and",
"net",
"spec",
"ing",
"the",
"axis",
"and",
"shift",
"parameters",
"of",
"the",
"crop",
"."
] | def crop(top_from, top_to):
"""
Define a Crop layer to crop a top (from) to another top (to) by
determining the coordinate mapping between the two and net spec'ing
the axis and shift parameters of the crop.
"""
ax, a, b = coord_map_from_to(top_from, top_to)
assert (a == 1).all(), 'scale mismatch on crop (a = {})'.format(a)
assert (b <= 0).all(), 'cannot crop negative offset (b = {})'.format(b)
assert (np.round(b) == b).all(), 'cannot crop noninteger offset ' \
'(b = {})'.format(b)
return L.Crop(top_from, top_to,
crop_param=dict(axis=ax + 1, # +1 for first cropping dim.
offset=list(-np.round(b).astype(int)))) | [
"def",
"crop",
"(",
"top_from",
",",
"top_to",
")",
":",
"ax",
",",
"a",
",",
"b",
"=",
"coord_map_from_to",
"(",
"top_from",
",",
"top_to",
")",
"assert",
"(",
"a",
"==",
"1",
")",
".",
"all",
"(",
")",
",",
"'scale mismatch on crop (a = {})'",
".",
"format",
"(",
"a",
")",
"assert",
"(",
"b",
"<=",
"0",
")",
".",
"all",
"(",
")",
",",
"'cannot crop negative offset (b = {})'",
".",
"format",
"(",
"b",
")",
"assert",
"(",
"np",
".",
"round",
"(",
"b",
")",
"==",
"b",
")",
".",
"all",
"(",
")",
",",
"'cannot crop noninteger offset '",
"'(b = {})'",
".",
"format",
"(",
"b",
")",
"return",
"L",
".",
"Crop",
"(",
"top_from",
",",
"top_to",
",",
"crop_param",
"=",
"dict",
"(",
"axis",
"=",
"ax",
"+",
"1",
",",
"# +1 for first cropping dim.",
"offset",
"=",
"list",
"(",
"-",
"np",
".",
"round",
"(",
"b",
")",
".",
"astype",
"(",
"int",
")",
")",
")",
")"
] | https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/python/caffe/coord_map.py#L172-L185 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/utils/gc.py | python | get_paths | (base_dir, parser) | return sorted(paths) | Gets a list of Paths in a given directory.
Args:
base_dir: directory.
parser: a function which gets the raw Path and can augment it with
information such as the export_version, or ignore the path by returning
None. An example parser may extract the export version from a path
such as "/tmp/exports/100" an another may extract from a full file
name such as "/tmp/checkpoint-99.out".
Returns:
A list of Paths contained in the base directory with the parsing function
applied.
By default the following fields are populated,
- Path.path
The parsing function is responsible for populating,
- Path.export_version | Gets a list of Paths in a given directory. | [
"Gets",
"a",
"list",
"of",
"Paths",
"in",
"a",
"given",
"directory",
"."
] | def get_paths(base_dir, parser):
"""Gets a list of Paths in a given directory.
Args:
base_dir: directory.
parser: a function which gets the raw Path and can augment it with
information such as the export_version, or ignore the path by returning
None. An example parser may extract the export version from a path
such as "/tmp/exports/100" an another may extract from a full file
name such as "/tmp/checkpoint-99.out".
Returns:
A list of Paths contained in the base directory with the parsing function
applied.
By default the following fields are populated,
- Path.path
The parsing function is responsible for populating,
- Path.export_version
"""
raw_paths = gfile.ListDirectory(base_dir)
paths = []
for r in raw_paths:
p = parser(Path(os.path.join(compat.as_str_any(base_dir),
compat.as_str_any(r)),
None))
if p:
paths.append(p)
return sorted(paths) | [
"def",
"get_paths",
"(",
"base_dir",
",",
"parser",
")",
":",
"raw_paths",
"=",
"gfile",
".",
"ListDirectory",
"(",
"base_dir",
")",
"paths",
"=",
"[",
"]",
"for",
"r",
"in",
"raw_paths",
":",
"p",
"=",
"parser",
"(",
"Path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"compat",
".",
"as_str_any",
"(",
"base_dir",
")",
",",
"compat",
".",
"as_str_any",
"(",
"r",
")",
")",
",",
"None",
")",
")",
"if",
"p",
":",
"paths",
".",
"append",
"(",
"p",
")",
"return",
"sorted",
"(",
"paths",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/utils/gc.py#L182-L209 | |
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | tools/onnx-graphsurgeon/onnx_graphsurgeon/ir/tensor.py | python | Tensor.o | (self, consumer_idx=0, tensor_idx=0) | return self.outputs[consumer_idx].outputs[tensor_idx] | Convenience function to get an output tensor of one of this tensor's output nodes.
For example:
::
assert tensor.o() == tensor.outputs[0].outputs[0]
assert tensor.o(2, 1) == tensor.outputs[2].outputs[1]
Args:
consumer_idx (int): The index of the consumer of the input tensor. Defaults to 0.
tensor_idx (int): The index of the output tensor of the node, if the node has multiple outputs. Defaults to 0.
Returns:
Tensor: The specified consumer (output) tensor | Convenience function to get an output tensor of one of this tensor's output nodes. | [
"Convenience",
"function",
"to",
"get",
"an",
"output",
"tensor",
"of",
"one",
"of",
"this",
"tensor",
"s",
"output",
"nodes",
"."
] | def o(self, consumer_idx=0, tensor_idx=0):
"""
Convenience function to get an output tensor of one of this tensor's output nodes.
For example:
::
assert tensor.o() == tensor.outputs[0].outputs[0]
assert tensor.o(2, 1) == tensor.outputs[2].outputs[1]
Args:
consumer_idx (int): The index of the consumer of the input tensor. Defaults to 0.
tensor_idx (int): The index of the output tensor of the node, if the node has multiple outputs. Defaults to 0.
Returns:
Tensor: The specified consumer (output) tensor
"""
return self.outputs[consumer_idx].outputs[tensor_idx] | [
"def",
"o",
"(",
"self",
",",
"consumer_idx",
"=",
"0",
",",
"tensor_idx",
"=",
"0",
")",
":",
"return",
"self",
".",
"outputs",
"[",
"consumer_idx",
"]",
".",
"outputs",
"[",
"tensor_idx",
"]"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/onnx-graphsurgeon/onnx_graphsurgeon/ir/tensor.py#L112-L129 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-score-from-removing-stones.py | python | Solution.maximumScore | (self, a, b, c) | return min((a+b+c)//2, a+b+c - max(a, b, c)) | :type a: int
:type b: int
:type c: int
:rtype: int | :type a: int
:type b: int
:type c: int
:rtype: int | [
":",
"type",
"a",
":",
"int",
":",
"type",
"b",
":",
"int",
":",
"type",
"c",
":",
"int",
":",
"rtype",
":",
"int"
] | def maximumScore(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: int
"""
# assumed c is the max size
# case1: a+b > c
# => (a+b-c)//2 + c = (a+b+c)//2 < a+b
# case2: a+b <= c
# => a+b <= (a+b+c)//2
return min((a+b+c)//2, a+b+c - max(a, b, c)) | [
"def",
"maximumScore",
"(",
"self",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"# assumed c is the max size",
"# case1: a+b > c",
"# => (a+b-c)//2 + c = (a+b+c)//2 < a+b",
"# case2: a+b <= c",
"# => a+b <= (a+b+c)//2",
"return",
"min",
"(",
"(",
"a",
"+",
"b",
"+",
"c",
")",
"//",
"2",
",",
"a",
"+",
"b",
"+",
"c",
"-",
"max",
"(",
"a",
",",
"b",
",",
"c",
")",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-score-from-removing-stones.py#L5-L17 | |
Constellation/iv | 64c3a9c7c517063f29d90d449180ea8f6f4d946f | tools/GenerateFile.py | python | TOOL_SUBST | (env) | Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT
from the source to the target.
The values of SUBST_DICT first have any construction variables expanded
(its keys are not expanded).
If a value of SUBST_DICT is a python callable function, it is called and
the result is expanded as the value.
If there's more than one source and more than one target, each target gets
substituted from the corresponding source. | Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT
from the source to the target.
The values of SUBST_DICT first have any construction variables expanded
(its keys are not expanded).
If a value of SUBST_DICT is a python callable function, it is called and
the result is expanded as the value.
If there's more than one source and more than one target, each target gets
substituted from the corresponding source. | [
"Adds",
"SubstInFile",
"builder",
"which",
"substitutes",
"the",
"keys",
"-",
">",
"values",
"of",
"SUBST_DICT",
"from",
"the",
"source",
"to",
"the",
"target",
".",
"The",
"values",
"of",
"SUBST_DICT",
"first",
"have",
"any",
"construction",
"variables",
"expanded",
"(",
"its",
"keys",
"are",
"not",
"expanded",
")",
".",
"If",
"a",
"value",
"of",
"SUBST_DICT",
"is",
"a",
"python",
"callable",
"function",
"it",
"is",
"called",
"and",
"the",
"result",
"is",
"expanded",
"as",
"the",
"value",
".",
"If",
"there",
"s",
"more",
"than",
"one",
"source",
"and",
"more",
"than",
"one",
"target",
"each",
"target",
"gets",
"substituted",
"from",
"the",
"corresponding",
"source",
"."
] | def TOOL_SUBST(env):
"""Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT
from the source to the target.
The values of SUBST_DICT first have any construction variables expanded
(its keys are not expanded).
If a value of SUBST_DICT is a python callable function, it is called and
the result is expanded as the value.
If there's more than one source and more than one target, each target gets
substituted from the corresponding source.
"""
env.Append(TOOLS = 'SUBST')
def do_subst_in_file(targetfile, sourcefile, dict):
"""Replace all instances of the keys of dict with their values.
For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'},
then all instances of %VERSION% in the file will be replaced with 1.2345 etc.
"""
try:
f = open(sourcefile, 'rb')
contents = f.read()
f.close()
except:
raise SCons.Errors.UserError, "Can't read source file %s"%sourcefile
for (k,v) in dict.items():
contents = re.sub(k, v, contents)
try:
f = open(targetfile, 'wb')
f.write(contents)
f.close()
except:
raise SCons.Errors.UserError, "Can't write target file %s"%targetfile
return 0 # success
def subst_in_file(target, source, env):
if 'SUBST_DICT' not in env:
raise SCons.Errors.UserError, "SubstInFile requires SUBST_DICT to be set."
d = dict(env['SUBST_DICT']) # copy it
for (k,v) in d.items():
if callable(v):
d[k] = env.subst(v())
elif SCons.Util.is_String(v):
d[k]=env.subst(v)
else:
raise SCons.Errors.UserError, "SubstInFile: key %s: %s must be a string or callable"%(k, repr(v))
for (t,s) in zip(target, source):
return do_subst_in_file(str(t), str(s), d)
def subst_in_file_string(target, source, env):
"""This is what gets printed on the console."""
return '\n'.join(['Substituting vars from %s into %s'%(str(s), str(t))
for (t,s) in zip(target, source)])
def subst_emitter(target, source, env):
"""Add dependency from substituted SUBST_DICT to target.
Returns original target, source tuple unchanged.
"""
d = env['SUBST_DICT'].copy() # copy it
for (k,v) in d.items():
if callable(v):
d[k] = env.subst(v())
elif SCons.Util.is_String(v):
d[k]=env.subst(v)
Depends(target, SCons.Node.Python.Value(d))
return target, source
subst_action=SCons.Action.Action(subst_in_file, subst_in_file_string)
env['BUILDERS']['SubstInFile'] = Builder(action=subst_action, emitter=subst_emitter) | [
"def",
"TOOL_SUBST",
"(",
"env",
")",
":",
"env",
".",
"Append",
"(",
"TOOLS",
"=",
"'SUBST'",
")",
"def",
"do_subst_in_file",
"(",
"targetfile",
",",
"sourcefile",
",",
"dict",
")",
":",
"\"\"\"Replace all instances of the keys of dict with their values.\n For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'},\n then all instances of %VERSION% in the file will be replaced with 1.2345 etc.\n \"\"\"",
"try",
":",
"f",
"=",
"open",
"(",
"sourcefile",
",",
"'rb'",
")",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"except",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
",",
"\"Can't read source file %s\"",
"%",
"sourcefile",
"for",
"(",
"k",
",",
"v",
")",
"in",
"dict",
".",
"items",
"(",
")",
":",
"contents",
"=",
"re",
".",
"sub",
"(",
"k",
",",
"v",
",",
"contents",
")",
"try",
":",
"f",
"=",
"open",
"(",
"targetfile",
",",
"'wb'",
")",
"f",
".",
"write",
"(",
"contents",
")",
"f",
".",
"close",
"(",
")",
"except",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
",",
"\"Can't write target file %s\"",
"%",
"targetfile",
"return",
"0",
"# success",
"def",
"subst_in_file",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"if",
"'SUBST_DICT'",
"not",
"in",
"env",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
",",
"\"SubstInFile requires SUBST_DICT to be set.\"",
"d",
"=",
"dict",
"(",
"env",
"[",
"'SUBST_DICT'",
"]",
")",
"# copy it",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"callable",
"(",
"v",
")",
":",
"d",
"[",
"k",
"]",
"=",
"env",
".",
"subst",
"(",
"v",
"(",
")",
")",
"elif",
"SCons",
".",
"Util",
".",
"is_String",
"(",
"v",
")",
":",
"d",
"[",
"k",
"]",
"=",
"env",
".",
"subst",
"(",
"v",
")",
"else",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
",",
"\"SubstInFile: key %s: %s must be a string or callable\"",
"%",
"(",
"k",
",",
"repr",
"(",
"v",
")",
")",
"for",
"(",
"t",
",",
"s",
")",
"in",
"zip",
"(",
"target",
",",
"source",
")",
":",
"return",
"do_subst_in_file",
"(",
"str",
"(",
"t",
")",
",",
"str",
"(",
"s",
")",
",",
"d",
")",
"def",
"subst_in_file_string",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"\"\"\"This is what gets printed on the console.\"\"\"",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"'Substituting vars from %s into %s'",
"%",
"(",
"str",
"(",
"s",
")",
",",
"str",
"(",
"t",
")",
")",
"for",
"(",
"t",
",",
"s",
")",
"in",
"zip",
"(",
"target",
",",
"source",
")",
"]",
")",
"def",
"subst_emitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"\"\"\"Add dependency from substituted SUBST_DICT to target.\n Returns original target, source tuple unchanged.\n \"\"\"",
"d",
"=",
"env",
"[",
"'SUBST_DICT'",
"]",
".",
"copy",
"(",
")",
"# copy it",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"callable",
"(",
"v",
")",
":",
"d",
"[",
"k",
"]",
"=",
"env",
".",
"subst",
"(",
"v",
"(",
")",
")",
"elif",
"SCons",
".",
"Util",
".",
"is_String",
"(",
"v",
")",
":",
"d",
"[",
"k",
"]",
"=",
"env",
".",
"subst",
"(",
"v",
")",
"Depends",
"(",
"target",
",",
"SCons",
".",
"Node",
".",
"Python",
".",
"Value",
"(",
"d",
")",
")",
"return",
"target",
",",
"source",
"subst_action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"subst_in_file",
",",
"subst_in_file_string",
")",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'SubstInFile'",
"]",
"=",
"Builder",
"(",
"action",
"=",
"subst_action",
",",
"emitter",
"=",
"subst_emitter",
")"
] | https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/GenerateFile.py#L4-L69 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/device_worker.py | python | Hogwild.__init__ | (self) | Init. | Init. | [
"Init",
"."
] | def __init__(self):
"""Init."""
super(Hogwild, self).__init__() | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"Hogwild",
",",
"self",
")",
".",
"__init__",
"(",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/device_worker.py#L81-L83 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/special/orthogonal.py | python | roots_legendre | (n, mu=False) | return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu) | r"""Gauss-Legendre quadrature.
Computes the sample points and weights for Gauss-Legendre quadrature.
The sample points are the roots of the n-th degree Legendre polynomial
:math:`P_n(x)`. These sample points and weights correctly integrate
polynomials of degree :math:`2n - 1` or less over the interval
:math:`[-1, 1]` with weight function :math:`f(x) = 1.0`.
Parameters
----------
n : int
quadrature order
mu : bool, optional
If True, return the sum of the weights, optional.
Returns
-------
x : ndarray
Sample points
w : ndarray
Weights
mu : float
Sum of the weights
See Also
--------
scipy.integrate.quadrature
scipy.integrate.fixed_quad
numpy.polynomial.legendre.leggauss | r"""Gauss-Legendre quadrature. | [
"r",
"Gauss",
"-",
"Legendre",
"quadrature",
"."
] | def roots_legendre(n, mu=False):
r"""Gauss-Legendre quadrature.
Computes the sample points and weights for Gauss-Legendre quadrature.
The sample points are the roots of the n-th degree Legendre polynomial
:math:`P_n(x)`. These sample points and weights correctly integrate
polynomials of degree :math:`2n - 1` or less over the interval
:math:`[-1, 1]` with weight function :math:`f(x) = 1.0`.
Parameters
----------
n : int
quadrature order
mu : bool, optional
If True, return the sum of the weights, optional.
Returns
-------
x : ndarray
Sample points
w : ndarray
Weights
mu : float
Sum of the weights
See Also
--------
scipy.integrate.quadrature
scipy.integrate.fixed_quad
numpy.polynomial.legendre.leggauss
"""
m = int(n)
if n < 1 or n != m:
raise ValueError("n must be a positive integer.")
mu0 = 2.0
an_func = lambda k: 0.0 * k
bn_func = lambda k: k * np.sqrt(1.0 / (4 * k * k - 1))
f = cephes.eval_legendre
df = lambda n, x: (-n*x*cephes.eval_legendre(n, x)
+ n*cephes.eval_legendre(n-1, x))/(1-x**2)
return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu) | [
"def",
"roots_legendre",
"(",
"n",
",",
"mu",
"=",
"False",
")",
":",
"m",
"=",
"int",
"(",
"n",
")",
"if",
"n",
"<",
"1",
"or",
"n",
"!=",
"m",
":",
"raise",
"ValueError",
"(",
"\"n must be a positive integer.\"",
")",
"mu0",
"=",
"2.0",
"an_func",
"=",
"lambda",
"k",
":",
"0.0",
"*",
"k",
"bn_func",
"=",
"lambda",
"k",
":",
"k",
"*",
"np",
".",
"sqrt",
"(",
"1.0",
"/",
"(",
"4",
"*",
"k",
"*",
"k",
"-",
"1",
")",
")",
"f",
"=",
"cephes",
".",
"eval_legendre",
"df",
"=",
"lambda",
"n",
",",
"x",
":",
"(",
"-",
"n",
"*",
"x",
"*",
"cephes",
".",
"eval_legendre",
"(",
"n",
",",
"x",
")",
"+",
"n",
"*",
"cephes",
".",
"eval_legendre",
"(",
"n",
"-",
"1",
",",
"x",
")",
")",
"/",
"(",
"1",
"-",
"x",
"**",
"2",
")",
"return",
"_gen_roots_and_weights",
"(",
"m",
",",
"mu0",
",",
"an_func",
",",
"bn_func",
",",
"f",
",",
"df",
",",
"True",
",",
"mu",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/special/orthogonal.py#L1884-L1925 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/package.py | python | Package.validate | (self, warnings=None) | makes sure all standards for packages are met
:param package: Package to check
:param warnings: Print warnings if None or return them in the given list
:raises InvalidPackage: in case validation fails | makes sure all standards for packages are met
:param package: Package to check
:param warnings: Print warnings if None or return them in the given list
:raises InvalidPackage: in case validation fails | [
"makes",
"sure",
"all",
"standards",
"for",
"packages",
"are",
"met",
":",
"param",
"package",
":",
"Package",
"to",
"check",
":",
"param",
"warnings",
":",
"Print",
"warnings",
"if",
"None",
"or",
"return",
"them",
"in",
"the",
"given",
"list",
":",
"raises",
"InvalidPackage",
":",
"in",
"case",
"validation",
"fails"
] | def validate(self, warnings=None):
"""
makes sure all standards for packages are met
:param package: Package to check
:param warnings: Print warnings if None or return them in the given list
:raises InvalidPackage: in case validation fails
"""
errors = []
new_warnings = []
if self.package_format:
if not re.match('^[1-9][0-9]*$', str(self.package_format)):
errors.append('The "format" attribute of the package must contain a positive integer if present')
if not self.name:
errors.append('Package name must not be empty')
# accepting upper case letters and hyphens only for backward compatibility
if not re.match('^[a-zA-Z0-9][a-zA-Z0-9_-]*$', self.name):
errors.append('Package name "%s" does not follow naming conventions' % self.name)
elif not re.match('^[a-z][a-z0-9_]*$', self.name):
new_warnings.append('Package name "%s" does not follow the naming conventions. It should start with a lower case letter and only contain lower case letters, digits and underscores.' % self.name)
if not self.version:
errors.append('Package version must not be empty')
elif not re.match('^[0-9]+\.[0-9]+\.[0-9]+$', self.version):
errors.append('Package version "%s" does not follow version conventions' % self.version)
elif not re.match('^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$', self.version):
new_warnings.append('Package "%s" does not follow the version conventions. It should not contain leading zeros (unless the number is 0).' % self.name)
if not self.description:
errors.append('Package description must not be empty')
if not self.maintainers:
errors.append('Package must declare at least one maintainer')
for maintainer in self.maintainers:
try:
maintainer.validate()
except InvalidPackage as e:
errors.append(str(e))
if not maintainer.email:
errors.append('Maintainers must have an email address')
if not self.licenses:
errors.append('The package node must contain at least one "license" tag')
if [l for l in self.licenses if not l.strip()]:
errors.append('The license tag must neither be empty nor only contain whitespaces')
if self.authors is not None:
for author in self.authors:
try:
author.validate()
except InvalidPackage as e:
errors.append(str(e))
dep_types = {
'build': self.build_depends,
'buildtool': self.buildtool_depends,
'build_export': self.build_export_depends,
'buildtool_export': self.buildtool_export_depends,
'exec': self.exec_depends,
'test': self.test_depends,
'doc': self.doc_depends
}
for dep_type, depends in dep_types.items():
for depend in depends:
if depend.name == self.name:
errors.append('The package must not "%s_depend" on a package with the same name as this package' % dep_type)
if self.is_metapackage():
if not self.has_buildtool_depend_on_catkin():
# TODO escalate to error in the future, or use metapackage.validate_metapackage
new_warnings.append('Metapackage "%s" must buildtool_depend on catkin.' % self.name)
if self.has_invalid_metapackage_dependencies():
new_warnings.append('Metapackage "%s" should not have other dependencies besides a '
'buildtool_depend on catkin and run_depends.' % self.name)
for warning in new_warnings:
if warnings is None:
print('WARNING: ' + warning, file=sys.stderr)
elif warning not in warnings:
warnings.append(warning)
if errors:
raise InvalidPackage('\n'.join(errors)) | [
"def",
"validate",
"(",
"self",
",",
"warnings",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"]",
"new_warnings",
"=",
"[",
"]",
"if",
"self",
".",
"package_format",
":",
"if",
"not",
"re",
".",
"match",
"(",
"'^[1-9][0-9]*$'",
",",
"str",
"(",
"self",
".",
"package_format",
")",
")",
":",
"errors",
".",
"append",
"(",
"'The \"format\" attribute of the package must contain a positive integer if present'",
")",
"if",
"not",
"self",
".",
"name",
":",
"errors",
".",
"append",
"(",
"'Package name must not be empty'",
")",
"# accepting upper case letters and hyphens only for backward compatibility",
"if",
"not",
"re",
".",
"match",
"(",
"'^[a-zA-Z0-9][a-zA-Z0-9_-]*$'",
",",
"self",
".",
"name",
")",
":",
"errors",
".",
"append",
"(",
"'Package name \"%s\" does not follow naming conventions'",
"%",
"self",
".",
"name",
")",
"elif",
"not",
"re",
".",
"match",
"(",
"'^[a-z][a-z0-9_]*$'",
",",
"self",
".",
"name",
")",
":",
"new_warnings",
".",
"append",
"(",
"'Package name \"%s\" does not follow the naming conventions. It should start with a lower case letter and only contain lower case letters, digits and underscores.'",
"%",
"self",
".",
"name",
")",
"if",
"not",
"self",
".",
"version",
":",
"errors",
".",
"append",
"(",
"'Package version must not be empty'",
")",
"elif",
"not",
"re",
".",
"match",
"(",
"'^[0-9]+\\.[0-9]+\\.[0-9]+$'",
",",
"self",
".",
"version",
")",
":",
"errors",
".",
"append",
"(",
"'Package version \"%s\" does not follow version conventions'",
"%",
"self",
".",
"version",
")",
"elif",
"not",
"re",
".",
"match",
"(",
"'^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$'",
",",
"self",
".",
"version",
")",
":",
"new_warnings",
".",
"append",
"(",
"'Package \"%s\" does not follow the version conventions. It should not contain leading zeros (unless the number is 0).'",
"%",
"self",
".",
"name",
")",
"if",
"not",
"self",
".",
"description",
":",
"errors",
".",
"append",
"(",
"'Package description must not be empty'",
")",
"if",
"not",
"self",
".",
"maintainers",
":",
"errors",
".",
"append",
"(",
"'Package must declare at least one maintainer'",
")",
"for",
"maintainer",
"in",
"self",
".",
"maintainers",
":",
"try",
":",
"maintainer",
".",
"validate",
"(",
")",
"except",
"InvalidPackage",
"as",
"e",
":",
"errors",
".",
"append",
"(",
"str",
"(",
"e",
")",
")",
"if",
"not",
"maintainer",
".",
"email",
":",
"errors",
".",
"append",
"(",
"'Maintainers must have an email address'",
")",
"if",
"not",
"self",
".",
"licenses",
":",
"errors",
".",
"append",
"(",
"'The package node must contain at least one \"license\" tag'",
")",
"if",
"[",
"l",
"for",
"l",
"in",
"self",
".",
"licenses",
"if",
"not",
"l",
".",
"strip",
"(",
")",
"]",
":",
"errors",
".",
"append",
"(",
"'The license tag must neither be empty nor only contain whitespaces'",
")",
"if",
"self",
".",
"authors",
"is",
"not",
"None",
":",
"for",
"author",
"in",
"self",
".",
"authors",
":",
"try",
":",
"author",
".",
"validate",
"(",
")",
"except",
"InvalidPackage",
"as",
"e",
":",
"errors",
".",
"append",
"(",
"str",
"(",
"e",
")",
")",
"dep_types",
"=",
"{",
"'build'",
":",
"self",
".",
"build_depends",
",",
"'buildtool'",
":",
"self",
".",
"buildtool_depends",
",",
"'build_export'",
":",
"self",
".",
"build_export_depends",
",",
"'buildtool_export'",
":",
"self",
".",
"buildtool_export_depends",
",",
"'exec'",
":",
"self",
".",
"exec_depends",
",",
"'test'",
":",
"self",
".",
"test_depends",
",",
"'doc'",
":",
"self",
".",
"doc_depends",
"}",
"for",
"dep_type",
",",
"depends",
"in",
"dep_types",
".",
"items",
"(",
")",
":",
"for",
"depend",
"in",
"depends",
":",
"if",
"depend",
".",
"name",
"==",
"self",
".",
"name",
":",
"errors",
".",
"append",
"(",
"'The package must not \"%s_depend\" on a package with the same name as this package'",
"%",
"dep_type",
")",
"if",
"self",
".",
"is_metapackage",
"(",
")",
":",
"if",
"not",
"self",
".",
"has_buildtool_depend_on_catkin",
"(",
")",
":",
"# TODO escalate to error in the future, or use metapackage.validate_metapackage",
"new_warnings",
".",
"append",
"(",
"'Metapackage \"%s\" must buildtool_depend on catkin.'",
"%",
"self",
".",
"name",
")",
"if",
"self",
".",
"has_invalid_metapackage_dependencies",
"(",
")",
":",
"new_warnings",
".",
"append",
"(",
"'Metapackage \"%s\" should not have other dependencies besides a '",
"'buildtool_depend on catkin and run_depends.'",
"%",
"self",
".",
"name",
")",
"for",
"warning",
"in",
"new_warnings",
":",
"if",
"warnings",
"is",
"None",
":",
"print",
"(",
"'WARNING: '",
"+",
"warning",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"elif",
"warning",
"not",
"in",
"warnings",
":",
"warnings",
".",
"append",
"(",
"warning",
")",
"if",
"errors",
":",
"raise",
"InvalidPackage",
"(",
"'\\n'",
".",
"join",
"(",
"errors",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/package.py#L161-L244 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStr.InsStr | (self, *args) | return _snap.TStr_InsStr(self, *args) | InsStr(TStr self, int const & BChN, TStr Str)
Parameters:
BChN: int const &
Str: TStr const & | InsStr(TStr self, int const & BChN, TStr Str) | [
"InsStr",
"(",
"TStr",
"self",
"int",
"const",
"&",
"BChN",
"TStr",
"Str",
")"
] | def InsStr(self, *args):
"""
InsStr(TStr self, int const & BChN, TStr Str)
Parameters:
BChN: int const &
Str: TStr const &
"""
return _snap.TStr_InsStr(self, *args) | [
"def",
"InsStr",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStr_InsStr",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L9899-L9908 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/serialport/serialportmap.py | python | SerialPortMap.__init__ | (self) | Create map of tools and ports based on serial number matching. Method used is
very different on Windows and other platforms. | Create map of tools and ports based on serial number matching. Method used is
very different on Windows and other platforms. | [
"Create",
"map",
"of",
"tools",
"and",
"ports",
"based",
"on",
"serial",
"number",
"matching",
".",
"Method",
"used",
"is",
"very",
"different",
"on",
"Windows",
"and",
"other",
"platforms",
"."
] | def __init__(self):
"""
Create map of tools and ports based on serial number matching. Method used is
very different on Windows and other platforms.
"""
# Hook onto logger
self.logger = getLogger(__name__)
self.portmap = []
tools = hid_transport().devices
if os.name == "nt":
# On Windows, use registry lookup impemented in wincdc.py
cdc = CDC()
for tool in tools:
if tool.serial_number:
name = tool.product_string.split(" ")[0].lower()
port = cdc.find_cdc_port(name, tool.serial_number)
if port:
self.portmap.append({"tool": tool, "port": port})
else:
# On Mac & Linux, all info needed is found using serial.ports.list_ports.
usbports = [p for p in serial.tools.list_ports.comports() if "USB" in p.hwid]
for tool in tools:
for port in usbports:
if tool.serial_number and tool.serial_number == port.serial_number:
self.portmap.append({"tool": tool, "port": port.device}) | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Hook onto logger",
"self",
".",
"logger",
"=",
"getLogger",
"(",
"__name__",
")",
"self",
".",
"portmap",
"=",
"[",
"]",
"tools",
"=",
"hid_transport",
"(",
")",
".",
"devices",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"# On Windows, use registry lookup impemented in wincdc.py",
"cdc",
"=",
"CDC",
"(",
")",
"for",
"tool",
"in",
"tools",
":",
"if",
"tool",
".",
"serial_number",
":",
"name",
"=",
"tool",
".",
"product_string",
".",
"split",
"(",
"\" \"",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"port",
"=",
"cdc",
".",
"find_cdc_port",
"(",
"name",
",",
"tool",
".",
"serial_number",
")",
"if",
"port",
":",
"self",
".",
"portmap",
".",
"append",
"(",
"{",
"\"tool\"",
":",
"tool",
",",
"\"port\"",
":",
"port",
"}",
")",
"else",
":",
"# On Mac & Linux, all info needed is found using serial.ports.list_ports.",
"usbports",
"=",
"[",
"p",
"for",
"p",
"in",
"serial",
".",
"tools",
".",
"list_ports",
".",
"comports",
"(",
")",
"if",
"\"USB\"",
"in",
"p",
".",
"hwid",
"]",
"for",
"tool",
"in",
"tools",
":",
"for",
"port",
"in",
"usbports",
":",
"if",
"tool",
".",
"serial_number",
"and",
"tool",
".",
"serial_number",
"==",
"port",
".",
"serial_number",
":",
"self",
".",
"portmap",
".",
"append",
"(",
"{",
"\"tool\"",
":",
"tool",
",",
"\"port\"",
":",
"port",
".",
"device",
"}",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/serialport/serialportmap.py#L21-L46 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/cmdoptions.py | python | _convert_python_version | (value) | return (version_info, None) | Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is
non-None if and only if there was a parsing error. | Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. | [
"Convert",
"a",
"version",
"string",
"like",
"3",
"37",
"or",
"3",
".",
"7",
".",
"3",
"into",
"a",
"tuple",
"of",
"ints",
"."
] | def _convert_python_version(value):
# type: (str) -> Tuple[Tuple[int, ...], Optional[str]]
"""
Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is
non-None if and only if there was a parsing error.
"""
if not value:
# The empty string is the same as not providing a value.
return (None, None)
parts = value.split('.')
if len(parts) > 3:
return ((), 'at most three version parts are allowed')
if len(parts) == 1:
# Then we are in the case of "3" or "37".
value = parts[0]
if len(value) > 1:
parts = [value[0], value[1:]]
try:
version_info = tuple(int(part) for part in parts)
except ValueError:
return ((), 'each version part must be an integer')
return (version_info, None) | [
"def",
"_convert_python_version",
"(",
"value",
")",
":",
"# type: (str) -> Tuple[Tuple[int, ...], Optional[str]]",
"if",
"not",
"value",
":",
"# The empty string is the same as not providing a value.",
"return",
"(",
"None",
",",
"None",
")",
"parts",
"=",
"value",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
">",
"3",
":",
"return",
"(",
"(",
")",
",",
"'at most three version parts are allowed'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"# Then we are in the case of \"3\" or \"37\".",
"value",
"=",
"parts",
"[",
"0",
"]",
"if",
"len",
"(",
"value",
")",
">",
"1",
":",
"parts",
"=",
"[",
"value",
"[",
"0",
"]",
",",
"value",
"[",
"1",
":",
"]",
"]",
"try",
":",
"version_info",
"=",
"tuple",
"(",
"int",
"(",
"part",
")",
"for",
"part",
"in",
"parts",
")",
"except",
"ValueError",
":",
"return",
"(",
"(",
")",
",",
"'each version part must be an integer'",
")",
"return",
"(",
"version_info",
",",
"None",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/cmdoptions.py#L513-L540 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py | python | _handle_ns | (packageName, path_item) | return subpath | Ensure that named package includes a subpath of path_item (if needed) | Ensure that named package includes a subpath of path_item (if needed) | [
"Ensure",
"that",
"named",
"package",
"includes",
"a",
"subpath",
"of",
"path_item",
"(",
"if",
"needed",
")"
] | def _handle_ns(packageName, path_item):
"""Ensure that named package includes a subpath of path_item (if needed)"""
importer = get_importer(path_item)
if importer is None:
return None
# capture warnings due to #1111
with warnings.catch_warnings():
warnings.simplefilter("ignore")
loader = importer.find_module(packageName)
if loader is None:
return None
module = sys.modules.get(packageName)
if module is None:
module = sys.modules[packageName] = types.ModuleType(packageName)
module.__path__ = []
_set_parent_ns(packageName)
elif not hasattr(module, '__path__'):
raise TypeError("Not a package:", packageName)
handler = _find_adapter(_namespace_handlers, importer)
subpath = handler(importer, path_item, packageName, module)
if subpath is not None:
path = module.__path__
path.append(subpath)
loader.load_module(packageName)
_rebuild_mod_path(path, packageName, module)
return subpath | [
"def",
"_handle_ns",
"(",
"packageName",
",",
"path_item",
")",
":",
"importer",
"=",
"get_importer",
"(",
"path_item",
")",
"if",
"importer",
"is",
"None",
":",
"return",
"None",
"# capture warnings due to #1111",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"loader",
"=",
"importer",
".",
"find_module",
"(",
"packageName",
")",
"if",
"loader",
"is",
"None",
":",
"return",
"None",
"module",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"packageName",
")",
"if",
"module",
"is",
"None",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"packageName",
"]",
"=",
"types",
".",
"ModuleType",
"(",
"packageName",
")",
"module",
".",
"__path__",
"=",
"[",
"]",
"_set_parent_ns",
"(",
"packageName",
")",
"elif",
"not",
"hasattr",
"(",
"module",
",",
"'__path__'",
")",
":",
"raise",
"TypeError",
"(",
"\"Not a package:\"",
",",
"packageName",
")",
"handler",
"=",
"_find_adapter",
"(",
"_namespace_handlers",
",",
"importer",
")",
"subpath",
"=",
"handler",
"(",
"importer",
",",
"path_item",
",",
"packageName",
",",
"module",
")",
"if",
"subpath",
"is",
"not",
"None",
":",
"path",
"=",
"module",
".",
"__path__",
"path",
".",
"append",
"(",
"subpath",
")",
"loader",
".",
"load_module",
"(",
"packageName",
")",
"_rebuild_mod_path",
"(",
"path",
",",
"packageName",
",",
"module",
")",
"return",
"subpath"
] | 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/pkg_resources/__init__.py#L2094-L2122 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/backend.py | python | std | (x, axis=None, keepdims=False) | return math_ops.sqrt(var(x, axis=axis, keepdims=keepdims)) | Standard deviation of a tensor, alongside the specified axis.
Arguments:
x: A tensor or variable.
axis: An integer, the axis to compute the standard deviation.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
Returns:
A tensor with the standard deviation of elements of `x`. | Standard deviation of a tensor, alongside the specified axis. | [
"Standard",
"deviation",
"of",
"a",
"tensor",
"alongside",
"the",
"specified",
"axis",
"."
] | def std(x, axis=None, keepdims=False):
"""Standard deviation of a tensor, alongside the specified axis.
Arguments:
x: A tensor or variable.
axis: An integer, the axis to compute the standard deviation.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
Returns:
A tensor with the standard deviation of elements of `x`.
"""
return math_ops.sqrt(var(x, axis=axis, keepdims=keepdims)) | [
"def",
"std",
"(",
"x",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"return",
"math_ops",
".",
"sqrt",
"(",
"var",
"(",
"x",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"keepdims",
")",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L1473-L1487 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStrV.AddSorted | (self, *args) | return _snap.TStrV_AddSorted(self, *args) | AddSorted(TStrV self, TStr Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TStr const &
Asc: bool const &
_MxVals: int const &
AddSorted(TStrV self, TStr Val, bool const & Asc=True) -> int
Parameters:
Val: TStr const &
Asc: bool const &
AddSorted(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const & | AddSorted(TStrV self, TStr Val, bool const & Asc=True, int const & _MxVals=-1) -> int | [
"AddSorted",
"(",
"TStrV",
"self",
"TStr",
"Val",
"bool",
"const",
"&",
"Asc",
"=",
"True",
"int",
"const",
"&",
"_MxVals",
"=",
"-",
"1",
")",
"-",
">",
"int"
] | def AddSorted(self, *args):
"""
AddSorted(TStrV self, TStr Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TStr const &
Asc: bool const &
_MxVals: int const &
AddSorted(TStrV self, TStr Val, bool const & Asc=True) -> int
Parameters:
Val: TStr const &
Asc: bool const &
AddSorted(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_AddSorted(self, *args) | [
"def",
"AddSorted",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStrV_AddSorted",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19457-L19478 | |
uber/neuropod | de304c40ec0634a868d7ef41ba7bf89ebc364f10 | source/python/neuropod/backends/torchscript/packager.py | python | create_torchscript_neuropod | (neuropod_path, module=None, module_path=None, **kwargs) | Packages a TorchScript model as a neuropod package.
{common_doc_pre}
:param module: An instance of a PyTorch ScriptModule. This model should return the outputs
as a dictionary. If this is not provided, `module_path` must be set.
!!! note ""
For example, a model may output something like this:
```
{
"output1": value1,
"output2": value2,
}
```
:param module_path: The path to a ScriptModule that was already exported using `torch.jit.save`.
If this is not provided, `module` must be set.
{common_doc_post} | Packages a TorchScript model as a neuropod package. | [
"Packages",
"a",
"TorchScript",
"model",
"as",
"a",
"neuropod",
"package",
"."
] | def create_torchscript_neuropod(neuropod_path, module=None, module_path=None, **kwargs):
"""
Packages a TorchScript model as a neuropod package.
{common_doc_pre}
:param module: An instance of a PyTorch ScriptModule. This model should return the outputs
as a dictionary. If this is not provided, `module_path` must be set.
!!! note ""
For example, a model may output something like this:
```
{
"output1": value1,
"output2": value2,
}
```
:param module_path: The path to a ScriptModule that was already exported using `torch.jit.save`.
If this is not provided, `module` must be set.
{common_doc_post}
"""
# Make sure the inputs are valid
if (module is None) == (module_path is None):
# If they are both None or both not None
raise ValueError("Exactly one of 'module' and 'module_path' must be provided.")
# Create a folder to store the model
neuropod_data_path = os.path.join(neuropod_path, "0", "data")
os.makedirs(neuropod_data_path)
# Add the model to the neuropod
model_path = os.path.join(neuropod_data_path, "model.pt")
if module_path is not None:
# Copy in the module
shutil.copyfile(module_path, model_path)
else:
# Save the model
torch.jit.save(module, model_path) | [
"def",
"create_torchscript_neuropod",
"(",
"neuropod_path",
",",
"module",
"=",
"None",
",",
"module_path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make sure the inputs are valid",
"if",
"(",
"module",
"is",
"None",
")",
"==",
"(",
"module_path",
"is",
"None",
")",
":",
"# If they are both None or both not None",
"raise",
"ValueError",
"(",
"\"Exactly one of 'module' and 'module_path' must be provided.\"",
")",
"# Create a folder to store the model",
"neuropod_data_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"neuropod_path",
",",
"\"0\"",
",",
"\"data\"",
")",
"os",
".",
"makedirs",
"(",
"neuropod_data_path",
")",
"# Add the model to the neuropod",
"model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"neuropod_data_path",
",",
"\"model.pt\"",
")",
"if",
"module_path",
"is",
"not",
"None",
":",
"# Copy in the module",
"shutil",
".",
"copyfile",
"(",
"module_path",
",",
"model_path",
")",
"else",
":",
"# Save the model",
"torch",
".",
"jit",
".",
"save",
"(",
"module",
",",
"model_path",
")"
] | https://github.com/uber/neuropod/blob/de304c40ec0634a868d7ef41ba7bf89ebc364f10/source/python/neuropod/backends/torchscript/packager.py#L23-L62 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ntpath.py | python | islink | (path) | return stat.S_ISLNK(st.st_mode) | Test whether a path is a symbolic link.
This will always return false for Windows prior to 6.0. | Test whether a path is a symbolic link.
This will always return false for Windows prior to 6.0. | [
"Test",
"whether",
"a",
"path",
"is",
"a",
"symbolic",
"link",
".",
"This",
"will",
"always",
"return",
"false",
"for",
"Windows",
"prior",
"to",
"6",
".",
"0",
"."
] | def islink(path):
"""Test whether a path is a symbolic link.
This will always return false for Windows prior to 6.0.
"""
try:
st = os.lstat(path)
except (OSError, AttributeError):
return False
return stat.S_ISLNK(st.st_mode) | [
"def",
"islink",
"(",
"path",
")",
":",
"try",
":",
"st",
"=",
"os",
".",
"lstat",
"(",
"path",
")",
"except",
"(",
"OSError",
",",
"AttributeError",
")",
":",
"return",
"False",
"return",
"stat",
".",
"S_ISLNK",
"(",
"st",
".",
"st_mode",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ntpath.py#L226-L234 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_stc.py | python | EditraStc.WordPartLeftExtend | (self) | Extend selection left to the next change in c
apitalization/punctuation.
@note: overrides default function to not count whitespace as words | Extend selection left to the next change in c
apitalization/punctuation.
@note: overrides default function to not count whitespace as words | [
"Extend",
"selection",
"left",
"to",
"the",
"next",
"change",
"in",
"c",
"apitalization",
"/",
"punctuation",
".",
"@note",
":",
"overrides",
"default",
"function",
"to",
"not",
"count",
"whitespace",
"as",
"words"
] | def WordPartLeftExtend(self): # pylint: disable-msg=W0221
"""Extend selection left to the next change in c
apitalization/punctuation.
@note: overrides default function to not count whitespace as words
"""
super(EditraStc, self).WordPartLeftExtend()
cpos = self.GetCurrentPos()
if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:
super(EditraStc, self).WordPartLeftExtend() | [
"def",
"WordPartLeftExtend",
"(",
"self",
")",
":",
"# pylint: disable-msg=W0221",
"super",
"(",
"EditraStc",
",",
"self",
")",
".",
"WordPartLeftExtend",
"(",
")",
"cpos",
"=",
"self",
".",
"GetCurrentPos",
"(",
")",
"if",
"self",
".",
"GetTextRange",
"(",
"cpos",
",",
"cpos",
"+",
"1",
")",
"in",
"SPACECHARS",
":",
"super",
"(",
"EditraStc",
",",
"self",
")",
".",
"WordPartLeftExtend",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L1717-L1726 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/special/orthogonal.py | python | s_roots | (n, mu=False) | r"""Gauss-Chebyshev (second kind) quadrature.
Computes the sample points and weights for Gauss-Chebyshev quadrature.
The sample points are the roots of the n-th degree Chebyshev polynomial of
the second kind, :math:`S_n(x)`. These sample points and weights correctly
integrate polynomials of degree :math:`2n - 1` or less over the interval
:math:`[-2, 2]` with weight function :math:`f(x) = \sqrt{1 - (x/2)^2}`.
Parameters
----------
n : int
quadrature order
mu : bool, optional
If True, return the sum of the weights, optional.
Returns
-------
x : ndarray
Sample points
w : ndarray
Weights
mu : float
Sum of the weights
See Also
--------
scipy.integrate.quadrature
scipy.integrate.fixed_quad | r"""Gauss-Chebyshev (second kind) quadrature. | [
"r",
"Gauss",
"-",
"Chebyshev",
"(",
"second",
"kind",
")",
"quadrature",
"."
] | def s_roots(n, mu=False):
r"""Gauss-Chebyshev (second kind) quadrature.
Computes the sample points and weights for Gauss-Chebyshev quadrature.
The sample points are the roots of the n-th degree Chebyshev polynomial of
the second kind, :math:`S_n(x)`. These sample points and weights correctly
integrate polynomials of degree :math:`2n - 1` or less over the interval
:math:`[-2, 2]` with weight function :math:`f(x) = \sqrt{1 - (x/2)^2}`.
Parameters
----------
n : int
quadrature order
mu : bool, optional
If True, return the sum of the weights, optional.
Returns
-------
x : ndarray
Sample points
w : ndarray
Weights
mu : float
Sum of the weights
See Also
--------
scipy.integrate.quadrature
scipy.integrate.fixed_quad
"""
x, w, m = u_roots(n, True)
x *= 2
w *= 2
m *= 2
if mu:
return x, w, m
else:
return x, w | [
"def",
"s_roots",
"(",
"n",
",",
"mu",
"=",
"False",
")",
":",
"x",
",",
"w",
",",
"m",
"=",
"u_roots",
"(",
"n",
",",
"True",
")",
"x",
"*=",
"2",
"w",
"*=",
"2",
"m",
"*=",
"2",
"if",
"mu",
":",
"return",
"x",
",",
"w",
",",
"m",
"else",
":",
"return",
"x",
",",
"w"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/special/orthogonal.py#L1629-L1666 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/sort-headers.py | python | IsInclude | (line) | return line.startswith('#include ') or line.startswith('#import ') | Returns True if the line is an #include/#import line. | Returns True if the line is an #include/#import line. | [
"Returns",
"True",
"if",
"the",
"line",
"is",
"an",
"#include",
"/",
"#import",
"line",
"."
] | def IsInclude(line):
"""Returns True if the line is an #include/#import line."""
return line.startswith('#include ') or line.startswith('#import ') | [
"def",
"IsInclude",
"(",
"line",
")",
":",
"return",
"line",
".",
"startswith",
"(",
"'#include '",
")",
"or",
"line",
".",
"startswith",
"(",
"'#import '",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/sort-headers.py#L69-L71 | |
cmu-db/noisepage | 79276e68fe83322f1249e8a8be96bd63c583ae56 | build-support/run-clang-tidy.py | python | run_tidy | (args, tmpdir, build_path, queue, lock, failed_files) | Takes filenames out of queue and runs clang-tidy on them. | Takes filenames out of queue and runs clang-tidy on them. | [
"Takes",
"filenames",
"out",
"of",
"queue",
"and",
"runs",
"clang",
"-",
"tidy",
"on",
"them",
"."
] | def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
"""Takes filenames out of queue and runs clang-tidy on them."""
while True:
name = queue.get()
print("\r Checking: {}".format(name), end='')
sys.stdout.flush()
invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
tmpdir, build_path, args.header_filter,
args.extra_arg, args.extra_arg_before,
args.quiet, args.config)
proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = proc.communicate()
if proc.returncode != 0:
failed_files.append(name)
# NOISEPAGE: we write our own printing logic
# with lock:
# sys.stdout.write(' '.join(invocation) + '\n' + output + '\n')
# if err > 0:
# sys.stderr.write(err + '\n')
# In particular, we only want important lines:
with lock:
output = output.decode('utf-8') if output is not None else None
err = err.decode('utf-8') if output is not None else None
# unfortunately, our error messages are actually on STDOUT
# STDERR tells how many warnings are generated,
# but this includes non-user-code warnings, so it is useless...
if output:
sys.stdout.write('\n')
sys.stdout.write(output)
queue.task_done() | [
"def",
"run_tidy",
"(",
"args",
",",
"tmpdir",
",",
"build_path",
",",
"queue",
",",
"lock",
",",
"failed_files",
")",
":",
"while",
"True",
":",
"name",
"=",
"queue",
".",
"get",
"(",
")",
"print",
"(",
"\"\\r Checking: {}\"",
".",
"format",
"(",
"name",
")",
",",
"end",
"=",
"''",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"invocation",
"=",
"get_tidy_invocation",
"(",
"name",
",",
"args",
".",
"clang_tidy_binary",
",",
"args",
".",
"checks",
",",
"tmpdir",
",",
"build_path",
",",
"args",
".",
"header_filter",
",",
"args",
".",
"extra_arg",
",",
"args",
".",
"extra_arg_before",
",",
"args",
".",
"quiet",
",",
"args",
".",
"config",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"invocation",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"output",
",",
"err",
"=",
"proc",
".",
"communicate",
"(",
")",
"if",
"proc",
".",
"returncode",
"!=",
"0",
":",
"failed_files",
".",
"append",
"(",
"name",
")",
"# NOISEPAGE: we write our own printing logic",
"# with lock:",
"# sys.stdout.write(' '.join(invocation) + '\\n' + output + '\\n')",
"# if err > 0:",
"# sys.stderr.write(err + '\\n')",
"# In particular, we only want important lines:",
"with",
"lock",
":",
"output",
"=",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"output",
"is",
"not",
"None",
"else",
"None",
"err",
"=",
"err",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"output",
"is",
"not",
"None",
"else",
"None",
"# unfortunately, our error messages are actually on STDOUT",
"# STDERR tells how many warnings are generated,",
"# but this includes non-user-code warnings, so it is useless...",
"if",
"output",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"output",
")",
"queue",
".",
"task_done",
"(",
")"
] | https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/run-clang-tidy.py#L156-L185 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/tkFileDialog.py | python | asksaveasfilename | (**options) | return SaveAs(**options).show() | Ask for a filename to save as | Ask for a filename to save as | [
"Ask",
"for",
"a",
"filename",
"to",
"save",
"as"
] | def asksaveasfilename(**options):
"Ask for a filename to save as"
return SaveAs(**options).show() | [
"def",
"asksaveasfilename",
"(",
"*",
"*",
"options",
")",
":",
"return",
"SaveAs",
"(",
"*",
"*",
"options",
")",
".",
"show",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/tkFileDialog.py#L127-L130 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Script/SConscript.py | python | SConsEnvironment._get_SConscript_filenames | (self, ls, kw) | return (files, exports) | Convert the parameters passed to SConscript() calls into a list
of files and export variables. If the parameters are invalid,
throws SCons.Errors.UserError. Returns a tuple (l, e) where l
is a list of SConscript filenames and e is a list of exports. | Convert the parameters passed to SConscript() calls into a list
of files and export variables. If the parameters are invalid,
throws SCons.Errors.UserError. Returns a tuple (l, e) where l
is a list of SConscript filenames and e is a list of exports. | [
"Convert",
"the",
"parameters",
"passed",
"to",
"SConscript",
"()",
"calls",
"into",
"a",
"list",
"of",
"files",
"and",
"export",
"variables",
".",
"If",
"the",
"parameters",
"are",
"invalid",
"throws",
"SCons",
".",
"Errors",
".",
"UserError",
".",
"Returns",
"a",
"tuple",
"(",
"l",
"e",
")",
"where",
"l",
"is",
"a",
"list",
"of",
"SConscript",
"filenames",
"and",
"e",
"is",
"a",
"list",
"of",
"exports",
"."
] | def _get_SConscript_filenames(self, ls, kw):
"""
Convert the parameters passed to SConscript() calls into a list
of files and export variables. If the parameters are invalid,
throws SCons.Errors.UserError. Returns a tuple (l, e) where l
is a list of SConscript filenames and e is a list of exports.
"""
exports = []
if len(ls) == 0:
try:
dirs = kw["dirs"]
except KeyError:
raise SCons.Errors.UserError("Invalid SConscript usage - no parameters")
if not is_List(dirs):
dirs = [ dirs ]
dirs = list(map(str, dirs))
name = kw.get('name', 'SConscript')
files = [os.path.join(n, name) for n in dirs]
elif len(ls) == 1:
files = ls[0]
elif len(ls) == 2:
files = ls[0]
exports = self.Split(ls[1])
else:
raise SCons.Errors.UserError("Invalid SConscript() usage - too many arguments")
if not is_List(files):
files = [ files ]
if kw.get('exports'):
exports.extend(self.Split(kw['exports']))
variant_dir = kw.get('variant_dir')
if variant_dir:
if len(files) != 1:
raise SCons.Errors.UserError("Invalid SConscript() usage - can only specify one SConscript with a variant_dir")
duplicate = kw.get('duplicate', 1)
src_dir = kw.get('src_dir')
if not src_dir:
src_dir, fname = os.path.split(str(files[0]))
files = [os.path.join(str(variant_dir), fname)]
else:
if not isinstance(src_dir, SCons.Node.Node):
src_dir = self.fs.Dir(src_dir)
fn = files[0]
if not isinstance(fn, SCons.Node.Node):
fn = self.fs.File(fn)
if fn.is_under(src_dir):
# Get path relative to the source directory.
fname = fn.get_path(src_dir)
files = [os.path.join(str(variant_dir), fname)]
else:
files = [fn.get_abspath()]
kw['src_dir'] = variant_dir
self.fs.VariantDir(variant_dir, src_dir, duplicate)
return (files, exports) | [
"def",
"_get_SConscript_filenames",
"(",
"self",
",",
"ls",
",",
"kw",
")",
":",
"exports",
"=",
"[",
"]",
"if",
"len",
"(",
"ls",
")",
"==",
"0",
":",
"try",
":",
"dirs",
"=",
"kw",
"[",
"\"dirs\"",
"]",
"except",
"KeyError",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"Invalid SConscript usage - no parameters\"",
")",
"if",
"not",
"is_List",
"(",
"dirs",
")",
":",
"dirs",
"=",
"[",
"dirs",
"]",
"dirs",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"dirs",
")",
")",
"name",
"=",
"kw",
".",
"get",
"(",
"'name'",
",",
"'SConscript'",
")",
"files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"n",
",",
"name",
")",
"for",
"n",
"in",
"dirs",
"]",
"elif",
"len",
"(",
"ls",
")",
"==",
"1",
":",
"files",
"=",
"ls",
"[",
"0",
"]",
"elif",
"len",
"(",
"ls",
")",
"==",
"2",
":",
"files",
"=",
"ls",
"[",
"0",
"]",
"exports",
"=",
"self",
".",
"Split",
"(",
"ls",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"Invalid SConscript() usage - too many arguments\"",
")",
"if",
"not",
"is_List",
"(",
"files",
")",
":",
"files",
"=",
"[",
"files",
"]",
"if",
"kw",
".",
"get",
"(",
"'exports'",
")",
":",
"exports",
".",
"extend",
"(",
"self",
".",
"Split",
"(",
"kw",
"[",
"'exports'",
"]",
")",
")",
"variant_dir",
"=",
"kw",
".",
"get",
"(",
"'variant_dir'",
")",
"if",
"variant_dir",
":",
"if",
"len",
"(",
"files",
")",
"!=",
"1",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"Invalid SConscript() usage - can only specify one SConscript with a variant_dir\"",
")",
"duplicate",
"=",
"kw",
".",
"get",
"(",
"'duplicate'",
",",
"1",
")",
"src_dir",
"=",
"kw",
".",
"get",
"(",
"'src_dir'",
")",
"if",
"not",
"src_dir",
":",
"src_dir",
",",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"str",
"(",
"files",
"[",
"0",
"]",
")",
")",
"files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"str",
"(",
"variant_dir",
")",
",",
"fname",
")",
"]",
"else",
":",
"if",
"not",
"isinstance",
"(",
"src_dir",
",",
"SCons",
".",
"Node",
".",
"Node",
")",
":",
"src_dir",
"=",
"self",
".",
"fs",
".",
"Dir",
"(",
"src_dir",
")",
"fn",
"=",
"files",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"fn",
",",
"SCons",
".",
"Node",
".",
"Node",
")",
":",
"fn",
"=",
"self",
".",
"fs",
".",
"File",
"(",
"fn",
")",
"if",
"fn",
".",
"is_under",
"(",
"src_dir",
")",
":",
"# Get path relative to the source directory.",
"fname",
"=",
"fn",
".",
"get_path",
"(",
"src_dir",
")",
"files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"str",
"(",
"variant_dir",
")",
",",
"fname",
")",
"]",
"else",
":",
"files",
"=",
"[",
"fn",
".",
"get_abspath",
"(",
")",
"]",
"kw",
"[",
"'src_dir'",
"]",
"=",
"variant_dir",
"self",
".",
"fs",
".",
"VariantDir",
"(",
"variant_dir",
",",
"src_dir",
",",
"duplicate",
")",
"return",
"(",
"files",
",",
"exports",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Script/SConscript.py#L402-L468 | |
letscontrolit/ESPEasy | acb2c9e695d6f61d8d67adf0fe4037c08d4baedd | lib/IRremoteESP8266/tools/scrape_supported_devices.py | python | getdecodedprotocols | () | return ret | All protocols that include decoding support | All protocols that include decoding support | [
"All",
"protocols",
"that",
"include",
"decoding",
"support"
] | def getdecodedprotocols():
"""All protocols that include decoding support"""
ret = set()
for path in ARGS.directory.iterdir():
if path.suffix != ".cpp":
continue
matches = DECODED_PROTOCOLS.finditer(path.open(encoding="utf-8").read())
for match in matches:
protocol = match.group(1)
if protocol not in EXCLUDED_PROTOCOLS:
ret.add(protocol)
return ret | [
"def",
"getdecodedprotocols",
"(",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"ARGS",
".",
"directory",
".",
"iterdir",
"(",
")",
":",
"if",
"path",
".",
"suffix",
"!=",
"\".cpp\"",
":",
"continue",
"matches",
"=",
"DECODED_PROTOCOLS",
".",
"finditer",
"(",
"path",
".",
"open",
"(",
"encoding",
"=",
"\"utf-8\"",
")",
".",
"read",
"(",
")",
")",
"for",
"match",
"in",
"matches",
":",
"protocol",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"protocol",
"not",
"in",
"EXCLUDED_PROTOCOLS",
":",
"ret",
".",
"add",
"(",
"protocol",
")",
"return",
"ret"
] | https://github.com/letscontrolit/ESPEasy/blob/acb2c9e695d6f61d8d67adf0fe4037c08d4baedd/lib/IRremoteESP8266/tools/scrape_supported_devices.py#L80-L91 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/toolkits/image_analysis/image_analysis.py | python | _decode | (image_data) | Internal helper function for decoding a single Image or an SArray of Images | Internal helper function for decoding a single Image or an SArray of Images | [
"Internal",
"helper",
"function",
"for",
"decoding",
"a",
"single",
"Image",
"or",
"an",
"SArray",
"of",
"Images"
] | def _decode(image_data):
"""
Internal helper function for decoding a single Image or an SArray of Images
"""
from ...data_structures.sarray import SArray as _SArray
from ... import extensions as _extensions
if type(image_data) is _SArray:
return _extensions.decode_image_sarray(image_data)
elif type(image_data) is _Image:
return _extensions.decode_image(image_data) | [
"def",
"_decode",
"(",
"image_data",
")",
":",
"from",
".",
".",
".",
"data_structures",
".",
"sarray",
"import",
"SArray",
"as",
"_SArray",
"from",
".",
".",
".",
"import",
"extensions",
"as",
"_extensions",
"if",
"type",
"(",
"image_data",
")",
"is",
"_SArray",
":",
"return",
"_extensions",
".",
"decode_image_sarray",
"(",
"image_data",
")",
"elif",
"type",
"(",
"image_data",
")",
"is",
"_Image",
":",
"return",
"_extensions",
".",
"decode_image",
"(",
"image_data",
")"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/toolkits/image_analysis/image_analysis.py#L65-L74 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/meta/decompiler/control_flow_instructions.py | python | CtrlFlowInstructions.SET_ADD | (self, instr) | NOP | NOP | [
"NOP"
] | def SET_ADD(self, instr):
'NOP' | [
"def",
"SET_ADD",
"(",
"self",
",",
"instr",
")",
":"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/meta/decompiler/control_flow_instructions.py#L551-L552 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PyFontProperty._SetSelf | (*args, **kwargs) | return _propgrid.PyFontProperty__SetSelf(*args, **kwargs) | _SetSelf(self, PyObject self) | _SetSelf(self, PyObject self) | [
"_SetSelf",
"(",
"self",
"PyObject",
"self",
")"
] | def _SetSelf(*args, **kwargs):
"""_SetSelf(self, PyObject self)"""
return _propgrid.PyFontProperty__SetSelf(*args, **kwargs) | [
"def",
"_SetSelf",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PyFontProperty__SetSelf",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L4285-L4287 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/__init__.py | python | Component.supports | (self, format) | return format in self.supported | Is `format` supported by this component?
To be used by transforms to ask the dependent component if it supports
a certain input context or output format. | Is `format` supported by this component? | [
"Is",
"format",
"supported",
"by",
"this",
"component?"
] | def supports(self, format):
"""
Is `format` supported by this component?
To be used by transforms to ask the dependent component if it supports
a certain input context or output format.
"""
return format in self.supported | [
"def",
"supports",
"(",
"self",
",",
"format",
")",
":",
"return",
"format",
"in",
"self",
".",
"supported"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/__init__.py#L255-L262 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/msw/gizmos.py | python | TreeListCtrl.GetPrevVisible | (*args, **kwargs) | return _gizmos.TreeListCtrl_GetPrevVisible(*args, **kwargs) | GetPrevVisible(self, TreeItemId item, bool fullRow=False) -> TreeItemId | GetPrevVisible(self, TreeItemId item, bool fullRow=False) -> TreeItemId | [
"GetPrevVisible",
"(",
"self",
"TreeItemId",
"item",
"bool",
"fullRow",
"=",
"False",
")",
"-",
">",
"TreeItemId"
] | def GetPrevVisible(*args, **kwargs):
"""GetPrevVisible(self, TreeItemId item, bool fullRow=False) -> TreeItemId"""
return _gizmos.TreeListCtrl_GetPrevVisible(*args, **kwargs) | [
"def",
"GetPrevVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_GetPrevVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L822-L824 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/auth.py | python | HTTPDigestAuth.handle_redirect | (self, r, **kwargs) | Reset num_401_calls counter on redirects. | Reset num_401_calls counter on redirects. | [
"Reset",
"num_401_calls",
"counter",
"on",
"redirects",
"."
] | def handle_redirect(self, r, **kwargs):
"""Reset num_401_calls counter on redirects."""
if r.is_redirect:
self._thread_local.num_401_calls = 1 | [
"def",
"handle_redirect",
"(",
"self",
",",
"r",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
".",
"is_redirect",
":",
"self",
".",
"_thread_local",
".",
"num_401_calls",
"=",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/auth.py#L457-L463 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/cauchy.py | python | Cauchy.__init__ | (self,
loc=None,
scale=None,
seed=None,
dtype=mstype.float32,
name="Cauchy") | Constructor of Cauchy. | Constructor of Cauchy. | [
"Constructor",
"of",
"Cauchy",
"."
] | def __init__(self,
loc=None,
scale=None,
seed=None,
dtype=mstype.float32,
name="Cauchy"):
"""
Constructor of Cauchy.
"""
param = dict(locals())
param['param_dict'] = {'loc': loc, 'scale': scale}
valid_dtype = mstype.float_type
Validator.check_type_name(
"dtype", dtype, valid_dtype, type(self).__name__)
super(Cauchy, self).__init__(seed, dtype, name, param)
self._loc = self._add_parameter(loc, 'loc')
self._scale = self._add_parameter(scale, 'scale')
if self._scale is not None:
check_greater_zero(self._scale, "scale")
# ops needed for the class
self.atan = P.Atan()
self.cast = P.Cast()
self.const = P.ScalarToArray()
self.dtypeop = P.DType()
self.exp = exp_generic
self.fill = P.Fill()
self.less = P.Less()
self.log = log_generic
self.log1p = log1p_generic
self.squeeze = P.Squeeze(0)
self.shape = P.Shape()
self.sq = P.Square()
self.sqrt = P.Sqrt()
self.tan = P.Tan()
self.uniform = C.uniform
self.entropy_const = np.log(4 * np.pi) | [
"def",
"__init__",
"(",
"self",
",",
"loc",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"dtype",
"=",
"mstype",
".",
"float32",
",",
"name",
"=",
"\"Cauchy\"",
")",
":",
"param",
"=",
"dict",
"(",
"locals",
"(",
")",
")",
"param",
"[",
"'param_dict'",
"]",
"=",
"{",
"'loc'",
":",
"loc",
",",
"'scale'",
":",
"scale",
"}",
"valid_dtype",
"=",
"mstype",
".",
"float_type",
"Validator",
".",
"check_type_name",
"(",
"\"dtype\"",
",",
"dtype",
",",
"valid_dtype",
",",
"type",
"(",
"self",
")",
".",
"__name__",
")",
"super",
"(",
"Cauchy",
",",
"self",
")",
".",
"__init__",
"(",
"seed",
",",
"dtype",
",",
"name",
",",
"param",
")",
"self",
".",
"_loc",
"=",
"self",
".",
"_add_parameter",
"(",
"loc",
",",
"'loc'",
")",
"self",
".",
"_scale",
"=",
"self",
".",
"_add_parameter",
"(",
"scale",
",",
"'scale'",
")",
"if",
"self",
".",
"_scale",
"is",
"not",
"None",
":",
"check_greater_zero",
"(",
"self",
".",
"_scale",
",",
"\"scale\"",
")",
"# ops needed for the class",
"self",
".",
"atan",
"=",
"P",
".",
"Atan",
"(",
")",
"self",
".",
"cast",
"=",
"P",
".",
"Cast",
"(",
")",
"self",
".",
"const",
"=",
"P",
".",
"ScalarToArray",
"(",
")",
"self",
".",
"dtypeop",
"=",
"P",
".",
"DType",
"(",
")",
"self",
".",
"exp",
"=",
"exp_generic",
"self",
".",
"fill",
"=",
"P",
".",
"Fill",
"(",
")",
"self",
".",
"less",
"=",
"P",
".",
"Less",
"(",
")",
"self",
".",
"log",
"=",
"log_generic",
"self",
".",
"log1p",
"=",
"log1p_generic",
"self",
".",
"squeeze",
"=",
"P",
".",
"Squeeze",
"(",
"0",
")",
"self",
".",
"shape",
"=",
"P",
".",
"Shape",
"(",
")",
"self",
".",
"sq",
"=",
"P",
".",
"Square",
"(",
")",
"self",
".",
"sqrt",
"=",
"P",
".",
"Sqrt",
"(",
")",
"self",
".",
"tan",
"=",
"P",
".",
"Tan",
"(",
")",
"self",
".",
"uniform",
"=",
"C",
".",
"uniform",
"self",
".",
"entropy_const",
"=",
"np",
".",
"log",
"(",
"4",
"*",
"np",
".",
"pi",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/cauchy.py#L158-L196 | ||
WeitaoVan/L-GM-loss | 598582f0631bac876b3eeb8d6c4cd1d780269e03 | python/caffe/io.py | python | Transformer.set_mean | (self, in_, mean) | Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable) | Set the mean to subtract for centering the data. | [
"Set",
"the",
"mean",
"to",
"subtract",
"for",
"centering",
"the",
"data",
"."
] | def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
raise ValueError('Mean shape incompatible with input shape.')
self.mean[in_] = mean | [
"def",
"set_mean",
"(",
"self",
",",
"in_",
",",
"mean",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"ms",
"=",
"mean",
".",
"shape",
"if",
"mean",
".",
"ndim",
"==",
"1",
":",
"# broadcast channels",
"if",
"ms",
"[",
"0",
"]",
"!=",
"self",
".",
"inputs",
"[",
"in_",
"]",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'Mean channels incompatible with input.'",
")",
"mean",
"=",
"mean",
"[",
":",
",",
"np",
".",
"newaxis",
",",
"np",
".",
"newaxis",
"]",
"else",
":",
"# elementwise mean",
"if",
"len",
"(",
"ms",
")",
"==",
"2",
":",
"ms",
"=",
"(",
"1",
",",
")",
"+",
"ms",
"if",
"len",
"(",
"ms",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Mean shape invalid'",
")",
"if",
"ms",
"!=",
"self",
".",
"inputs",
"[",
"in_",
"]",
"[",
"1",
":",
"]",
":",
"raise",
"ValueError",
"(",
"'Mean shape incompatible with input shape.'",
")",
"self",
".",
"mean",
"[",
"in_",
"]",
"=",
"mean"
] | https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/python/caffe/io.py#L236-L260 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_basewin.py | python | FindMainWindow | (window) | return None | Find the MainWindow of the given window
@return: MainWindow or None | Find the MainWindow of the given window
@return: MainWindow or None | [
"Find",
"the",
"MainWindow",
"of",
"the",
"given",
"window",
"@return",
":",
"MainWindow",
"or",
"None"
] | def FindMainWindow(window):
"""Find the MainWindow of the given window
@return: MainWindow or None
"""
def IsMainWin(win):
"""Check if the given window is a main window"""
return getattr(win, '__name__', '') == 'MainWindow'
if IsMainWin(window):
return window
# else start looking up the parent hierarchy
tlw = window.GetTopLevelParent()
if IsMainWin(tlw):
return tlw
elif hasattr(tlw, 'GetParent'):
tlw = tlw.GetParent()
if IsMainWin(tlw):
return tlw
return None | [
"def",
"FindMainWindow",
"(",
"window",
")",
":",
"def",
"IsMainWin",
"(",
"win",
")",
":",
"\"\"\"Check if the given window is a main window\"\"\"",
"return",
"getattr",
"(",
"win",
",",
"'__name__'",
",",
"''",
")",
"==",
"'MainWindow'",
"if",
"IsMainWin",
"(",
"window",
")",
":",
"return",
"window",
"# else start looking up the parent hierarchy",
"tlw",
"=",
"window",
".",
"GetTopLevelParent",
"(",
")",
"if",
"IsMainWin",
"(",
"tlw",
")",
":",
"return",
"tlw",
"elif",
"hasattr",
"(",
"tlw",
",",
"'GetParent'",
")",
":",
"tlw",
"=",
"tlw",
".",
"GetParent",
"(",
")",
"if",
"IsMainWin",
"(",
"tlw",
")",
":",
"return",
"tlw",
"return",
"None"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_basewin.py#L30-L50 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/tpu/tpu_embedding.py | python | TPUEmbedding.hosts | (self) | return copy.copy(self._hosts) | A list of device names for CPU hosts.
Returns:
A list of device names for CPU hosts. | A list of device names for CPU hosts. | [
"A",
"list",
"of",
"device",
"names",
"for",
"CPU",
"hosts",
"."
] | def hosts(self):
"""A list of device names for CPU hosts.
Returns:
A list of device names for CPU hosts.
"""
return copy.copy(self._hosts) | [
"def",
"hosts",
"(",
"self",
")",
":",
"return",
"copy",
".",
"copy",
"(",
"self",
".",
"_hosts",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/tpu_embedding.py#L1469-L1475 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py | python | _IPAddressBase._prefix_from_prefix_string | (cls, prefixlen_str) | return prefixlen | Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask | Return prefix length from a numeric string | [
"Return",
"prefix",
"length",
"from",
"a",
"numeric",
"string"
] | def _prefix_from_prefix_string(cls, prefixlen_str):
"""Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask
"""
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
cls._report_invalid_netmask(prefixlen_str)
try:
prefixlen = int(prefixlen_str)
except ValueError:
cls._report_invalid_netmask(prefixlen_str)
if not (0 <= prefixlen <= cls._max_prefixlen):
cls._report_invalid_netmask(prefixlen_str)
return prefixlen | [
"def",
"_prefix_from_prefix_string",
"(",
"cls",
",",
"prefixlen_str",
")",
":",
"# int allows a leading +/- as well as surrounding whitespace,",
"# so we ensure that isn't the case",
"if",
"not",
"_BaseV4",
".",
"_DECIMAL_DIGITS",
".",
"issuperset",
"(",
"prefixlen_str",
")",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"prefixlen_str",
")",
"try",
":",
"prefixlen",
"=",
"int",
"(",
"prefixlen_str",
")",
"except",
"ValueError",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"prefixlen_str",
")",
"if",
"not",
"(",
"0",
"<=",
"prefixlen",
"<=",
"cls",
".",
"_max_prefixlen",
")",
":",
"cls",
".",
"_report_invalid_netmask",
"(",
"prefixlen_str",
")",
"return",
"prefixlen"
] | 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/ipaddress.py#L600-L622 | |
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | SortRef.__ne__ | (self, other) | return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) | Return `True` if `self` and `other` are not the same Z3 sort.
>>> p = Bool('p')
>>> p.sort() != BoolSort()
False
>>> p.sort() != IntSort()
True | Return `True` if `self` and `other` are not the same Z3 sort. | [
"Return",
"True",
"if",
"self",
"and",
"other",
"are",
"not",
"the",
"same",
"Z3",
"sort",
"."
] | def __ne__(self, other):
"""Return `True` if `self` and `other` are not the same Z3 sort.
>>> p = Bool('p')
>>> p.sort() != BoolSort()
False
>>> p.sort() != IntSort()
True
"""
return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"return",
"not",
"Z3_is_eq_sort",
"(",
"self",
".",
"ctx_ref",
"(",
")",
",",
"self",
".",
"ast",
",",
"other",
".",
"ast",
")"
] | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L630-L639 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.GetScrollPos | (*args, **kwargs) | return _core_.Window_GetScrollPos(*args, **kwargs) | GetScrollPos(self, int orientation) -> int
Returns the built-in scrollbar position. | GetScrollPos(self, int orientation) -> int | [
"GetScrollPos",
"(",
"self",
"int",
"orientation",
")",
"-",
">",
"int"
] | def GetScrollPos(*args, **kwargs):
"""
GetScrollPos(self, int orientation) -> int
Returns the built-in scrollbar position.
"""
return _core_.Window_GetScrollPos(*args, **kwargs) | [
"def",
"GetScrollPos",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_GetScrollPos",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L11236-L11242 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column_v2.py | python | _create_weighted_sum | (column, transformation_cache, state_manager,
sparse_combiner, weight_var) | Creates a weighted sum for a dense/categorical column for linear_model. | Creates a weighted sum for a dense/categorical column for linear_model. | [
"Creates",
"a",
"weighted",
"sum",
"for",
"a",
"dense",
"/",
"categorical",
"column",
"for",
"linear_model",
"."
] | def _create_weighted_sum(column, transformation_cache, state_manager,
sparse_combiner, weight_var):
"""Creates a weighted sum for a dense/categorical column for linear_model."""
if isinstance(column, CategoricalColumn):
return _create_categorical_column_weighted_sum(
column=column,
transformation_cache=transformation_cache,
state_manager=state_manager,
sparse_combiner=sparse_combiner,
weight_var=weight_var)
else:
return _create_dense_column_weighted_sum(
column=column,
transformation_cache=transformation_cache,
state_manager=state_manager,
weight_var=weight_var) | [
"def",
"_create_weighted_sum",
"(",
"column",
",",
"transformation_cache",
",",
"state_manager",
",",
"sparse_combiner",
",",
"weight_var",
")",
":",
"if",
"isinstance",
"(",
"column",
",",
"CategoricalColumn",
")",
":",
"return",
"_create_categorical_column_weighted_sum",
"(",
"column",
"=",
"column",
",",
"transformation_cache",
"=",
"transformation_cache",
",",
"state_manager",
"=",
"state_manager",
",",
"sparse_combiner",
"=",
"sparse_combiner",
",",
"weight_var",
"=",
"weight_var",
")",
"else",
":",
"return",
"_create_dense_column_weighted_sum",
"(",
"column",
"=",
"column",
",",
"transformation_cache",
"=",
"transformation_cache",
",",
"state_manager",
"=",
"state_manager",
",",
"weight_var",
"=",
"weight_var",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L2227-L2242 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pep517/_in_process.py | python | _find_already_built_wheel | (metadata_directory) | return whl_files[0] | Check for a wheel already built during the get_wheel_metadata hook. | Check for a wheel already built during the get_wheel_metadata hook. | [
"Check",
"for",
"a",
"wheel",
"already",
"built",
"during",
"the",
"get_wheel_metadata",
"hook",
"."
] | def _find_already_built_wheel(metadata_directory):
"""Check for a wheel already built during the get_wheel_metadata hook.
"""
if not metadata_directory:
return None
metadata_parent = os.path.dirname(metadata_directory)
if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
return None
whl_files = glob(os.path.join(metadata_parent, '*.whl'))
if not whl_files:
print('Found wheel built marker, but no .whl files')
return None
if len(whl_files) > 1:
print('Found multiple .whl files; unspecified behaviour. '
'Will call build_wheel.')
return None
# Exactly one .whl file
return whl_files[0] | [
"def",
"_find_already_built_wheel",
"(",
"metadata_directory",
")",
":",
"if",
"not",
"metadata_directory",
":",
"return",
"None",
"metadata_parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"metadata_directory",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pjoin",
"(",
"metadata_parent",
",",
"WHEEL_BUILT_MARKER",
")",
")",
":",
"return",
"None",
"whl_files",
"=",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"metadata_parent",
",",
"'*.whl'",
")",
")",
"if",
"not",
"whl_files",
":",
"print",
"(",
"'Found wheel built marker, but no .whl files'",
")",
"return",
"None",
"if",
"len",
"(",
"whl_files",
")",
">",
"1",
":",
"print",
"(",
"'Found multiple .whl files; unspecified behaviour. '",
"'Will call build_wheel.'",
")",
"return",
"None",
"# Exactly one .whl file",
"return",
"whl_files",
"[",
"0",
"]"
] | 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/pep517/_in_process.py#L106-L125 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlCellEvent.GetLinkClicked | (*args, **kwargs) | return _html.HtmlCellEvent_GetLinkClicked(*args, **kwargs) | GetLinkClicked(self) -> bool | GetLinkClicked(self) -> bool | [
"GetLinkClicked",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetLinkClicked(*args, **kwargs):
"""GetLinkClicked(self) -> bool"""
return _html.HtmlCellEvent_GetLinkClicked(*args, **kwargs) | [
"def",
"GetLinkClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlCellEvent_GetLinkClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1706-L1708 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/head.py | python | _identity_metric_single | (name, input_tensor) | return (metric_variable.value(), update_op) | A metric which takes on its last updated value.
This keeps evaluation metrics in sync with one another, since update ops are
run separately from their result Tensors. Simply returning (input_tensor,
no_op) as a metric with a value but no update means that a metric will come
from a different batch of data than metrics which cache values in a Variable
(e.g. the default loss metric).
Args:
name: A name for the metric.
input_tensor: Any Tensor.
Returns:
A tuple of (value, update_op). | A metric which takes on its last updated value. | [
"A",
"metric",
"which",
"takes",
"on",
"its",
"last",
"updated",
"value",
"."
] | def _identity_metric_single(name, input_tensor):
"""A metric which takes on its last updated value.
This keeps evaluation metrics in sync with one another, since update ops are
run separately from their result Tensors. Simply returning (input_tensor,
no_op) as a metric with a value but no update means that a metric will come
from a different batch of data than metrics which cache values in a Variable
(e.g. the default loss metric).
Args:
name: A name for the metric.
input_tensor: Any Tensor.
Returns:
A tuple of (value, update_op).
"""
metric_variable = variable_scope.variable(
name="{}_identity_metric".format(name),
initial_value=array_ops.zeros([], dtype=input_tensor.dtype),
collections=[ops.GraphKeys.LOCAL_VARIABLES],
validate_shape=False)
update_op = state_ops.assign(
metric_variable, input_tensor, validate_shape=False)
# This shape will be correct once the first update runs (but may be
# incomplete, so is not helpful for initializing the variable).
metric_variable.set_shape(input_tensor.get_shape())
return (metric_variable.value(), update_op) | [
"def",
"_identity_metric_single",
"(",
"name",
",",
"input_tensor",
")",
":",
"metric_variable",
"=",
"variable_scope",
".",
"variable",
"(",
"name",
"=",
"\"{}_identity_metric\"",
".",
"format",
"(",
"name",
")",
",",
"initial_value",
"=",
"array_ops",
".",
"zeros",
"(",
"[",
"]",
",",
"dtype",
"=",
"input_tensor",
".",
"dtype",
")",
",",
"collections",
"=",
"[",
"ops",
".",
"GraphKeys",
".",
"LOCAL_VARIABLES",
"]",
",",
"validate_shape",
"=",
"False",
")",
"update_op",
"=",
"state_ops",
".",
"assign",
"(",
"metric_variable",
",",
"input_tensor",
",",
"validate_shape",
"=",
"False",
")",
"# This shape will be correct once the first update runs (but may be",
"# incomplete, so is not helpful for initializing the variable).",
"metric_variable",
".",
"set_shape",
"(",
"input_tensor",
".",
"get_shape",
"(",
")",
")",
"return",
"(",
"metric_variable",
".",
"value",
"(",
")",
",",
"update_op",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/head.py#L434-L459 | |
eric612/Caffe-YOLOv3-Windows | 6736ca6e16781789b828cc64218ff77cc3454e5d | python/caffe/net_spec.py | python | param_name_dict | () | return dict(zip(param_type_names, param_names)) | Find out the correspondence between layer names and parameter names. | Find out the correspondence between layer names and parameter names. | [
"Find",
"out",
"the",
"correspondence",
"between",
"layer",
"names",
"and",
"parameter",
"names",
"."
] | def param_name_dict():
"""Find out the correspondence between layer names and parameter names."""
layer = caffe_pb2.LayerParameter()
# get all parameter names (typically underscore case) and corresponding
# type names (typically camel case), which contain the layer names
# (note that not all parameters correspond to layers, but we'll ignore that)
param_names = [f.name for f in layer.DESCRIPTOR.fields if f.name.endswith('_param')]
param_type_names = [type(getattr(layer, s)).__name__ for s in param_names]
# strip the final '_param' or 'Parameter'
param_names = [s[:-len('_param')] for s in param_names]
param_type_names = [s[:-len('Parameter')] for s in param_type_names]
return dict(zip(param_type_names, param_names)) | [
"def",
"param_name_dict",
"(",
")",
":",
"layer",
"=",
"caffe_pb2",
".",
"LayerParameter",
"(",
")",
"# get all parameter names (typically underscore case) and corresponding",
"# type names (typically camel case), which contain the layer names",
"# (note that not all parameters correspond to layers, but we'll ignore that)",
"param_names",
"=",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"layer",
".",
"DESCRIPTOR",
".",
"fields",
"if",
"f",
".",
"name",
".",
"endswith",
"(",
"'_param'",
")",
"]",
"param_type_names",
"=",
"[",
"type",
"(",
"getattr",
"(",
"layer",
",",
"s",
")",
")",
".",
"__name__",
"for",
"s",
"in",
"param_names",
"]",
"# strip the final '_param' or 'Parameter'",
"param_names",
"=",
"[",
"s",
"[",
":",
"-",
"len",
"(",
"'_param'",
")",
"]",
"for",
"s",
"in",
"param_names",
"]",
"param_type_names",
"=",
"[",
"s",
"[",
":",
"-",
"len",
"(",
"'Parameter'",
")",
"]",
"for",
"s",
"in",
"param_type_names",
"]",
"return",
"dict",
"(",
"zip",
"(",
"param_type_names",
",",
"param_names",
")",
")"
] | https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/python/caffe/net_spec.py#L28-L40 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/internal/enum_type_wrapper.py | python | EnumTypeWrapper.items | (self) | return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | Return a list of the (name, value) pairs of the enum.
Returns:
A list of (str, int) pairs, in the order they were defined
in the .proto file. | Return a list of the (name, value) pairs of the enum. | [
"Return",
"a",
"list",
"of",
"the",
"(",
"name",
"value",
")",
"pairs",
"of",
"the",
"enum",
"."
] | def items(self):
"""Return a list of the (name, value) pairs of the enum.
Returns:
A list of (str, int) pairs, in the order they were defined
in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"value_descriptor",
".",
"name",
",",
"value_descriptor",
".",
"number",
")",
"for",
"value_descriptor",
"in",
"self",
".",
"_enum_type",
".",
"values",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/enum_type_wrapper.py#L98-L106 | |
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/serial/serialutil.py | python | SerialBase.port | (self) | return self._port | \
Get the current port setting. The value that was passed on init or using
setPort() is passed back. | \
Get the current port setting. The value that was passed on init or using
setPort() is passed back. | [
"\\",
"Get",
"the",
"current",
"port",
"setting",
".",
"The",
"value",
"that",
"was",
"passed",
"on",
"init",
"or",
"using",
"setPort",
"()",
"is",
"passed",
"back",
"."
] | def port(self):
"""\
Get the current port setting. The value that was passed on init or using
setPort() is passed back.
"""
return self._port | [
"def",
"port",
"(",
"self",
")",
":",
"return",
"self",
".",
"_port"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialutil.py#L251-L256 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/context.py | python | NRTContext.meminfo_alloc_aligned | (self, builder, size, align) | return builder.call(fn, [size, align]) | Allocate a new MemInfo with an aligned data payload of `size` bytes.
The data pointer is aligned to `align` bytes. `align` can be either
a Python int or a LLVM uint32 value.
A pointer to the MemInfo is returned. | Allocate a new MemInfo with an aligned data payload of `size` bytes.
The data pointer is aligned to `align` bytes. `align` can be either
a Python int or a LLVM uint32 value. | [
"Allocate",
"a",
"new",
"MemInfo",
"with",
"an",
"aligned",
"data",
"payload",
"of",
"size",
"bytes",
".",
"The",
"data",
"pointer",
"is",
"aligned",
"to",
"align",
"bytes",
".",
"align",
"can",
"be",
"either",
"a",
"Python",
"int",
"or",
"a",
"LLVM",
"uint32",
"value",
"."
] | def meminfo_alloc_aligned(self, builder, size, align):
"""
Allocate a new MemInfo with an aligned data payload of `size` bytes.
The data pointer is aligned to `align` bytes. `align` can be either
a Python int or a LLVM uint32 value.
A pointer to the MemInfo is returned.
"""
self._require_nrt()
mod = builder.module
u32 = ir.IntType(32)
fnty = ir.FunctionType(cgutils.voidptr_t, [cgutils.intp_t, u32])
fn = mod.get_or_insert_function(fnty,
name="NRT_MemInfo_alloc_safe_aligned")
fn.return_value.add_attribute("noalias")
if isinstance(align, int):
align = self._context.get_constant(types.uint32, align)
else:
assert align.type == u32, "align must be a uint32"
return builder.call(fn, [size, align]) | [
"def",
"meminfo_alloc_aligned",
"(",
"self",
",",
"builder",
",",
"size",
",",
"align",
")",
":",
"self",
".",
"_require_nrt",
"(",
")",
"mod",
"=",
"builder",
".",
"module",
"u32",
"=",
"ir",
".",
"IntType",
"(",
"32",
")",
"fnty",
"=",
"ir",
".",
"FunctionType",
"(",
"cgutils",
".",
"voidptr_t",
",",
"[",
"cgutils",
".",
"intp_t",
",",
"u32",
"]",
")",
"fn",
"=",
"mod",
".",
"get_or_insert_function",
"(",
"fnty",
",",
"name",
"=",
"\"NRT_MemInfo_alloc_safe_aligned\"",
")",
"fn",
".",
"return_value",
".",
"add_attribute",
"(",
"\"noalias\"",
")",
"if",
"isinstance",
"(",
"align",
",",
"int",
")",
":",
"align",
"=",
"self",
".",
"_context",
".",
"get_constant",
"(",
"types",
".",
"uint32",
",",
"align",
")",
"else",
":",
"assert",
"align",
".",
"type",
"==",
"u32",
",",
"\"align must be a uint32\"",
"return",
"builder",
".",
"call",
"(",
"fn",
",",
"[",
"size",
",",
"align",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/context.py#L70-L90 | |
openclonk/openclonk | 701bcf38c9f3c4877e1b4a8651b9ce922b15969e | docs/tools/xml2po.py | python | normalizeString | (text, ignorewhitespace = 1) | return result | Normalizes string to be used as key for gettext lookup.
Removes all unnecessary whitespace. | Normalizes string to be used as key for gettext lookup. | [
"Normalizes",
"string",
"to",
"be",
"used",
"as",
"key",
"for",
"gettext",
"lookup",
"."
] | def normalizeString(text, ignorewhitespace = 1):
"""Normalizes string to be used as key for gettext lookup.
Removes all unnecessary whitespace."""
if not ignorewhitespace:
return text
try:
# Lets add document DTD so entities are resolved
dtd = doc.intSubset()
tmp = dtd.serialize('utf-8')
tmp = tmp + '<norm>%s</norm>' % text
except:
tmp = '<norm>%s</norm>' % text
try:
ctxt = libxml2.createDocParserCtxt(tmp)
if expand_entities:
ctxt.replaceEntities(1)
ctxt.parseDocument()
tree = ctxt.doc()
newnode = tree.getRootElement()
except:
print >> sys.stderr, """Error while normalizing string as XML:\n"%s"\n""" % (text)
return text
normalizeNode(newnode)
result = ''
child = newnode.children
while child:
result += child.serialize('utf-8')
child = child.next
result = re.sub('^ ','', result)
result = re.sub(' $','', result)
return result | [
"def",
"normalizeString",
"(",
"text",
",",
"ignorewhitespace",
"=",
"1",
")",
":",
"if",
"not",
"ignorewhitespace",
":",
"return",
"text",
"try",
":",
"# Lets add document DTD so entities are resolved",
"dtd",
"=",
"doc",
".",
"intSubset",
"(",
")",
"tmp",
"=",
"dtd",
".",
"serialize",
"(",
"'utf-8'",
")",
"tmp",
"=",
"tmp",
"+",
"'<norm>%s</norm>'",
"%",
"text",
"except",
":",
"tmp",
"=",
"'<norm>%s</norm>'",
"%",
"text",
"try",
":",
"ctxt",
"=",
"libxml2",
".",
"createDocParserCtxt",
"(",
"tmp",
")",
"if",
"expand_entities",
":",
"ctxt",
".",
"replaceEntities",
"(",
"1",
")",
"ctxt",
".",
"parseDocument",
"(",
")",
"tree",
"=",
"ctxt",
".",
"doc",
"(",
")",
"newnode",
"=",
"tree",
".",
"getRootElement",
"(",
")",
"except",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"\"\"Error while normalizing string as XML:\\n\"%s\"\\n\"\"\"",
"%",
"(",
"text",
")",
"return",
"text",
"normalizeNode",
"(",
"newnode",
")",
"result",
"=",
"''",
"child",
"=",
"newnode",
".",
"children",
"while",
"child",
":",
"result",
"+=",
"child",
".",
"serialize",
"(",
"'utf-8'",
")",
"child",
"=",
"child",
".",
"next",
"result",
"=",
"re",
".",
"sub",
"(",
"'^ '",
",",
"''",
",",
"result",
")",
"result",
"=",
"re",
".",
"sub",
"(",
"' $'",
",",
"''",
",",
"result",
")",
"return",
"result"
] | https://github.com/openclonk/openclonk/blob/701bcf38c9f3c4877e1b4a8651b9ce922b15969e/docs/tools/xml2po.py#L135-L171 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/image_ops.py | python | transpose_image | (image) | return array_ops.transpose(image, [1, 0, 2], name='transpose_image') | Transpose an image by swapping the first and second dimension.
See also `transpose()`.
Args:
image: 3-D tensor of shape `[height, width, channels]`
Returns:
A 3-D tensor of shape `[width, height, channels]`
Raises:
ValueError: if the shape of `image` not supported. | Transpose an image by swapping the first and second dimension. | [
"Transpose",
"an",
"image",
"by",
"swapping",
"the",
"first",
"and",
"second",
"dimension",
"."
] | def transpose_image(image):
"""Transpose an image by swapping the first and second dimension.
See also `transpose()`.
Args:
image: 3-D tensor of shape `[height, width, channels]`
Returns:
A 3-D tensor of shape `[width, height, channels]`
Raises:
ValueError: if the shape of `image` not supported.
"""
image = ops.convert_to_tensor(image, name='image')
_Check3DImage(image, require_static=False)
return array_ops.transpose(image, [1, 0, 2], name='transpose_image') | [
"def",
"transpose_image",
"(",
"image",
")",
":",
"image",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"image",
",",
"name",
"=",
"'image'",
")",
"_Check3DImage",
"(",
"image",
",",
"require_static",
"=",
"False",
")",
"return",
"array_ops",
".",
"transpose",
"(",
"image",
",",
"[",
"1",
",",
"0",
",",
"2",
"]",
",",
"name",
"=",
"'transpose_image'",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/image_ops.py#L416-L432 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/poolmanager.py | python | PoolManager.clear | (self) | Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion. | Empty our store of pools and direct them all to close. | [
"Empty",
"our",
"store",
"of",
"pools",
"and",
"direct",
"them",
"all",
"to",
"close",
"."
] | def clear(self):
"""
Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.
"""
self.pools.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"pools",
".",
"clear",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/poolmanager.py#L84-L91 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py | python | KScriptGenerator.updateFunctionCallMap | (self, caller, callee) | Maintains a map of functions that are called from other functions | Maintains a map of functions that are called from other functions | [
"Maintains",
"a",
"map",
"of",
"functions",
"that",
"are",
"called",
"from",
"other",
"functions"
] | def updateFunctionCallMap(self, caller, callee):
"""Maintains a map of functions that are called from other functions"""
if not caller in self.calledFunctionTable:
self.calledFunctionTable[caller] = []
if not callee in self.calledFunctionTable[caller]:
self.calledFunctionTable[caller].append(callee)
if not caller in self.comprehensiveCalledFunctionTable:
self.comprehensiveCalledFunctionTable[caller] = []
self.comprehensiveCalledFunctionTable[caller].append(callee) | [
"def",
"updateFunctionCallMap",
"(",
"self",
",",
"caller",
",",
"callee",
")",
":",
"if",
"not",
"caller",
"in",
"self",
".",
"calledFunctionTable",
":",
"self",
".",
"calledFunctionTable",
"[",
"caller",
"]",
"=",
"[",
"]",
"if",
"not",
"callee",
"in",
"self",
".",
"calledFunctionTable",
"[",
"caller",
"]",
":",
"self",
".",
"calledFunctionTable",
"[",
"caller",
"]",
".",
"append",
"(",
"callee",
")",
"if",
"not",
"caller",
"in",
"self",
".",
"comprehensiveCalledFunctionTable",
":",
"self",
".",
"comprehensiveCalledFunctionTable",
"[",
"caller",
"]",
"=",
"[",
"]",
"self",
".",
"comprehensiveCalledFunctionTable",
"[",
"caller",
"]",
".",
"append",
"(",
"callee",
")"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L58-L66 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mailbox.py | python | Maildir.get_message | (self, key) | return msg | Return a Message representation or raise a KeyError. | Return a Message representation or raise a KeyError. | [
"Return",
"a",
"Message",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_message(self, key):
"""Return a Message representation or raise a KeyError."""
subpath = self._lookup(key)
f = open(os.path.join(self._path, subpath), 'r')
try:
if self._factory:
msg = self._factory(f)
else:
msg = MaildirMessage(f)
finally:
f.close()
subdir, name = os.path.split(subpath)
msg.set_subdir(subdir)
if self.colon in name:
msg.set_info(name.split(self.colon)[-1])
msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
return msg | [
"def",
"get_message",
"(",
"self",
",",
"key",
")",
":",
"subpath",
"=",
"self",
".",
"_lookup",
"(",
"key",
")",
"f",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"subpath",
")",
",",
"'r'",
")",
"try",
":",
"if",
"self",
".",
"_factory",
":",
"msg",
"=",
"self",
".",
"_factory",
"(",
"f",
")",
"else",
":",
"msg",
"=",
"MaildirMessage",
"(",
"f",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"subdir",
",",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"subpath",
")",
"msg",
".",
"set_subdir",
"(",
"subdir",
")",
"if",
"self",
".",
"colon",
"in",
"name",
":",
"msg",
".",
"set_info",
"(",
"name",
".",
"split",
"(",
"self",
".",
"colon",
")",
"[",
"-",
"1",
"]",
")",
"msg",
".",
"set_date",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"subpath",
")",
")",
")",
"return",
"msg"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L350-L366 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/data/ops/dataset_ops.py | python | ShardDataset.__init__ | (self, input_dataset, num_shards, index, name=None) | See `Dataset.shard()` for details. | See `Dataset.shard()` for details. | [
"See",
"Dataset",
".",
"shard",
"()",
"for",
"details",
"."
] | def __init__(self, input_dataset, num_shards, index, name=None):
"""See `Dataset.shard()` for details."""
self._input_dataset = input_dataset
self._num_shards = ops.convert_to_tensor(
num_shards, dtype=dtypes.int64, name="num_shards")
self._index = ops.convert_to_tensor(index, dtype=dtypes.int64, name="index")
self._name = name
variant_tensor = gen_dataset_ops.shard_dataset(
input_dataset._variant_tensor, # pylint: disable=protected-access
num_shards=self._num_shards,
index=self._index,
**self._common_args)
super(ShardDataset, self).__init__(input_dataset, variant_tensor) | [
"def",
"__init__",
"(",
"self",
",",
"input_dataset",
",",
"num_shards",
",",
"index",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_input_dataset",
"=",
"input_dataset",
"self",
".",
"_num_shards",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"num_shards",
",",
"dtype",
"=",
"dtypes",
".",
"int64",
",",
"name",
"=",
"\"num_shards\"",
")",
"self",
".",
"_index",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"index",
",",
"dtype",
"=",
"dtypes",
".",
"int64",
",",
"name",
"=",
"\"index\"",
")",
"self",
".",
"_name",
"=",
"name",
"variant_tensor",
"=",
"gen_dataset_ops",
".",
"shard_dataset",
"(",
"input_dataset",
".",
"_variant_tensor",
",",
"# pylint: disable=protected-access",
"num_shards",
"=",
"self",
".",
"_num_shards",
",",
"index",
"=",
"self",
".",
"_index",
",",
"*",
"*",
"self",
".",
"_common_args",
")",
"super",
"(",
"ShardDataset",
",",
"self",
")",
".",
"__init__",
"(",
"input_dataset",
",",
"variant_tensor",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/ops/dataset_ops.py#L4865-L4877 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/distributed_c10d.py | python | reduce | (tensor, dst, op=ReduceOp.SUM, group=None, async_op=False) | Reduces the tensor data across all machines.
Only the process with rank ``dst`` is going to receive the final result.
Args:
tensor (Tensor): Input and output of the collective. The function
operates in-place.
dst (int): Destination rank
op (optional): One of the values from
``torch.distributed.ReduceOp``
enum. Specifies an operation used for element-wise reductions.
group (ProcessGroup, optional): The process group to work on. If None,
the default process group will be used.
async_op (bool, optional): Whether this op should be an async op
Returns:
Async work handle, if async_op is set to True.
None, if not async_op or if not part of the group | Reduces the tensor data across all machines. | [
"Reduces",
"the",
"tensor",
"data",
"across",
"all",
"machines",
"."
] | def reduce(tensor, dst, op=ReduceOp.SUM, group=None, async_op=False):
"""
Reduces the tensor data across all machines.
Only the process with rank ``dst`` is going to receive the final result.
Args:
tensor (Tensor): Input and output of the collective. The function
operates in-place.
dst (int): Destination rank
op (optional): One of the values from
``torch.distributed.ReduceOp``
enum. Specifies an operation used for element-wise reductions.
group (ProcessGroup, optional): The process group to work on. If None,
the default process group will be used.
async_op (bool, optional): Whether this op should be an async op
Returns:
Async work handle, if async_op is set to True.
None, if not async_op or if not part of the group
"""
_check_single_tensor(tensor, "tensor")
if _rank_not_in_group(group):
_warn_not_in_group("reduce")
return
opts = ReduceOptions()
opts.reduceOp = op
opts.rootRank = dst
if group is None or group is GroupMember.WORLD:
default_pg = _get_default_group()
work = default_pg.reduce([tensor], opts)
else:
group_dst_rank = _get_group_rank(group, dst)
opts.rootRank = group_dst_rank
work = group.reduce([tensor], opts)
if async_op:
return work
else:
work.wait() | [
"def",
"reduce",
"(",
"tensor",
",",
"dst",
",",
"op",
"=",
"ReduceOp",
".",
"SUM",
",",
"group",
"=",
"None",
",",
"async_op",
"=",
"False",
")",
":",
"_check_single_tensor",
"(",
"tensor",
",",
"\"tensor\"",
")",
"if",
"_rank_not_in_group",
"(",
"group",
")",
":",
"_warn_not_in_group",
"(",
"\"reduce\"",
")",
"return",
"opts",
"=",
"ReduceOptions",
"(",
")",
"opts",
".",
"reduceOp",
"=",
"op",
"opts",
".",
"rootRank",
"=",
"dst",
"if",
"group",
"is",
"None",
"or",
"group",
"is",
"GroupMember",
".",
"WORLD",
":",
"default_pg",
"=",
"_get_default_group",
"(",
")",
"work",
"=",
"default_pg",
".",
"reduce",
"(",
"[",
"tensor",
"]",
",",
"opts",
")",
"else",
":",
"group_dst_rank",
"=",
"_get_group_rank",
"(",
"group",
",",
"dst",
")",
"opts",
".",
"rootRank",
"=",
"group_dst_rank",
"work",
"=",
"group",
".",
"reduce",
"(",
"[",
"tensor",
"]",
",",
"opts",
")",
"if",
"async_op",
":",
"return",
"work",
"else",
":",
"work",
".",
"wait",
"(",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/distributed_c10d.py#L1437-L1479 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ConfigParser.py | python | Error._get_message | (self) | return self.__message | Getter for 'message'; needed only to override deprecation in
BaseException. | Getter for 'message'; needed only to override deprecation in
BaseException. | [
"Getter",
"for",
"message",
";",
"needed",
"only",
"to",
"override",
"deprecation",
"in",
"BaseException",
"."
] | def _get_message(self):
"""Getter for 'message'; needed only to override deprecation in
BaseException."""
return self.__message | [
"def",
"_get_message",
"(",
"self",
")",
":",
"return",
"self",
".",
"__message"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ConfigParser.py#L115-L118 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | PrinterDC.GetPaperRect | (*args, **kwargs) | return _gdi_.PrinterDC_GetPaperRect(*args, **kwargs) | GetPaperRect(self) -> Rect | GetPaperRect(self) -> Rect | [
"GetPaperRect",
"(",
"self",
")",
"-",
">",
"Rect"
] | def GetPaperRect(*args, **kwargs):
"""GetPaperRect(self) -> Rect"""
return _gdi_.PrinterDC_GetPaperRect(*args, **kwargs) | [
"def",
"GetPaperRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"PrinterDC_GetPaperRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L5412-L5414 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/trade.py | python | Trade.to_dict | (self) | return result | Returns the model properties as a dict | Returns the model properties as a dict | [
"Returns",
"the",
"model",
"properties",
"as",
"a",
"dict"
] | def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Trade, dict):
for key, value in self.items():
result[key] = value
return result | [
"def",
"to_dict",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"attr",
",",
"_",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"swagger_types",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"result",
"[",
"attr",
"]",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"to_dict",
"(",
")",
"if",
"hasattr",
"(",
"x",
",",
"\"to_dict\"",
")",
"else",
"x",
",",
"value",
")",
")",
"elif",
"hasattr",
"(",
"value",
",",
"\"to_dict\"",
")",
":",
"result",
"[",
"attr",
"]",
"=",
"value",
".",
"to_dict",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"result",
"[",
"attr",
"]",
"=",
"dict",
"(",
"map",
"(",
"lambda",
"item",
":",
"(",
"item",
"[",
"0",
"]",
",",
"item",
"[",
"1",
"]",
".",
"to_dict",
"(",
")",
")",
"if",
"hasattr",
"(",
"item",
"[",
"1",
"]",
",",
"\"to_dict\"",
")",
"else",
"item",
",",
"value",
".",
"items",
"(",
")",
")",
")",
"else",
":",
"result",
"[",
"attr",
"]",
"=",
"value",
"if",
"issubclass",
"(",
"Trade",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"items",
"(",
")",
":",
"result",
"[",
"key",
"]",
"=",
"value",
"return",
"result"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/trade.py#L307-L332 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/tensorboard/backend/server.py | python | StartMultiplexerReloadingThread | (multiplexer, path_to_run, load_interval) | return thread | Starts a thread to automatically reload the given multiplexer.
The thread will reload the multiplexer by calling `ReloadMultiplexer` every
`load_interval` seconds, starting immediately.
Args:
multiplexer: The `EventMultiplexer` to add runs to and reload.
path_to_run: A dict mapping from paths to run names, where `None` as the run
name is interpreted as a run name equal to the path.
load_interval: How many seconds to wait after one load before starting the
next load.
Returns:
A started `threading.Thread` that reloads the multiplexer. | Starts a thread to automatically reload the given multiplexer. | [
"Starts",
"a",
"thread",
"to",
"automatically",
"reload",
"the",
"given",
"multiplexer",
"."
] | def StartMultiplexerReloadingThread(multiplexer, path_to_run, load_interval):
"""Starts a thread to automatically reload the given multiplexer.
The thread will reload the multiplexer by calling `ReloadMultiplexer` every
`load_interval` seconds, starting immediately.
Args:
multiplexer: The `EventMultiplexer` to add runs to and reload.
path_to_run: A dict mapping from paths to run names, where `None` as the run
name is interpreted as a run name equal to the path.
load_interval: How many seconds to wait after one load before starting the
next load.
Returns:
A started `threading.Thread` that reloads the multiplexer.
"""
# We don't call multiplexer.Reload() here because that would make
# AddRunsFromDirectory block until the runs have all loaded.
for path in path_to_run.keys():
if gcs.IsGCSPath(path):
gcs.CheckIsSupported()
logging.info(
'Assuming %s is intended to be a Google Cloud Storage path because '
'it starts with %s. If it isn\'t, prefix it with \'/.\' (i.e., use '
'/.%s instead)', path, gcs.PATH_PREFIX, path)
def _ReloadForever():
while True:
ReloadMultiplexer(multiplexer, path_to_run)
time.sleep(load_interval)
thread = threading.Thread(target=_ReloadForever)
thread.daemon = True
thread.start()
return thread | [
"def",
"StartMultiplexerReloadingThread",
"(",
"multiplexer",
",",
"path_to_run",
",",
"load_interval",
")",
":",
"# We don't call multiplexer.Reload() here because that would make",
"# AddRunsFromDirectory block until the runs have all loaded.",
"for",
"path",
"in",
"path_to_run",
".",
"keys",
"(",
")",
":",
"if",
"gcs",
".",
"IsGCSPath",
"(",
"path",
")",
":",
"gcs",
".",
"CheckIsSupported",
"(",
")",
"logging",
".",
"info",
"(",
"'Assuming %s is intended to be a Google Cloud Storage path because '",
"'it starts with %s. If it isn\\'t, prefix it with \\'/.\\' (i.e., use '",
"'/.%s instead)'",
",",
"path",
",",
"gcs",
".",
"PATH_PREFIX",
",",
"path",
")",
"def",
"_ReloadForever",
"(",
")",
":",
"while",
"True",
":",
"ReloadMultiplexer",
"(",
"multiplexer",
",",
"path_to_run",
")",
"time",
".",
"sleep",
"(",
"load_interval",
")",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"_ReloadForever",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")",
"return",
"thread"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/tensorboard/backend/server.py#L105-L139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.