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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/ltisys.py | python | TransferFunction.to_zpk | (self) | return ZerosPolesGain(*tf2zpk(self.num, self.den),
**self._dt_dict) | Convert system representation to `ZerosPolesGain`.
Returns
-------
sys : instance of `ZerosPolesGain`
Zeros, poles, gain representation of the current system | Convert system representation to `ZerosPolesGain`. | [
"Convert",
"system",
"representation",
"to",
"ZerosPolesGain",
"."
] | def to_zpk(self):
"""
Convert system representation to `ZerosPolesGain`.
Returns
-------
sys : instance of `ZerosPolesGain`
Zeros, poles, gain representation of the current system
"""
return ZerosPolesGain(*tf2zpk(self.num, self.den),
**self._dt_dict) | [
"def",
"to_zpk",
"(",
"self",
")",
":",
"return",
"ZerosPolesGain",
"(",
"*",
"tf2zpk",
"(",
"self",
".",
"num",
",",
"self",
".",
"den",
")",
",",
"*",
"*",
"self",
".",
"_dt_dict",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/ltisys.py#L653-L664 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/drafttaskpanels/task_shapestring.py | python | ShapeStringTaskPanel.fileSelect | (self, fn) | Assign the selected file. | Assign the selected file. | [
"Assign",
"the",
"selected",
"file",
"."
] | def fileSelect(self, fn):
"""Assign the selected file."""
self.fileSpec = fn | [
"def",
"fileSelect",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"fileSpec",
"=",
"fn"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/drafttaskpanels/task_shapestring.py#L90-L92 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py | python | CycleStateSpaceModel.get_observation_model | (self, times) | return array_ops.concat(
values=[
array_ops.ones([1], dtype=self.dtype), array_ops.zeros(
[self._periodicity - 2], dtype=self.dtype)
],
axis=0) | Observe only the first of the rotating latent values.
See StateSpaceModel.get_observation_model.
Args:
times: Unused. See the parent class for details.
Returns:
A static, univariate observation model for later broadcasting. | Observe only the first of the rotating latent values. | [
"Observe",
"only",
"the",
"first",
"of",
"the",
"rotating",
"latent",
"values",
"."
] | def get_observation_model(self, times):
"""Observe only the first of the rotating latent values.
See StateSpaceModel.get_observation_model.
Args:
times: Unused. See the parent class for details.
Returns:
A static, univariate observation model for later broadcasting.
"""
del times # Does not rely on times. Uses broadcasting from the parent.
return array_ops.concat(
values=[
array_ops.ones([1], dtype=self.dtype), array_ops.zeros(
[self._periodicity - 2], dtype=self.dtype)
],
axis=0) | [
"def",
"get_observation_model",
"(",
"self",
",",
"times",
")",
":",
"del",
"times",
"# Does not rely on times. Uses broadcasting from the parent.",
"return",
"array_ops",
".",
"concat",
"(",
"values",
"=",
"[",
"array_ops",
".",
"ones",
"(",
"[",
"1",
"]",
",",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py#L180-L195 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/.ycm_extra_conf.py | python | FlagsForFile | (filename) | return {
'flags': final_flags,
'do_cache': True
} | This is the main entry point for YCM. Its interface is fixed.
Args:
filename: (String) Path to source file being edited.
Returns:
(Dictionary)
'flags': (List of Strings) Command line flags.
'do_cache': (Boolean) True if the result should be cached. | This is the main entry point for YCM. Its interface is fixed. | [
"This",
"is",
"the",
"main",
"entry",
"point",
"for",
"YCM",
".",
"Its",
"interface",
"is",
"fixed",
"."
] | def FlagsForFile(filename):
"""This is the main entry point for YCM. Its interface is fixed.
Args:
filename: (String) Path to source file being edited.
Returns:
(Dictionary)
'flags': (List of Strings) Command line flags.
'do_cache': (Boolean) True if the result should be cached.
"""
v8_root = FindV8SrcFromFilename(filename)
v8_flags = GetClangCommandFromNinjaForFilename(v8_root, filename)
final_flags = flags + v8_flags
return {
'flags': final_flags,
'do_cache': True
} | [
"def",
"FlagsForFile",
"(",
"filename",
")",
":",
"v8_root",
"=",
"FindV8SrcFromFilename",
"(",
"filename",
")",
"v8_flags",
"=",
"GetClangCommandFromNinjaForFilename",
"(",
"v8_root",
",",
"filename",
")",
"final_flags",
"=",
"flags",
"+",
"v8_flags",
"return",
"... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/.ycm_extra_conf.py#L176-L193 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/tk_graph_ui.py | python | TkGraphWidget.get_active_facts | (self) | return facts | Return a list of the selected facts | Return a list of the selected facts | [
"Return",
"a",
"list",
"of",
"the",
"selected",
"facts"
] | def get_active_facts(self):
"""
Return a list of the selected facts
"""
facts = self.g.constraints.conjuncts()
if hasattr(self,'selected_constraints'):
sc = self.selected_constraints
if len(sc) == len(facts): # paranoia
facts = [x for x,y in zip(facts,sc) if y]
return facts | [
"def",
"get_active_facts",
"(",
"self",
")",
":",
"facts",
"=",
"self",
".",
"g",
".",
"constraints",
".",
"conjuncts",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"'selected_constraints'",
")",
":",
"sc",
"=",
"self",
".",
"selected_constraints",
"if",
... | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/tk_graph_ui.py#L201-L210 | |
junhyukoh/caffe-lstm | 598d45456fa2a1b127a644f4aa38daa8fb9fc722 | scripts/cpp_lint.py | python | CheckPosixThreading | (filename, clean_lines, linenum, error) | Checks for calls to thread-unsafe functions.
Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for calls to thread-unsafe functions. | [
"Checks",
"for",
"calls",
"to",
"thread",
"-",
"unsafe",
"functions",
"."
] | def CheckPosixThreading(filename, clean_lines, linenum, error):
"""Checks for calls to thread-unsafe functions.
Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for single_thread_function, multithread_safe_function in threading_list:
ix = line.find(single_thread_function)
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
error(filename, linenum, 'runtime/threadsafe_fn', 2,
'Consider using ' + multithread_safe_function +
'...) instead of ' + single_thread_function +
'...) for improved thread safety.') | [
"def",
"CheckPosixThreading",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"for",
"single_thread_function",
",",
"multithread_safe_function",
"in",
"threading_list",
":... | https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L1681-L1705 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap_external.py | python | ExtensionFileLoader.get_code | (self, fullname) | return None | Return None as an extension module cannot create a code object. | Return None as an extension module cannot create a code object. | [
"Return",
"None",
"as",
"an",
"extension",
"module",
"cannot",
"create",
"a",
"code",
"object",
"."
] | def get_code(self, fullname):
"""Return None as an extension module cannot create a code object."""
return None | [
"def",
"get_code",
"(",
"self",
",",
"fullname",
")",
":",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap_external.py#L1060-L1062 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py | python | fields | (cls) | return attrs | Return the tuple of ``attrs`` attributes for a class.
The tuple also allows accessing the fields by their names (see below for
examples).
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: tuple (with name accessors) of `attr.Attribute`
.. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
by name. | Return the tuple of ``attrs`` attributes for a class. | [
"Return",
"the",
"tuple",
"of",
"attrs",
"attributes",
"for",
"a",
"class",
"."
] | def fields(cls):
"""
Return the tuple of ``attrs`` attributes for a class.
The tuple also allows accessing the fields by their names (see below for
examples).
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: tuple (with name accessors) of `attr.Attribute`
.. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
by name.
"""
if not isclass(cls):
raise TypeError("Passed object must be a class.")
attrs = getattr(cls, "__attrs_attrs__", None)
if attrs is None:
raise NotAnAttrsClassError(
"{cls!r} is not an attrs-decorated class.".format(cls=cls)
)
return attrs | [
"def",
"fields",
"(",
"cls",
")",
":",
"if",
"not",
"isclass",
"(",
"cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Passed object must be a class.\"",
")",
"attrs",
"=",
"getattr",
"(",
"cls",
",",
"\"__attrs_attrs__\"",
",",
"None",
")",
"if",
"attrs",
"is... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py#L1377-L1402 | |
include-what-you-use/include-what-you-use | 208fbfffa5d69364b9f78e427caa443441279283 | fix_includes.py | python | _IsSameProject | (line_info, edited_file, project) | return (included_root and edited_root and included_root == edited_root) | Return true if included file and edited file are in the same project.
An included_file is in project 'project' if the project is a prefix of the
included_file. 'project' should end with /.
As a special case, if project is '<tld>', then the project is defined to
be the top-level directory of edited_file.
Arguments:
line_info: a LineInfo structure with .key containing the file that is
being included.
edited_file: the name of the file being edited.
project: if '<tld>', set the project path to be the top-level directory
name of the file being edited. If not '<tld>', this value is used to
specify the project directory.
Returns:
True if line_info and filename belong in the same project, False otherwise. | Return true if included file and edited file are in the same project. | [
"Return",
"true",
"if",
"included",
"file",
"and",
"edited",
"file",
"are",
"in",
"the",
"same",
"project",
"."
] | def _IsSameProject(line_info, edited_file, project):
"""Return true if included file and edited file are in the same project.
An included_file is in project 'project' if the project is a prefix of the
included_file. 'project' should end with /.
As a special case, if project is '<tld>', then the project is defined to
be the top-level directory of edited_file.
Arguments:
line_info: a LineInfo structure with .key containing the file that is
being included.
edited_file: the name of the file being edited.
project: if '<tld>', set the project path to be the top-level directory
name of the file being edited. If not '<tld>', this value is used to
specify the project directory.
Returns:
True if line_info and filename belong in the same project, False otherwise.
"""
included_file = line_info.key[1:]
if project != '<tld>':
return included_file.startswith(project)
included_root = _GetPathRoot(included_file)
edited_root = _GetPathRoot(edited_file)
return (included_root and edited_root and included_root == edited_root) | [
"def",
"_IsSameProject",
"(",
"line_info",
",",
"edited_file",
",",
"project",
")",
":",
"included_file",
"=",
"line_info",
".",
"key",
"[",
"1",
":",
"]",
"if",
"project",
"!=",
"'<tld>'",
":",
"return",
"included_file",
".",
"startswith",
"(",
"project",
... | https://github.com/include-what-you-use/include-what-you-use/blob/208fbfffa5d69364b9f78e427caa443441279283/fix_includes.py#L1628-L1653 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/results.py | python | Analysis.arcs_unpredicted | (self) | return sorted(unpredicted) | Returns a sorted list of the executed arcs missing from the code. | Returns a sorted list of the executed arcs missing from the code. | [
"Returns",
"a",
"sorted",
"list",
"of",
"the",
"executed",
"arcs",
"missing",
"from",
"the",
"code",
"."
] | def arcs_unpredicted(self):
"""Returns a sorted list of the executed arcs missing from the code."""
possible = self.arc_possibilities()
executed = self.arcs_executed()
# Exclude arcs here which connect a line to itself. They can occur
# in executed data in some cases. This is where they can cause
# trouble, and here is where it's the least burden to remove them.
unpredicted = [
e for e in executed
if e not in possible
and e[0] != e[1]
]
return sorted(unpredicted) | [
"def",
"arcs_unpredicted",
"(",
"self",
")",
":",
"possible",
"=",
"self",
".",
"arc_possibilities",
"(",
")",
"executed",
"=",
"self",
".",
"arcs_executed",
"(",
")",
"# Exclude arcs here which connect a line to itself. They can occur",
"# in executed data in some cases. ... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/results.py#L95-L107 | |
vtraag/louvain-igraph | 124ea1be49ee74eec2eaca8006599d7fc5560db6 | src/louvain/VertexPartition.py | python | MutableVertexPartition.weight_to_comm | (self, v, comm) | return _c_louvain._MutableVertexPartition_weight_to_comm(self._partition, v, comm) | The total number of edges (or sum of weights) from node ``v`` to
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_from_comm` | The total number of edges (or sum of weights) from node ``v`` to
community ``comm``. | [
"The",
"total",
"number",
"of",
"edges",
"(",
"or",
"sum",
"of",
"weights",
")",
"from",
"node",
"v",
"to",
"community",
"comm",
"."
] | def weight_to_comm(self, v, comm):
""" The total number of edges (or sum of weights) from node ``v`` to
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_from_comm`
"""
return _c_louvain._MutableVertexPartition_weight_to_comm(self._partition, v, comm) | [
"def",
"weight_to_comm",
"(",
"self",
",",
"v",
",",
"comm",
")",
":",
"return",
"_c_louvain",
".",
"_MutableVertexPartition_weight_to_comm",
"(",
"self",
".",
"_partition",
",",
"v",
",",
"comm",
")"
] | https://github.com/vtraag/louvain-igraph/blob/124ea1be49ee74eec2eaca8006599d7fc5560db6/src/louvain/VertexPartition.py#L364-L372 | |
pgRouting/osm2pgrouting | 8491929fc4037d308f271e84d59bb96da3c28aa2 | tools/cpplint.py | python | _BackupFilters | () | Saves the current filter list to backup storage. | Saves the current filter list to backup storage. | [
"Saves",
"the",
"current",
"filter",
"list",
"to",
"backup",
"storage",
"."
] | def _BackupFilters():
""" Saves the current filter list to backup storage."""
_cpplint_state.BackupFilters() | [
"def",
"_BackupFilters",
"(",
")",
":",
"_cpplint_state",
".",
"BackupFilters",
"(",
")"
] | https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L903-L905 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/jedi/jedi/evaluate/compiled/context.py | python | _parse_function_doc | (doc) | return param_str, ret | Takes a function and returns the params and return value as a tuple.
This is nothing more than a docstring parser.
TODO docstrings like utime(path, (atime, mtime)) and a(b [, b]) -> None
TODO docstrings like 'tuple of integers' | Takes a function and returns the params and return value as a tuple.
This is nothing more than a docstring parser. | [
"Takes",
"a",
"function",
"and",
"returns",
"the",
"params",
"and",
"return",
"value",
"as",
"a",
"tuple",
".",
"This",
"is",
"nothing",
"more",
"than",
"a",
"docstring",
"parser",
"."
] | def _parse_function_doc(doc):
"""
Takes a function and returns the params and return value as a tuple.
This is nothing more than a docstring parser.
TODO docstrings like utime(path, (atime, mtime)) and a(b [, b]) -> None
TODO docstrings like 'tuple of integers'
"""
doc = force_unicode(doc)
# parse round parentheses: def func(a, (b,c))
try:
count = 0
start = doc.index('(')
for i, s in enumerate(doc[start:]):
if s == '(':
count += 1
elif s == ')':
count -= 1
if count == 0:
end = start + i
break
param_str = doc[start + 1:end]
except (ValueError, UnboundLocalError):
# ValueError for doc.index
# UnboundLocalError for undefined end in last line
debug.dbg('no brackets found - no param')
end = 0
param_str = u''
else:
# remove square brackets, that show an optional param ( = None)
def change_options(m):
args = m.group(1).split(',')
for i, a in enumerate(args):
if a and '=' not in a:
args[i] += '=None'
return ','.join(args)
while True:
param_str, changes = re.subn(r' ?\[([^\[\]]+)\]',
change_options, param_str)
if changes == 0:
break
param_str = param_str.replace('-', '_') # see: isinstance.__doc__
# parse return value
r = re.search(u'-[>-]* ', doc[end:end + 7])
if r is None:
ret = u''
else:
index = end + r.end()
# get result type, which can contain newlines
pattern = re.compile(r'(,\n|[^\n-])+')
ret_str = pattern.match(doc, index).group(0).strip()
# New object -> object()
ret_str = re.sub(r'[nN]ew (.*)', r'\1()', ret_str)
ret = docstr_defaults.get(ret_str, ret_str)
return param_str, ret | [
"def",
"_parse_function_doc",
"(",
"doc",
")",
":",
"doc",
"=",
"force_unicode",
"(",
"doc",
")",
"# parse round parentheses: def func(a, (b,c))",
"try",
":",
"count",
"=",
"0",
"start",
"=",
"doc",
".",
"index",
"(",
"'('",
")",
"for",
"i",
",",
"s",
"in"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/evaluate/compiled/context.py#L381-L439 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | parserCtxt.parseName | (self) | return ret | parse an XML name. [4] NameChar ::= Letter | Digit | '.' |
'-' | '_' | ':' | CombiningChar | Extender [5] Name ::=
(Letter | '_' | ':') (NameChar)* [6] Names ::= Name (#x20
Name)* | parse an XML name. [4] NameChar ::= Letter | Digit | '.' |
'-' | '_' | ':' | CombiningChar | Extender [5] Name ::=
(Letter | '_' | ':') (NameChar)* [6] Names ::= Name (#x20
Name)* | [
"parse",
"an",
"XML",
"name",
".",
"[",
"4",
"]",
"NameChar",
"::",
"=",
"Letter",
"|",
"Digit",
"|",
".",
"|",
"-",
"|",
"_",
"|",
":",
"|",
"CombiningChar",
"|",
"Extender",
"[",
"5",
"]",
"Name",
"::",
"=",
"(",
"Letter",
"|",
"_",
"|",
":... | def parseName(self):
"""parse an XML name. [4] NameChar ::= Letter | Digit | '.' |
'-' | '_' | ':' | CombiningChar | Extender [5] Name ::=
(Letter | '_' | ':') (NameChar)* [6] Names ::= Name (#x20
Name)* """
ret = libxml2mod.xmlParseName(self._o)
return ret | [
"def",
"parseName",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlParseName",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L5285-L5291 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | EventLoopBase_SetActive | (*args, **kwargs) | return _core_.EventLoopBase_SetActive(*args, **kwargs) | EventLoopBase_SetActive(EventLoopBase loop) | EventLoopBase_SetActive(EventLoopBase loop) | [
"EventLoopBase_SetActive",
"(",
"EventLoopBase",
"loop",
")"
] | def EventLoopBase_SetActive(*args, **kwargs):
"""EventLoopBase_SetActive(EventLoopBase loop)"""
return _core_.EventLoopBase_SetActive(*args, **kwargs) | [
"def",
"EventLoopBase_SetActive",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"EventLoopBase_SetActive",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8848-L8850 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | docs/sphinxext/mantiddoc/directives/base.py | python | AlgorithmBaseDirective._set_algorithm_name_and_version | (self) | Returns the name and version of an algorithm based on the name of the
document. The expected name of the document is "AlgorithmName-v?", which
is the name of the file with the extension removed | Returns the name and version of an algorithm based on the name of the
document. The expected name of the document is "AlgorithmName-v?", which
is the name of the file with the extension removed | [
"Returns",
"the",
"name",
"and",
"version",
"of",
"an",
"algorithm",
"based",
"on",
"the",
"name",
"of",
"the",
"document",
".",
"The",
"expected",
"name",
"of",
"the",
"document",
"is",
"AlgorithmName",
"-",
"v?",
"which",
"is",
"the",
"name",
"of",
"th... | def _set_algorithm_name_and_version(self):
"""
Returns the name and version of an algorithm based on the name of the
document. The expected name of the document is "AlgorithmName-v?", which
is the name of the file with the extension removed
"""
(self.algm_name, self.algm_version) = algorithm_name_and_version(self.source()) | [
"def",
"_set_algorithm_name_and_version",
"(",
"self",
")",
":",
"(",
"self",
".",
"algm_name",
",",
"self",
".",
"algm_version",
")",
"=",
"algorithm_name_and_version",
"(",
"self",
".",
"source",
"(",
")",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/docs/sphinxext/mantiddoc/directives/base.py#L247-L253 | ||
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Tool/FortranCommon.py | python | add_f95_to_env | (env) | Add Builders and construction variables for f95 to an Environment. | Add Builders and construction variables for f95 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f95",
"to",
"an",
"Environment",
"."
] | def add_f95_to_env(env):
"""Add Builders and construction variables for f95 to an Environment."""
try:
F95Suffixes = env['F95FILESUFFIXES']
except KeyError:
F95Suffixes = ['.f95']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F95PPSuffixes = env['F95PPFILESUFFIXES']
except KeyError:
F95PPSuffixes = []
DialectAddToEnv(env, "F95", F95Suffixes, F95PPSuffixes,
support_module = 1) | [
"def",
"add_f95_to_env",
"(",
"env",
")",
":",
"try",
":",
"F95Suffixes",
"=",
"env",
"[",
"'F95FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F95Suffixes",
"=",
"[",
"'.f95'",
"]",
"#print(\"Adding %s to f95 suffixes\" % F95Suffixes)",
"try",
":",
"F95PPSuffixes"... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/FortranCommon.py#L218-L232 | ||
microsoft/DirectXShaderCompiler | 8348ff8d9e0287610ba05d3a828e10af981a1c05 | tools/clang/bindings/python/clang/cindex.py | python | SourceRange.__contains__ | (self, other) | return False | Useful to detect the Token/Lexer bug | Useful to detect the Token/Lexer bug | [
"Useful",
"to",
"detect",
"the",
"Token",
"/",
"Lexer",
"bug"
] | def __contains__(self, other):
"""Useful to detect the Token/Lexer bug"""
if not isinstance(other, SourceLocation):
return False
if other.file is None and self.start.file is None:
pass
elif ( self.start.file.name != other.file.name or
other.file.name != self.end.file.name):
# same file name
return False
# same file, in between lines
if self.start.line < other.line < self.end.line:
return True
elif self.start.line == other.line:
# same file first line
if self.start.column <= other.column:
return True
elif other.line == self.end.line:
# same file last line
if other.column <= self.end.column:
return True
return False | [
"def",
"__contains__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"SourceLocation",
")",
":",
"return",
"False",
"if",
"other",
".",
"file",
"is",
"None",
"and",
"self",
".",
"start",
".",
"file",
"is",
"None",
... | https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/tools/clang/bindings/python/clang/cindex.py#L269-L290 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/contrib/crosstalkcaffe/utils/format.py | python | json_parser | (path) | return conf | Parse a json file into dict
Args:
path: the path to json file
Return:
(dict): the parsed dict | Parse a json file into dict | [
"Parse",
"a",
"json",
"file",
"into",
"dict"
] | def json_parser(path):
'''
Parse a json file into dict
Args:
path: the path to json file
Return:
(dict): the parsed dict
'''
with open(path, 'r') as conf:
conf = json.JSONDecoder().raw_decode(conf.read())[0]
# to support python2/3 in both unicode and utf-8
python_version = [int(v) for v in platform.python_version().split('.')]
if python_version[0] < 3:
conf = _unicode_to_utf(conf)
return conf | [
"def",
"json_parser",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"conf",
":",
"conf",
"=",
"json",
".",
"JSONDecoder",
"(",
")",
".",
"raw_decode",
"(",
"conf",
".",
"read",
"(",
")",
")",
"[",
"0",
"]",
"# to supp... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/crosstalkcaffe/utils/format.py#L41-L57 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py | python | _parse_input_dimensions | (args, input_core_dims) | return broadcast_shape, dim_sizes | Parse broadcast and core dimensions for vectorize with a signature.
Arguments
---------
args : Tuple[ndarray, ...]
Tuple of input arguments to examine.
input_core_dims : List[Tuple[str, ...]]
List of core dimensions corresponding to each input.
Returns
-------
broadcast_shape : Tuple[int, ...]
Common shape to broadcast all non-core dimensions to.
dim_sizes : Dict[str, int]
Common sizes for named core dimensions. | Parse broadcast and core dimensions for vectorize with a signature. | [
"Parse",
"broadcast",
"and",
"core",
"dimensions",
"for",
"vectorize",
"with",
"a",
"signature",
"."
] | def _parse_input_dimensions(args, input_core_dims):
"""
Parse broadcast and core dimensions for vectorize with a signature.
Arguments
---------
args : Tuple[ndarray, ...]
Tuple of input arguments to examine.
input_core_dims : List[Tuple[str, ...]]
List of core dimensions corresponding to each input.
Returns
-------
broadcast_shape : Tuple[int, ...]
Common shape to broadcast all non-core dimensions to.
dim_sizes : Dict[str, int]
Common sizes for named core dimensions.
"""
broadcast_args = []
dim_sizes = {}
for arg, core_dims in zip(args, input_core_dims):
_update_dim_sizes(dim_sizes, arg, core_dims)
ndim = arg.ndim - len(core_dims)
dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim])
broadcast_args.append(dummy_array)
broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args)
return broadcast_shape, dim_sizes | [
"def",
"_parse_input_dimensions",
"(",
"args",
",",
"input_core_dims",
")",
":",
"broadcast_args",
"=",
"[",
"]",
"dim_sizes",
"=",
"{",
"}",
"for",
"arg",
",",
"core_dims",
"in",
"zip",
"(",
"args",
",",
"input_core_dims",
")",
":",
"_update_dim_sizes",
"("... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py#L1835-L1861 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | utils/lit/lit/util.py | python | detectCPUs | () | return 1 | Detects the number of CPUs on a system.
Cribbed from pp. | Detects the number of CPUs on a system. | [
"Detects",
"the",
"number",
"of",
"CPUs",
"on",
"a",
"system",
"."
] | def detectCPUs():
"""Detects the number of CPUs on a system.
Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, 'sysconf'):
if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf('SC_NPROCESSORS_ONLN')
if isinstance(ncpus, int) and ncpus > 0:
return ncpus
else: # OSX:
return int(subprocess.check_output(['sysctl', '-n', 'hw.ncpu'],
stderr=subprocess.STDOUT))
# Windows:
if 'NUMBER_OF_PROCESSORS' in os.environ:
ncpus = int(os.environ['NUMBER_OF_PROCESSORS'])
if ncpus > 0:
# With more than 32 processes, process creation often fails with
# "Too many open files". FIXME: Check if there's a better fix.
return min(ncpus, 32)
return 1 | [
"def",
"detectCPUs",
"(",
")",
":",
"# Linux, Unix and MacOS:",
"if",
"hasattr",
"(",
"os",
",",
"'sysconf'",
")",
":",
"if",
"'SC_NPROCESSORS_ONLN'",
"in",
"os",
".",
"sysconf_names",
":",
"# Linux & Unix:",
"ncpus",
"=",
"os",
".",
"sysconf",
"(",
"'SC_NPROC... | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/utils/lit/lit/util.py#L103-L126 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/service.py | python | RpcController.IsCanceled | (self) | Checks if the client cancelled the RPC.
If true, indicates that the client canceled the RPC, so the server may
as well give up on replying to it. The server should still call the
final "done" callback. | Checks if the client cancelled the RPC. | [
"Checks",
"if",
"the",
"client",
"cancelled",
"the",
"RPC",
"."
] | def IsCanceled(self):
"""Checks if the client cancelled the RPC.
If true, indicates that the client canceled the RPC, so the server may
as well give up on replying to it. The server should still call the
final "done" callback.
"""
raise NotImplementedError | [
"def",
"IsCanceled",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/service.py#L177-L184 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sets.py | python | BaseSet.__deepcopy__ | (self, memo) | return result | Return a deep copy of a set; used by copy module. | Return a deep copy of a set; used by copy module. | [
"Return",
"a",
"deep",
"copy",
"of",
"a",
"set",
";",
"used",
"by",
"copy",
"module",
"."
] | def __deepcopy__(self, memo):
"""Return a deep copy of a set; used by copy module."""
# This pre-creates the result and inserts it in the memo
# early, in case the deep copy recurses into another reference
# to this same set. A set can't be an element of itself, but
# it can certainly contain an object that has a reference to
# itself.
from copy import deepcopy
result = self.__class__()
memo[id(self)] = result
data = result._data
value = True
for elt in self:
data[deepcopy(elt, memo)] = value
return result | [
"def",
"__deepcopy__",
"(",
"self",
",",
"memo",
")",
":",
"# This pre-creates the result and inserts it in the memo",
"# early, in case the deep copy recurses into another reference",
"# to this same set. A set can't be an element of itself, but",
"# it can certainly contain an object that h... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sets.py#L153-L167 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/pyserial/serial/serialutil.py | python | FileLike.readline | (self, size=None, eol=LF) | return bytes(line) | read a line which is terminated with end-of-line (eol) character
('\n' by default) or until timeout. | read a line which is terminated with end-of-line (eol) character
('\n' by default) or until timeout. | [
"read",
"a",
"line",
"which",
"is",
"terminated",
"with",
"end",
"-",
"of",
"-",
"line",
"(",
"eol",
")",
"character",
"(",
"\\",
"n",
"by",
"default",
")",
"or",
"until",
"timeout",
"."
] | def readline(self, size=None, eol=LF):
"""read a line which is terminated with end-of-line (eol) character
('\n' by default) or until timeout."""
leneol = len(eol)
line = bytearray()
while True:
c = self.read(1)
if c:
line += c
if line[-leneol:] == eol:
break
if size is not None and len(line) >= size:
break
else:
break
return bytes(line) | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"None",
",",
"eol",
"=",
"LF",
")",
":",
"leneol",
"=",
"len",
"(",
"eol",
")",
"line",
"=",
"bytearray",
"(",
")",
"while",
"True",
":",
"c",
"=",
"self",
".",
"read",
"(",
"1",
")",
"if",
"c... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/serialutil.py#L162-L177 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/wheel.py | python | Wheel.update | (self, modifier, dest_dir=None, **kwargs) | return modified | Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the corresponding archive entries can be found. The
modifier is free to change the contents of the files pointed to, add
new entries and remove entries, before returning. This method will
extract the entire contents of the wheel to a temporary location, call
the modifier, and then use the passed (and possibly updated)
dictionary to write a new wheel. If ``dest_dir`` is specified, the new
wheel is written there -- otherwise, the original wheel is overwritten.
The modifier should return True if it updated the wheel, else False.
This method returns the same value the modifier returns. | Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the corresponding archive entries can be found. The
modifier is free to change the contents of the files pointed to, add
new entries and remove entries, before returning. This method will
extract the entire contents of the wheel to a temporary location, call
the modifier, and then use the passed (and possibly updated)
dictionary to write a new wheel. If ``dest_dir`` is specified, the new
wheel is written there -- otherwise, the original wheel is overwritten. | [
"Update",
"the",
"contents",
"of",
"a",
"wheel",
"in",
"a",
"generic",
"way",
".",
"The",
"modifier",
"should",
"be",
"a",
"callable",
"which",
"expects",
"a",
"dictionary",
"argument",
":",
"its",
"keys",
"are",
"archive",
"-",
"entry",
"paths",
"and",
... | def update(self, modifier, dest_dir=None, **kwargs):
"""
Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the corresponding archive entries can be found. The
modifier is free to change the contents of the files pointed to, add
new entries and remove entries, before returning. This method will
extract the entire contents of the wheel to a temporary location, call
the modifier, and then use the passed (and possibly updated)
dictionary to write a new wheel. If ``dest_dir`` is specified, the new
wheel is written there -- otherwise, the original wheel is overwritten.
The modifier should return True if it updated the wheel, else False.
This method returns the same value the modifier returns.
"""
def get_version(path_map, info_dir):
version = path = None
key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME)
if key not in path_map:
key = '%s/PKG-INFO' % info_dir
if key in path_map:
path = path_map[key]
version = Metadata(path=path).version
return version, path
def update_version(version, path):
updated = None
try:
v = NormalizedVersion(version)
i = version.find('-')
if i < 0:
updated = '%s+1' % version
else:
parts = [int(s) for s in version[i + 1:].split('.')]
parts[-1] += 1
updated = '%s+%s' % (version[:i],
'.'.join(str(i) for i in parts))
except UnsupportedVersionError:
logger.debug('Cannot update non-compliant (PEP-440) '
'version %r', version)
if updated:
md = Metadata(path=path)
md.version = updated
legacy = path.endswith(LEGACY_METADATA_FILENAME)
md.write(path=path, legacy=legacy)
logger.debug('Version updated from %r to %r', version,
updated)
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
info_dir = '%s.dist-info' % name_ver
record_name = posixpath.join(info_dir, 'RECORD')
with tempdir() as workdir:
with ZipFile(pathname, 'r') as zf:
path_map = {}
for zinfo in zf.infolist():
arcname = zinfo.filename
if isinstance(arcname, text_type):
u_arcname = arcname
else:
u_arcname = arcname.decode('utf-8')
if u_arcname == record_name:
continue
if '..' in u_arcname:
raise DistlibException('invalid entry in '
'wheel: %r' % u_arcname)
zf.extract(zinfo, workdir)
path = os.path.join(workdir, convert_path(u_arcname))
path_map[u_arcname] = path
# Remember the version.
original_version, _ = get_version(path_map, info_dir)
# Files extracted. Call the modifier.
modified = modifier(path_map, **kwargs)
if modified:
# Something changed - need to build a new wheel.
current_version, path = get_version(path_map, info_dir)
if current_version and (current_version == original_version):
# Add or update local version to signify changes.
update_version(current_version, path)
# Decide where the new wheel goes.
if dest_dir is None:
fd, newpath = tempfile.mkstemp(suffix='.whl',
prefix='wheel-update-',
dir=workdir)
os.close(fd)
else:
if not os.path.isdir(dest_dir):
raise DistlibException('Not a directory: %r' % dest_dir)
newpath = os.path.join(dest_dir, self.filename)
archive_paths = list(path_map.items())
distinfo = os.path.join(workdir, info_dir)
info = distinfo, info_dir
self.write_records(info, workdir, archive_paths)
self.build_zip(newpath, archive_paths)
if dest_dir is None:
shutil.copyfile(newpath, pathname)
return modified | [
"def",
"update",
"(",
"self",
",",
"modifier",
",",
"dest_dir",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"get_version",
"(",
"path_map",
",",
"info_dir",
")",
":",
"version",
"=",
"path",
"=",
"None",
"key",
"=",
"'%s/%s'",
"%",
"(",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/wheel.py#L840-L939 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/heapq.py | python | heappushpop | (heap, item) | return item | Fast version of a heappush followed by a heappop. | Fast version of a heappush followed by a heappop. | [
"Fast",
"version",
"of",
"a",
"heappush",
"followed",
"by",
"a",
"heappop",
"."
] | def heappushpop(heap, item):
"""Fast version of a heappush followed by a heappop."""
if heap and heap[0] < item:
item, heap[0] = heap[0], item
_siftup(heap, 0)
return item | [
"def",
"heappushpop",
"(",
"heap",
",",
"item",
")",
":",
"if",
"heap",
"and",
"heap",
"[",
"0",
"]",
"<",
"item",
":",
"item",
",",
"heap",
"[",
"0",
"]",
"=",
"heap",
"[",
"0",
"]",
",",
"item",
"_siftup",
"(",
"heap",
",",
"0",
")",
"retur... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/heapq.py#L161-L166 | |
wuye9036/SalviaRenderer | a3931dec1b1e5375ef497a9d4d064f0521ba6f37 | blibs/cpuinfo.py | python | _get_cpu_info_from_cat_var_run_dmesg_boot | () | return _parse_dmesg_output(output) | Returns the CPU info gathered from /var/run/dmesg.boot.
Returns {} if dmesg is not found or does not have the desired info. | Returns the CPU info gathered from /var/run/dmesg.boot.
Returns {} if dmesg is not found or does not have the desired info. | [
"Returns",
"the",
"CPU",
"info",
"gathered",
"from",
"/",
"var",
"/",
"run",
"/",
"dmesg",
".",
"boot",
".",
"Returns",
"{}",
"if",
"dmesg",
"is",
"not",
"found",
"or",
"does",
"not",
"have",
"the",
"desired",
"info",
"."
] | def _get_cpu_info_from_cat_var_run_dmesg_boot():
'''
Returns the CPU info gathered from /var/run/dmesg.boot.
Returns {} if dmesg is not found or does not have the desired info.
'''
# Just return {} if there is no /var/run/dmesg.boot
if not DataSource.has_var_run_dmesg_boot():
return {}
# If dmesg.boot fails return {}
returncode, output = DataSource.cat_var_run_dmesg_boot()
if output == None or returncode != 0:
return {}
return _parse_dmesg_output(output) | [
"def",
"_get_cpu_info_from_cat_var_run_dmesg_boot",
"(",
")",
":",
"# Just return {} if there is no /var/run/dmesg.boot",
"if",
"not",
"DataSource",
".",
"has_var_run_dmesg_boot",
"(",
")",
":",
"return",
"{",
"}",
"# If dmesg.boot fails return {}",
"returncode",
",",
"output... | https://github.com/wuye9036/SalviaRenderer/blob/a3931dec1b1e5375ef497a9d4d064f0521ba6f37/blibs/cpuinfo.py#L1653-L1667 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.winfo_fpixels | (self, number) | return getdouble(self.tk.call(
'winfo', 'fpixels', self._w, number)) | Return the number of pixels for the given distance NUMBER
(e.g. "3c") as float. | Return the number of pixels for the given distance NUMBER
(e.g. "3c") as float. | [
"Return",
"the",
"number",
"of",
"pixels",
"for",
"the",
"given",
"distance",
"NUMBER",
"(",
"e",
".",
"g",
".",
"3c",
")",
"as",
"float",
"."
] | def winfo_fpixels(self, number):
"""Return the number of pixels for the given distance NUMBER
(e.g. "3c") as float."""
return getdouble(self.tk.call(
'winfo', 'fpixels', self._w, number)) | [
"def",
"winfo_fpixels",
"(",
"self",
",",
"number",
")",
":",
"return",
"getdouble",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'fpixels'",
",",
"self",
".",
"_w",
",",
"number",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L771-L775 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/tools/scan-build-py/libear/__init__.py | python | Toolset.set_language_standard | (self, standard) | part of public interface | part of public interface | [
"part",
"of",
"public",
"interface"
] | def set_language_standard(self, standard):
""" part of public interface """
self.c_flags.append('-std=' + standard) | [
"def",
"set_language_standard",
"(",
"self",
",",
"standard",
")",
":",
"self",
".",
"c_flags",
".",
"append",
"(",
"'-std='",
"+",
"standard",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/tools/scan-build-py/libear/__init__.py#L90-L92 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/tools/sancov/coverage-report-server.py | python | SymcovData.compute_filecoverage | (self) | return result | Build a filename->pct coverage. | Build a filename->pct coverage. | [
"Build",
"a",
"filename",
"-",
">",
"pct",
"coverage",
"."
] | def compute_filecoverage(self):
"""Build a filename->pct coverage."""
result = dict()
for filename, fns in self.point_symbol_info.items():
file_points = []
for fn, points in fns.items():
file_points.extend(points.keys())
covered_points = self.covered_points & set(file_points)
result[filename] = int(math.ceil(
len(covered_points) * 100 / len(file_points)))
return result | [
"def",
"compute_filecoverage",
"(",
"self",
")",
":",
"result",
"=",
"dict",
"(",
")",
"for",
"filename",
",",
"fns",
"in",
"self",
".",
"point_symbol_info",
".",
"items",
"(",
")",
":",
"file_points",
"=",
"[",
"]",
"for",
"fn",
",",
"points",
"in",
... | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/sancov/coverage-report-server.py#L106-L116 | |
grrrr/py | 7c56d29a0be2f84064979ae28e32b0fa33710479 | scripts/script.py | python | addall | (*args) | return reduce(lambda a,b: a+b, args,0) | Add a couple of numbers | Add a couple of numbers | [
"Add",
"a",
"couple",
"of",
"numbers"
] | def addall(*args): # variable argument list
"""Add a couple of numbers"""
return reduce(lambda a,b: a+b, args,0) | [
"def",
"addall",
"(",
"*",
"args",
")",
":",
"# variable argument list",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"a",
"+",
"b",
",",
"args",
",",
"0",
")"
] | https://github.com/grrrr/py/blob/7c56d29a0be2f84064979ae28e32b0fa33710479/scripts/script.py#L33-L35 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/nn_ops.py | python | convolution_internal | (
input, # pylint: disable=redefined-builtin
filters,
strides=None,
padding="VALID",
data_format=None,
dilations=None,
name=None,
call_from_convolution=True,
num_spatial_dims=None) | Internal function which performs rank agnostic convolution.
Args:
input: See `convolution`.
filters: See `convolution`.
strides: See `convolution`.
padding: See `convolution`.
data_format: See `convolution`.
dilations: See `convolution`.
name: See `convolution`.
call_from_convolution: See `convolution`.
num_spatial_dims: (Optional.). It is a integer describing the
rank of the spatial dimensions. For `1-D`, `2-D` and `3-D` convolutions,
the value of `num_spatial_dims` is `1`, `2`, and `3`, respectively.
This argument is only required to disambiguate the rank of `batch_shape`
when `filter_shape.ndims is None` and `len(batch_shape) > 1`. For
backwards compatibility, if `num_spatial_dims is None` and
`filter_shape.ndims is None`, then `len(batch_shape)` is assumed to be
`1` (i.e., the input is expected to be
`[batch_size, num_channels] + input_spatial_shape`
or `[batch_size] + input_spatial_shape + [num_channels]`.
Returns:
A tensor of shape and dtype matching that of `input`.
Raises:
ValueError: If input and filter both have unknown shapes, or if
`num_spatial_dims` is provided and incompatible with the value
estimated from `filters.shape`. | Internal function which performs rank agnostic convolution. | [
"Internal",
"function",
"which",
"performs",
"rank",
"agnostic",
"convolution",
"."
] | def convolution_internal(
input, # pylint: disable=redefined-builtin
filters,
strides=None,
padding="VALID",
data_format=None,
dilations=None,
name=None,
call_from_convolution=True,
num_spatial_dims=None):
"""Internal function which performs rank agnostic convolution.
Args:
input: See `convolution`.
filters: See `convolution`.
strides: See `convolution`.
padding: See `convolution`.
data_format: See `convolution`.
dilations: See `convolution`.
name: See `convolution`.
call_from_convolution: See `convolution`.
num_spatial_dims: (Optional.). It is a integer describing the
rank of the spatial dimensions. For `1-D`, `2-D` and `3-D` convolutions,
the value of `num_spatial_dims` is `1`, `2`, and `3`, respectively.
This argument is only required to disambiguate the rank of `batch_shape`
when `filter_shape.ndims is None` and `len(batch_shape) > 1`. For
backwards compatibility, if `num_spatial_dims is None` and
`filter_shape.ndims is None`, then `len(batch_shape)` is assumed to be
`1` (i.e., the input is expected to be
`[batch_size, num_channels] + input_spatial_shape`
or `[batch_size] + input_spatial_shape + [num_channels]`.
Returns:
A tensor of shape and dtype matching that of `input`.
Raises:
ValueError: If input and filter both have unknown shapes, or if
`num_spatial_dims` is provided and incompatible with the value
estimated from `filters.shape`.
"""
if (not isinstance(filters, variables_lib.Variable) and
not tensor_util.is_tf_type(filters)):
with ops.name_scope("convolution_internal", None, [filters, input]):
filters = ops.convert_to_tensor(filters, name='filters')
if (not isinstance(input, ops.Tensor) and not tensor_util.is_tf_type(input)):
with ops.name_scope("convolution_internal", None, [filters, input]):
input = ops.convert_to_tensor(input, name="input")
filters_rank = filters.shape.rank
inputs_rank = input.shape.rank
if num_spatial_dims is None:
if filters_rank:
num_spatial_dims = filters_rank - 2
elif inputs_rank:
num_spatial_dims = inputs_rank - 2
else:
raise ValueError(
"When `num_spatial_dims` is not set, one of `input.shape.rank` or "
"`filters.shape.rank` must be known. "
f"Received: input.shape={input.shape} of rank {inputs_rank} and "
f"filters.shape={filters.shape} of rank {filters_rank}")
elif filters_rank and filters_rank - 2 != num_spatial_dims:
raise ValueError(
"`filters.shape.rank - 2` should equal `num_spatial_dims`. Received: "
f"filters.shape={filters.shape} of rank {filters_rank} and "
f"num_spatial_dims={num_spatial_dims}")
if inputs_rank:
num_batch_dims = inputs_rank - num_spatial_dims - 1 # Channel dimension.
else:
num_batch_dims = 1 # By default, assume single batch dimension.
if num_spatial_dims not in {1, 2, 3}:
raise ValueError(
"`num_spatial_dims` must be 1, 2, or 3. "
f"Received: num_spatial_dims={num_spatial_dims}.")
if data_format is None or data_format in _CHANNELS_LAST_FORMATS:
channel_index = num_batch_dims + num_spatial_dims
else:
channel_index = num_batch_dims
if dilations is None:
dilations = _get_sequence(dilations, num_spatial_dims, channel_index,
"dilations")
is_dilated_conv = False
else:
dilations = _get_sequence(dilations, num_spatial_dims, channel_index,
"dilations")
is_dilated_conv = any(i != 1 for i in dilations)
strides = _get_sequence(strides, num_spatial_dims, channel_index, "strides")
has_tpu_context = device_context.enclosing_tpu_context() is not None
if name:
default_name = None
elif not has_tpu_context or call_from_convolution:
default_name = "convolution"
elif num_spatial_dims == 2: # Most common case.
default_name = "Conv2D"
elif num_spatial_dims == 3:
default_name = "Conv3D"
else:
default_name = "conv1d"
with ops.name_scope(name, default_name, [input, filters]) as name:
# Fast path for TPU or if no dilation, as gradient only supported on TPU
# for dilations.
if not is_dilated_conv or has_tpu_context:
if num_spatial_dims == 2: # Most common case.
op = _conv2d_expanded_batch
elif num_spatial_dims == 3:
op = _conv3d_expanded_batch
else:
op = conv1d
return op(
input,
filters,
strides,
padding=padding,
data_format=data_format,
dilations=dilations,
name=name)
else:
if channel_index == 1:
strides = strides[2:]
dilations = dilations[2:]
else:
strides = strides[1:-1]
dilations = dilations[1:-1]
op = Convolution(
tensor_shape.as_shape(input.shape),
tensor_shape.as_shape(filters.shape),
padding,
strides=strides,
dilation_rate=dilations,
name=name,
data_format=data_format,
num_spatial_dims=num_spatial_dims)
return op(input, filters) | [
"def",
"convolution_internal",
"(",
"input",
",",
"# pylint: disable=redefined-builtin",
"filters",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"\"VALID\"",
",",
"data_format",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"name",
"=",
"None",
",",
"c... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/nn_ops.py#L1166-L1307 | ||
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | beyond/src/gcs.py | python | GCS.__sign_url | (self,
bucket,
path,
expiration,
method,
content_type = None,
content_length = None,
headers = {},
) | return url | `path` will be url-encoded, don't do it. | `path` will be url-encoded, don't do it. | [
"path",
"will",
"be",
"url",
"-",
"encoded",
"don",
"t",
"do",
"it",
"."
] | def __sign_url(self,
bucket,
path,
expiration,
method,
content_type = None,
content_length = None,
headers = {},
):
'''`path` will be url-encoded, don't do it.'''
expiration = datetime.datetime.now() + expiration
expiration = int(time.mktime(expiration.timetuple()))
path = urllib.parse.quote(path)
chunks = []
chunks.append(method)
chunks.append('') # MD5, optional
chunks.append(content_type or '')
for k, v in headers.items():
chunks.append('%s:%s' % (k, v))
chunks.append(str(expiration))
chunks.append('/%s/%s' % (self.__bucket(bucket), path))
signature_string = '\n'.join(chunks)
shahash = SHA256.new(signature_string.encode('utf-8'))
private_key = RSA.importKey(self.__key, passphrase='notasecret')
signer = PKCS1_v1_5.new(private_key)
signature_bytes = signer.sign(shahash)
sig = base64.b64encode(signature_bytes)
params = {
'GoogleAccessId': self.__login,
'Expires': str(expiration),
'Signature': sig
}
params = urllib.parse.urlencode(params)
url = 'https://%s.%s/%s?%s' % (self.__bucket(bucket), GCS.host,
path, params)
return url | [
"def",
"__sign_url",
"(",
"self",
",",
"bucket",
",",
"path",
",",
"expiration",
",",
"method",
",",
"content_type",
"=",
"None",
",",
"content_length",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
",",
")",
":",
"expiration",
"=",
"datetime",
".",
"dat... | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/beyond/src/gcs.py#L61-L96 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/commands/fib.py | python | FibSnoopCmd.print_route_db_delta | (
self,
delta_db: Union[
openr_types.RouteDatabaseDelta,
openr_types_py3.RouteDatabaseDelta,
],
prefixes: Optional[List[str]] = None,
) | print the RouteDatabaseDelta from Fib module | print the RouteDatabaseDelta from Fib module | [
"print",
"the",
"RouteDatabaseDelta",
"from",
"Fib",
"module"
] | def print_route_db_delta(
self,
delta_db: Union[
openr_types.RouteDatabaseDelta,
openr_types_py3.RouteDatabaseDelta,
],
prefixes: Optional[List[str]] = None,
) -> None:
"""print the RouteDatabaseDelta from Fib module"""
if len(delta_db.unicastRoutesToUpdate) != 0:
utils.print_unicast_routes(
caption="",
unicast_routes=delta_db.unicastRoutesToUpdate,
prefixes=prefixes,
element_prefix="+",
filter_exact_match=True,
timestamp=True,
)
if len(delta_db.unicastRoutesToDelete) != 0:
self.print_ip_prefixes_filtered(
ip_prefixes=delta_db.unicastRoutesToDelete,
prefixes_filter=prefixes,
element_prefix="-",
)
if prefixes:
return
if len(delta_db.mplsRoutesToUpdate) != 0:
utils.print_mpls_routes(
caption="",
mpls_routes=delta_db.mplsRoutesToUpdate,
element_prefix="+",
element_suffix="(MPLS)",
timestamp=True,
)
if len(delta_db.mplsRoutesToDelete) != 0:
self.print_mpls_labels(
labels=delta_db.mplsRoutesToDelete,
element_prefix="-",
element_suffix="(MPLS)",
) | [
"def",
"print_route_db_delta",
"(",
"self",
",",
"delta_db",
":",
"Union",
"[",
"openr_types",
".",
"RouteDatabaseDelta",
",",
"openr_types_py3",
".",
"RouteDatabaseDelta",
",",
"]",
",",
"prefixes",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"... | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/commands/fib.py#L362-L404 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/message.py | python | MIMEPart.iter_parts | (self) | Return an iterator over all immediate subparts of a multipart.
Return an empty iterator for a non-multipart. | Return an iterator over all immediate subparts of a multipart. | [
"Return",
"an",
"iterator",
"over",
"all",
"immediate",
"subparts",
"of",
"a",
"multipart",
"."
] | def iter_parts(self):
"""Return an iterator over all immediate subparts of a multipart.
Return an empty iterator for a non-multipart.
"""
if self.get_content_maintype() == 'multipart':
yield from self.get_payload() | [
"def",
"iter_parts",
"(",
"self",
")",
":",
"if",
"self",
".",
"get_content_maintype",
"(",
")",
"==",
"'multipart'",
":",
"yield",
"from",
"self",
".",
"get_payload",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/message.py#L1085-L1091 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/mms/runner.py | python | run_temporal | (*args, **kwargs) | return _runner(*args, rtype=TEMPORAL, **kwargs) | Runs input file for a temporal MMS problem (see _runner.py for inputs). | Runs input file for a temporal MMS problem (see _runner.py for inputs). | [
"Runs",
"input",
"file",
"for",
"a",
"temporal",
"MMS",
"problem",
"(",
"see",
"_runner",
".",
"py",
"for",
"inputs",
")",
"."
] | def run_temporal(*args, **kwargs):
"""Runs input file for a temporal MMS problem (see _runner.py for inputs)."""
return _runner(*args, rtype=TEMPORAL, **kwargs) | [
"def",
"run_temporal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_runner",
"(",
"*",
"args",
",",
"rtype",
"=",
"TEMPORAL",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mms/runner.py#L135-L137 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/depot_tools/cpplint.py | python | CheckHeaderFileIncluded | (filename, include_state, error) | Logs an error if a .cc file does not include its header. | Logs an error if a .cc file does not include its header. | [
"Logs",
"an",
"error",
"if",
"a",
".",
"cc",
"file",
"does",
"not",
"include",
"its",
"header",
"."
] | def CheckHeaderFileIncluded(filename, include_state, error):
"""Logs an error if a .cc file does not include its header."""
# Do not check test files
fileinfo = FileInfo(filename)
if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
return
headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
if not os.path.exists(headerfile):
return
headername = FileInfo(headerfile).RepositoryName()
first_include = 0
for section_list in include_state.include_list:
for f in section_list:
if headername in f[0] or f[0] in headername:
return
if not first_include:
first_include = f[1]
error(filename, first_include, 'build/include', 5,
'%s should include its header file %s' % (fileinfo.RepositoryName(),
headername)) | [
"def",
"CheckHeaderFileIncluded",
"(",
"filename",
",",
"include_state",
",",
"error",
")",
":",
"# Do not check test files",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"if",
"Search",
"(",
"_TEST_FILE_SUFFIX",
",",
"fileinfo",
".",
"BaseName",
"(",
")",
... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L1862-L1884 | ||
cksystemsgroup/scal | fa2208a97a77d65f4e90f85fef3404c27c1f2ac2 | tools/cpplint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/cksystemsgroup/scal/blob/fa2208a97a77d65f4e90f85fef3404c27c1f2ac2/tools/cpplint.py#L851-L853 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/transaction.py | python | Transaction.complete | (self, commit=True) | Finish transaction: commit or discard all deferred files | Finish transaction: commit or discard all deferred files | [
"Finish",
"transaction",
":",
"commit",
"or",
"discard",
"all",
"deferred",
"files"
] | def complete(self, commit=True):
"""Finish transaction: commit or discard all deferred files"""
for f in self.files:
if commit:
f.commit()
else:
f.discard()
self.files = []
self.fs._intrans = False | [
"def",
"complete",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"for",
"f",
"in",
"self",
".",
"files",
":",
"if",
"commit",
":",
"f",
".",
"commit",
"(",
")",
"else",
":",
"f",
".",
"discard",
"(",
")",
"self",
".",
"files",
"=",
"[",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/transaction.py#L33-L41 | ||
cvmfs/cvmfs | 4637bdb5153178eadf885c1acf37bdc5c685bf8a | cpplint.py | python | ResetNolintSuppressions | () | Resets the set of NOLINT suppressions to empty. | Resets the set of NOLINT suppressions to empty. | [
"Resets",
"the",
"set",
"of",
"NOLINT",
"suppressions",
"to",
"empty",
"."
] | def ResetNolintSuppressions():
"""Resets the set of NOLINT suppressions to empty."""
_error_suppressions.clear() | [
"def",
"ResetNolintSuppressions",
"(",
")",
":",
"_error_suppressions",
".",
"clear",
"(",
")"
] | https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L536-L538 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py | python | BlobstoreLineInputReader.to_json | (self) | return {self.BLOB_KEY_PARAM: self._blob_key,
self.INITIAL_POSITION_PARAM: new_pos,
self.END_POSITION_PARAM: self._end_position} | Returns an json-compatible input shard spec for remaining inputs. | Returns an json-compatible input shard spec for remaining inputs. | [
"Returns",
"an",
"json",
"-",
"compatible",
"input",
"shard",
"spec",
"for",
"remaining",
"inputs",
"."
] | def to_json(self):
"""Returns an json-compatible input shard spec for remaining inputs."""
new_pos = self._blob_reader.tell()
if self._has_iterated:
new_pos -= 1
return {self.BLOB_KEY_PARAM: self._blob_key,
self.INITIAL_POSITION_PARAM: new_pos,
self.END_POSITION_PARAM: self._end_position} | [
"def",
"to_json",
"(",
"self",
")",
":",
"new_pos",
"=",
"self",
".",
"_blob_reader",
".",
"tell",
"(",
")",
"if",
"self",
".",
"_has_iterated",
":",
"new_pos",
"-=",
"1",
"return",
"{",
"self",
".",
"BLOB_KEY_PARAM",
":",
"self",
".",
"_blob_key",
","... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py#L1346-L1353 | |
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/wire_format.py | python | _VarUInt64ByteSizeNoTag | (uint64) | return 10 | Returns the number of bytes required to serialize a single varint
using boundary value comparisons. (unrolled loop optimization -WPierce)
uint64 must be unsigned. | Returns the number of bytes required to serialize a single varint
using boundary value comparisons. (unrolled loop optimization -WPierce)
uint64 must be unsigned. | [
"Returns",
"the",
"number",
"of",
"bytes",
"required",
"to",
"serialize",
"a",
"single",
"varint",
"using",
"boundary",
"value",
"comparisons",
".",
"(",
"unrolled",
"loop",
"optimization",
"-",
"WPierce",
")",
"uint64",
"must",
"be",
"unsigned",
"."
] | def _VarUInt64ByteSizeNoTag(uint64):
"""Returns the number of bytes required to serialize a single varint
using boundary value comparisons. (unrolled loop optimization -WPierce)
uint64 must be unsigned.
"""
if uint64 <= 0x7f: return 1
if uint64 <= 0x3fff: return 2
if uint64 <= 0x1fffff: return 3
if uint64 <= 0xfffffff: return 4
if uint64 <= 0x7ffffffff: return 5
if uint64 <= 0x3ffffffffff: return 6
if uint64 <= 0x1ffffffffffff: return 7
if uint64 <= 0xffffffffffffff: return 8
if uint64 <= 0x7fffffffffffffff: return 9
if uint64 > UINT64_MAX:
raise message.EncodeError('Value out of range: %d' % uint64)
return 10 | [
"def",
"_VarUInt64ByteSizeNoTag",
"(",
"uint64",
")",
":",
"if",
"uint64",
"<=",
"0x7f",
":",
"return",
"1",
"if",
"uint64",
"<=",
"0x3fff",
":",
"return",
"2",
"if",
"uint64",
"<=",
"0x1fffff",
":",
"return",
"3",
"if",
"uint64",
"<=",
"0xfffffff",
":",... | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/wire_format.py#L232-L248 | |
luca-m/emotime | 643a5c09144b515a102942a178a3b7ce0e2cdc92 | src/dataset/datasetTrain.py | python | _subproc_call | (args) | Wrap a subprocess.call | Wrap a subprocess.call | [
"Wrap",
"a",
"subprocess",
".",
"call"
] | def _subproc_call(args):
""" Wrap a subprocess.call """
param, comstr = args
retcode=subprocess.call( param, shell=False )
#comstr=' '.join(param)
if retcode==0:
print("INFO: done %s"%comstr)
return (comstr,True)
else:
print("ERR: '%s' has encountered problems" % comstr)
return (comstr,False) | [
"def",
"_subproc_call",
"(",
"args",
")",
":",
"param",
",",
"comstr",
"=",
"args",
"retcode",
"=",
"subprocess",
".",
"call",
"(",
"param",
",",
"shell",
"=",
"False",
")",
"#comstr=' '.join(param)",
"if",
"retcode",
"==",
"0",
":",
"print",
"(",
"\"INF... | https://github.com/luca-m/emotime/blob/643a5c09144b515a102942a178a3b7ce0e2cdc92/src/dataset/datasetTrain.py#L15-L25 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/backports.functools-lru-cache/functools_lru_cache.py | python | update_wrapper | (wrapper,
wrapped,
assigned = functools.WRAPPER_ASSIGNMENTS,
updated = functools.WRAPPER_UPDATES) | return wrapper | Patch two bugs in functools.update_wrapper. | Patch two bugs in functools.update_wrapper. | [
"Patch",
"two",
"bugs",
"in",
"functools",
".",
"update_wrapper",
"."
] | def update_wrapper(wrapper,
wrapped,
assigned = functools.WRAPPER_ASSIGNMENTS,
updated = functools.WRAPPER_UPDATES):
"""
Patch two bugs in functools.update_wrapper.
"""
# workaround for http://bugs.python.org/issue3445
assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))
wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)
# workaround for https://bugs.python.org/issue17482
wrapper.__wrapped__ = wrapped
return wrapper | [
"def",
"update_wrapper",
"(",
"wrapper",
",",
"wrapped",
",",
"assigned",
"=",
"functools",
".",
"WRAPPER_ASSIGNMENTS",
",",
"updated",
"=",
"functools",
".",
"WRAPPER_UPDATES",
")",
":",
"# workaround for http://bugs.python.org/issue3445",
"assigned",
"=",
"tuple",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/backports.functools-lru-cache/functools_lru_cache.py#L11-L23 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py | python | MacPrefixHeader.GetPchBuildCommands | (self) | return [
(self._Gch('c'), '-x c-header', 'c', self.header),
(self._Gch('cc'), '-x c++-header', 'cc', self.header),
(self._Gch('m'), '-x objective-c-header', 'm', self.header),
(self._Gch('mm'), '-x objective-c++-header', 'mm', self.header),
] | Returns [(path_to_gch, language_flag, language, header)].
|path_to_gch| and |header| are relative to the build directory. | Returns [(path_to_gch, language_flag, language, header)].
|path_to_gch| and |header| are relative to the build directory. | [
"Returns",
"[",
"(",
"path_to_gch",
"language_flag",
"language",
"header",
")",
"]",
".",
"|path_to_gch|",
"and",
"|header|",
"are",
"relative",
"to",
"the",
"build",
"directory",
"."
] | def GetPchBuildCommands(self):
"""Returns [(path_to_gch, language_flag, language, header)].
|path_to_gch| and |header| are relative to the build directory.
"""
if not self.header or not self.compile_headers:
return []
return [
(self._Gch('c'), '-x c-header', 'c', self.header),
(self._Gch('cc'), '-x c++-header', 'cc', self.header),
(self._Gch('m'), '-x objective-c-header', 'm', self.header),
(self._Gch('mm'), '-x objective-c++-header', 'mm', self.header),
] | [
"def",
"GetPchBuildCommands",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"header",
"or",
"not",
"self",
".",
"compile_headers",
":",
"return",
"[",
"]",
"return",
"[",
"(",
"self",
".",
"_Gch",
"(",
"'c'",
")",
",",
"'-x c-header'",
",",
"'c'",
... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py#L780-L791 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/nvm.py | python | NvmAccessProvider.stop | (self) | Stop (deactivate) session | Stop (deactivate) session | [
"Stop",
"(",
"deactivate",
")",
"session"
] | def stop(self):
"""
Stop (deactivate) session
"""
self.logger.info("No specific de-initializer for this provider") | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"No specific de-initializer for this provider\"",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvm.py#L97-L101 | ||
daijifeng001/caffe-rfcn | 543f8f6a4b7c88256ea1445ae951a12d1ad9cffd | scripts/cpp_lint.py | python | _NestingState.UpdatePreprocessor | (self, line) | Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check. | Update preprocessor stack. | [
"Update",
"preprocessor",
"stack",
"."
] | def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass | [
"def",
"UpdatePreprocessor",
"(",
"self",
",",
"line",
")",
":",
"if",
"Match",
"(",
"r'^\\s*#\\s*(if|ifdef|ifndef)\\b'",
",",
"line",
")",
":",
"# Beginning of #if block, save the nesting stack here. The saved",
"# stack will allow us to restore the parsing state in the #else cas... | https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/scripts/cpp_lint.py#L1948-L2002 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/markupsafe/_native.py | python | escape_silent | (s) | return escape(s) | Like :func:`escape` but converts `None` into an empty
markup string. | Like :func:`escape` but converts `None` into an empty
markup string. | [
"Like",
":",
"func",
":",
"escape",
"but",
"converts",
"None",
"into",
"an",
"empty",
"markup",
"string",
"."
] | def escape_silent(s):
"""Like :func:`escape` but converts `None` into an empty
markup string.
"""
if s is None:
return Markup()
return escape(s) | [
"def",
"escape_silent",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"Markup",
"(",
")",
"return",
"escape",
"(",
"s",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/markupsafe/_native.py#L31-L37 | |
martinmoene/expected-lite | 6284387cb117ea78d973fb5b1cbff1651a8d5d9a | script/upload-conan.py | python | uploadToConanFromCommandLine | () | Collect arguments from the commandline and create conan package and upload it. | Collect arguments from the commandline and create conan package and upload it. | [
"Collect",
"arguments",
"from",
"the",
"commandline",
"and",
"create",
"conan",
"package",
"and",
"upload",
"it",
"."
] | def uploadToConanFromCommandLine():
"""Collect arguments from the commandline and create conan package and upload it."""
parser = argparse.ArgumentParser(
description='Create conan package and upload it to conan.',
epilog="""""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-n', '--dry-run',
action='store_true',
help='do not execute conan commands')
parser.add_argument(
'-v', '--verbose',
action='count',
default=0,
help='level of progress reporting')
parser.add_argument(
'--project',
metavar='p',
type=str,
default=def_conan_project,
help='conan project')
parser.add_argument(
'--user',
metavar='u',
type=str,
default=def_conan_user,
help='conan user')
parser.add_argument(
'--channel',
metavar='c',
type=str,
default=def_conan_channel,
help='conan channel')
parser.add_argument(
'--version',
metavar='v',
type=str,
default=versionFrom( cfg_conanfile ),
help='version number [from conanfile.py]')
uploadToConan( parser.parse_args() ) | [
"def",
"uploadToConanFromCommandLine",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Create conan package and upload it to conan.'",
",",
"epilog",
"=",
"\"\"\"\"\"\"",
",",
"formatter_class",
"=",
"argparse",
".",
"Argument... | https://github.com/martinmoene/expected-lite/blob/6284387cb117ea78d973fb5b1cbff1651a8d5d9a/script/upload-conan.py#L61-L108 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/filter_design.py | python | _align_nums | (nums) | Aligns the shapes of multiple numerators.
Given an array of numerator coefficient arrays [[a_1, a_2,...,
a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator
arrays with zero's so that all numerators have the same length. Such
alignment is necessary for functions like 'tf2ss', which needs the
alignment when dealing with SIMO transfer functions.
Parameters
----------
nums: array_like
Numerator or list of numerators. Not necessarily with same length.
Returns
-------
nums: array
The numerator. If `nums` input was a list of numerators then a 2d
array with padded zeros for shorter numerators is returned. Otherwise
returns ``np.asarray(nums)``. | Aligns the shapes of multiple numerators. | [
"Aligns",
"the",
"shapes",
"of",
"multiple",
"numerators",
"."
] | def _align_nums(nums):
"""Aligns the shapes of multiple numerators.
Given an array of numerator coefficient arrays [[a_1, a_2,...,
a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator
arrays with zero's so that all numerators have the same length. Such
alignment is necessary for functions like 'tf2ss', which needs the
alignment when dealing with SIMO transfer functions.
Parameters
----------
nums: array_like
Numerator or list of numerators. Not necessarily with same length.
Returns
-------
nums: array
The numerator. If `nums` input was a list of numerators then a 2d
array with padded zeros for shorter numerators is returned. Otherwise
returns ``np.asarray(nums)``.
"""
try:
# The statement can throw a ValueError if one
# of the numerators is a single digit and another
# is array-like e.g. if nums = [5, [1, 2, 3]]
nums = asarray(nums)
if not np.issubdtype(nums.dtype, np.number):
raise ValueError("dtype of numerator is non-numeric")
return nums
except ValueError:
nums = [np.atleast_1d(num) for num in nums]
max_width = max(num.size for num in nums)
# pre-allocate
aligned_nums = np.zeros((len(nums), max_width))
# Create numerators with padded zeros
for index, num in enumerate(nums):
aligned_nums[index, -num.size:] = num
return aligned_nums | [
"def",
"_align_nums",
"(",
"nums",
")",
":",
"try",
":",
"# The statement can throw a ValueError if one",
"# of the numerators is a single digit and another",
"# is array-like e.g. if nums = [5, [1, 2, 3]]",
"nums",
"=",
"asarray",
"(",
"nums",
")",
"if",
"not",
"np",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/filter_design.py#L1515-L1558 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_session.py | python | SessionManager.DeleteSession | (self, name) | return rval | Delete the specified session name
@param name: session name
@return: bool | Delete the specified session name
@param name: session name
@return: bool | [
"Delete",
"the",
"specified",
"session",
"name",
"@param",
"name",
":",
"session",
"name",
"@return",
":",
"bool"
] | def DeleteSession(self, name):
"""Delete the specified session name
@param name: session name
@return: bool
"""
rval = True
session = self.PathFromSessionName(name)
if os.path.exists(session):
try:
os.remove(session)
except OSError:
rval = False
return rval | [
"def",
"DeleteSession",
"(",
"self",
",",
"name",
")",
":",
"rval",
"=",
"True",
"session",
"=",
"self",
".",
"PathFromSessionName",
"(",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"session",
")",
":",
"try",
":",
"os",
".",
"remove",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_session.py#L64-L77 | |
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor.py | python | EnumDescriptor.CopyToProto | (self, proto) | Copies this to a descriptor_pb2.EnumDescriptorProto.
Args:
proto: An empty descriptor_pb2.EnumDescriptorProto. | Copies this to a descriptor_pb2.EnumDescriptorProto. | [
"Copies",
"this",
"to",
"a",
"descriptor_pb2",
".",
"EnumDescriptorProto",
"."
] | def CopyToProto(self, proto):
"""Copies this to a descriptor_pb2.EnumDescriptorProto.
Args:
proto: An empty descriptor_pb2.EnumDescriptorProto.
"""
# This function is overridden to give a better doc comment.
super(EnumDescriptor, self).CopyToProto(proto) | [
"def",
"CopyToProto",
"(",
"self",
",",
"proto",
")",
":",
"# This function is overridden to give a better doc comment.",
"super",
"(",
"EnumDescriptor",
",",
"self",
")",
".",
"CopyToProto",
"(",
"proto",
")"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor.py#L623-L630 | ||
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | python/caffe/detector.py | python | Detector.detect_windows | (self, images_windows) | return detections | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts. | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net. | [
"Do",
"windowed",
"detection",
"over",
"given",
"images",
"and",
"windows",
".",
"Windows",
"are",
"extracted",
"then",
"warped",
"to",
"the",
"input",
"dimensions",
"of",
"the",
"net",
"."
] | def detect_windows(self, images_windows):
"""
Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts.
"""
# Extract windows.
window_inputs = []
for image_fname, windows in images_windows:
image = caffe.io.load_image(image_fname).astype(np.float32)
for window in windows:
window_inputs.append(self.crop(image, window))
# Run through the net (warping windows to input dimensions).
in_ = self.inputs[0]
caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2])
+ self.blobs[in_].data.shape[2:],
dtype=np.float32)
for ix, window_in in enumerate(window_inputs):
caffe_in[ix] = self.transformer.preprocess(in_, window_in)
out = self.forward_all(**{in_: caffe_in})
predictions = out[self.outputs[0]]
# Package predictions with images and windows.
detections = []
ix = 0
for image_fname, windows in images_windows:
for window in windows:
detections.append({
'window': window,
'prediction': predictions[ix],
'filename': image_fname
})
ix += 1
return detections | [
"def",
"detect_windows",
"(",
"self",
",",
"images_windows",
")",
":",
"# Extract windows.",
"window_inputs",
"=",
"[",
"]",
"for",
"image_fname",
",",
"windows",
"in",
"images_windows",
":",
"image",
"=",
"caffe",
".",
"io",
".",
"load_image",
"(",
"image_fna... | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/python/caffe/detector.py#L56-L99 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | IKSolver.getMaxIters | (self) | return _robotsim.IKSolver_getMaxIters(self) | r"""
getMaxIters(IKSolver self) -> int
Returns the max # of iterations. | r"""
getMaxIters(IKSolver self) -> int | [
"r",
"getMaxIters",
"(",
"IKSolver",
"self",
")",
"-",
">",
"int"
] | def getMaxIters(self) -> "int":
r"""
getMaxIters(IKSolver self) -> int
Returns the max # of iterations.
"""
return _robotsim.IKSolver_getMaxIters(self) | [
"def",
"getMaxIters",
"(",
"self",
")",
"->",
"\"int\"",
":",
"return",
"_robotsim",
".",
"IKSolver_getMaxIters",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L6719-L6727 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py | python | Misc.option_add | (self, pattern, value, priority = None) | Set a VALUE (second parameter) for an option
PATTERN (first parameter).
An optional third parameter gives the numeric priority
(defaults to 80). | Set a VALUE (second parameter) for an option
PATTERN (first parameter). | [
"Set",
"a",
"VALUE",
"(",
"second",
"parameter",
")",
"for",
"an",
"option",
"PATTERN",
"(",
"first",
"parameter",
")",
"."
] | def option_add(self, pattern, value, priority = None):
"""Set a VALUE (second parameter) for an option
PATTERN (first parameter).
An optional third parameter gives the numeric priority
(defaults to 80)."""
self.tk.call('option', 'add', pattern, value, priority) | [
"def",
"option_add",
"(",
"self",
",",
"pattern",
",",
"value",
",",
"priority",
"=",
"None",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'option'",
",",
"'add'",
",",
"pattern",
",",
"value",
",",
"priority",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L854-L860 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Misc.winfo_pointerxy | (self) | return self._getints(
self.tk.call('winfo', 'pointerxy', self._w)) | Return a tuple of x and y coordinates of the pointer on the root window. | Return a tuple of x and y coordinates of the pointer on the root window. | [
"Return",
"a",
"tuple",
"of",
"x",
"and",
"y",
"coordinates",
"of",
"the",
"pointer",
"on",
"the",
"root",
"window",
"."
] | def winfo_pointerxy(self):
"""Return a tuple of x and y coordinates of the pointer on the root window."""
return self._getints(
self.tk.call('winfo', 'pointerxy', self._w)) | [
"def",
"winfo_pointerxy",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'pointerxy'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L884-L887 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | UpdateUIEvent.SetMode | (*args, **kwargs) | return _core_.UpdateUIEvent_SetMode(*args, **kwargs) | SetMode(int mode)
Specify how wxWidgets will send update events: to all windows, or only
to those which specify that they will process the events.
The mode may be one of the following values:
============================= ==========================================
wxUPDATE_UI_PROCESS_ALL Send UI update events to all windows. This
is the default setting.
wxUPDATE_UI_PROCESS_SPECIFIED Send UI update events only to windows that
have the wx.WS_EX_PROCESS_UI_UPDATES extra
style set.
============================= ========================================== | SetMode(int mode) | [
"SetMode",
"(",
"int",
"mode",
")"
] | def SetMode(*args, **kwargs):
"""
SetMode(int mode)
Specify how wxWidgets will send update events: to all windows, or only
to those which specify that they will process the events.
The mode may be one of the following values:
============================= ==========================================
wxUPDATE_UI_PROCESS_ALL Send UI update events to all windows. This
is the default setting.
wxUPDATE_UI_PROCESS_SPECIFIED Send UI update events only to windows that
have the wx.WS_EX_PROCESS_UI_UPDATES extra
style set.
============================= ==========================================
"""
return _core_.UpdateUIEvent_SetMode(*args, **kwargs) | [
"def",
"SetMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"UpdateUIEvent_SetMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L6908-L6926 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang-tools-extra/clangd/quality/CompletionModelCodegen.py | python | gen_cpp_code | (forest_json, features_json, filename, cpp_class) | return """%s
%s
#define BIT(X) (1 << X)
%s
%s
uint32_t %s::OrderEncode(float F) {
static_assert(std::numeric_limits<float>::is_iec559, "");
constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
// Get the bits of the float. Endianness is the same as for integers.
uint32_t U = llvm::bit_cast<uint32_t>(F);
std::memcpy(&U, &F, sizeof(U));
// IEEE 754 floats compare like sign-magnitude integers.
if (U & TopBit) // Negative float.
return 0 - U; // Map onto the low half of integers, order reversed.
return U + TopBit; // Positive floats map onto the high half of integers.
}
%s
%s
""" % (nl.join(angled_include), nl.join(quoted_include), cpp_class.ns_begin(),
using_decls, cpp_class.name, evaluate_func(forest_json, cpp_class),
cpp_class.ns_end()) | Generates code for the .cpp file. | Generates code for the .cpp file. | [
"Generates",
"code",
"for",
"the",
".",
"cpp",
"file",
"."
] | def gen_cpp_code(forest_json, features_json, filename, cpp_class):
"""Generates code for the .cpp file."""
# Headers
# Required by OrderEncode(float F).
angled_include = [
'#include <%s>' % h
for h in ["cstring", "limits"]
]
# Include generated header.
qouted_headers = {filename + '.h', 'llvm/ADT/bit.h'}
# Headers required by ENUM features used by the model.
qouted_headers |= {f["header"]
for f in features_json if f["kind"] == "ENUM"}
quoted_include = ['#include "%s"' % h for h in sorted(qouted_headers)]
# using-decl for ENUM features.
using_decls = "\n".join("using %s_type = %s;" % (
feature['name'], feature['type'])
for feature in features_json
if feature["kind"] == "ENUM")
nl = "\n"
return """%s
%s
#define BIT(X) (1 << X)
%s
%s
uint32_t %s::OrderEncode(float F) {
static_assert(std::numeric_limits<float>::is_iec559, "");
constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
// Get the bits of the float. Endianness is the same as for integers.
uint32_t U = llvm::bit_cast<uint32_t>(F);
std::memcpy(&U, &F, sizeof(U));
// IEEE 754 floats compare like sign-magnitude integers.
if (U & TopBit) // Negative float.
return 0 - U; // Map onto the low half of integers, order reversed.
return U + TopBit; // Positive floats map onto the high half of integers.
}
%s
%s
""" % (nl.join(angled_include), nl.join(quoted_include), cpp_class.ns_begin(),
using_decls, cpp_class.name, evaluate_func(forest_json, cpp_class),
cpp_class.ns_end()) | [
"def",
"gen_cpp_code",
"(",
"forest_json",
",",
"features_json",
",",
"filename",
",",
"cpp_class",
")",
":",
"# Headers",
"# Required by OrderEncode(float F).",
"angled_include",
"=",
"[",
"'#include <%s>'",
"%",
"h",
"for",
"h",
"in",
"[",
"\"cstring\"",
",",
"\... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang-tools-extra/clangd/quality/CompletionModelCodegen.py#L222-L271 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py | python | BufferedIOBase.detach | (self) | Separate the underlying raw stream from the buffer and return it.
After the raw stream has been detached, the buffer is in an unusable
state. | Separate the underlying raw stream from the buffer and return it. | [
"Separate",
"the",
"underlying",
"raw",
"stream",
"from",
"the",
"buffer",
"and",
"return",
"it",
"."
] | def detach(self):
"""
Separate the underlying raw stream from the buffer and return it.
After the raw stream has been detached, the buffer is in an unusable
state.
"""
self._unsupported("detach") | [
"def",
"detach",
"(",
"self",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"detach\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py#L721-L728 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_stc.py | python | EditraStc.ShowFindBar | (self) | Open the quick-find bar | Open the quick-find bar | [
"Open",
"the",
"quick",
"-",
"find",
"bar"
] | def ShowFindBar(self):
"""Open the quick-find bar"""
self.TopLevelParent.GetEditPane().ShowCommandControl(ed_glob.ID_QUICK_FIND) | [
"def",
"ShowFindBar",
"(",
"self",
")",
":",
"self",
".",
"TopLevelParent",
".",
"GetEditPane",
"(",
")",
".",
"ShowCommandControl",
"(",
"ed_glob",
".",
"ID_QUICK_FIND",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L338-L340 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py | python | BarChartEncoder._GetAxisLabelsAndPositions | (self, axis, chart) | return axis.labels, axis.label_positions | Reverse labels on the y-axis in horizontal bar charts.
(Otherwise the labels come out backwards from what you would expect) | Reverse labels on the y-axis in horizontal bar charts.
(Otherwise the labels come out backwards from what you would expect) | [
"Reverse",
"labels",
"on",
"the",
"y",
"-",
"axis",
"in",
"horizontal",
"bar",
"charts",
".",
"(",
"Otherwise",
"the",
"labels",
"come",
"out",
"backwards",
"from",
"what",
"you",
"would",
"expect",
")"
] | def _GetAxisLabelsAndPositions(self, axis, chart):
"""Reverse labels on the y-axis in horizontal bar charts.
(Otherwise the labels come out backwards from what you would expect)
"""
if not chart.vertical and axis == chart.left:
# The left axis of horizontal bar charts needs to have reversed labels
return reversed(axis.labels), reversed(axis.label_positions)
return axis.labels, axis.label_positions | [
"def",
"_GetAxisLabelsAndPositions",
"(",
"self",
",",
"axis",
",",
"chart",
")",
":",
"if",
"not",
"chart",
".",
"vertical",
"and",
"axis",
"==",
"chart",
".",
"left",
":",
"# The left axis of horizontal bar charts needs to have reversed labels",
"return",
"reversed"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py#L273-L280 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextParagraphLayoutBox.AddImage | (*args, **kwargs) | return _richtext.RichTextParagraphLayoutBox_AddImage(*args, **kwargs) | AddImage(self, Image image, RichTextAttr paraStyle=None) -> RichTextRange | AddImage(self, Image image, RichTextAttr paraStyle=None) -> RichTextRange | [
"AddImage",
"(",
"self",
"Image",
"image",
"RichTextAttr",
"paraStyle",
"=",
"None",
")",
"-",
">",
"RichTextRange"
] | def AddImage(*args, **kwargs):
"""AddImage(self, Image image, RichTextAttr paraStyle=None) -> RichTextRange"""
return _richtext.RichTextParagraphLayoutBox_AddImage(*args, **kwargs) | [
"def",
"AddImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraphLayoutBox_AddImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L1660-L1662 | |
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/parsers/XmlTopologyParser.py | python | XmlTopologyParser.get_name | (self) | return self.__name | Return name | Return name | [
"Return",
"name"
] | def get_name(self):
"""
Return name
"""
return self.__name | [
"def",
"get_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"__name"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/parsers/XmlTopologyParser.py#L322-L326 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/buttonpanel.py | python | ButtonInfo.GetText | (self) | return self._text | Returns the text associated to the button.
:return: A string containing the :class:`ButtonInfo` text. | Returns the text associated to the button. | [
"Returns",
"the",
"text",
"associated",
"to",
"the",
"button",
"."
] | def GetText(self):
"""
Returns the text associated to the button.
:return: A string containing the :class:`ButtonInfo` text.
"""
return self._text | [
"def",
"GetText",
"(",
"self",
")",
":",
"return",
"self",
".",
"_text"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L1698-L1705 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBValue.GetLocation | (self) | return _lldb.SBValue_GetLocation(self) | GetLocation(self) -> str | GetLocation(self) -> str | [
"GetLocation",
"(",
"self",
")",
"-",
">",
"str"
] | def GetLocation(self):
"""GetLocation(self) -> str"""
return _lldb.SBValue_GetLocation(self) | [
"def",
"GetLocation",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBValue_GetLocation",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11924-L11926 | |
envoyproxy/envoy-wasm | ab5d9381fdf92a1efa0b87cff80036b5b3e81198 | tools/code_format/format_python_tools.py | python | validateFormat | (fix=False) | return not fixes_required | Check the format of python files in the tools directory.
Arguments:
fix: a flag to indicate if fixes should be applied. | Check the format of python files in the tools directory. | [
"Check",
"the",
"format",
"of",
"python",
"files",
"in",
"the",
"tools",
"directory",
"."
] | def validateFormat(fix=False):
"""Check the format of python files in the tools directory.
Arguments:
fix: a flag to indicate if fixes should be applied.
"""
fixes_required = False
failed_update_files = set()
successful_update_files = set()
for python_file in collectFiles():
reformatted_source, encoding, changed = FormatFile(python_file,
style_config='tools/code_format/.style.yapf',
in_place=fix,
print_diff=not fix)
if not fix:
fixes_required = True if changed else fixes_required
if reformatted_source:
print(reformatted_source)
continue
file_list = failed_update_files if reformatted_source else successful_update_files
file_list.add(python_file)
if fix:
displayFixResults(successful_update_files, failed_update_files)
fixes_required = len(failed_update_files) > 0
return not fixes_required | [
"def",
"validateFormat",
"(",
"fix",
"=",
"False",
")",
":",
"fixes_required",
"=",
"False",
"failed_update_files",
"=",
"set",
"(",
")",
"successful_update_files",
"=",
"set",
"(",
")",
"for",
"python_file",
"in",
"collectFiles",
"(",
")",
":",
"reformatted_s... | https://github.com/envoyproxy/envoy-wasm/blob/ab5d9381fdf92a1efa0b87cff80036b5b3e81198/tools/code_format/format_python_tools.py#L31-L55 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/peakmeter.py | python | PeakMeterCtrl.DrawHorzBand | (self, dc, rect) | Draws horizontal bands.
:param `dc`: an instance of :class:`DC`;
:param `rect`: the horizontal bands client rectangle.
.. todo:: Implement falloff effect for horizontal bands. | Draws horizontal bands. | [
"Draws",
"horizontal",
"bands",
"."
] | def DrawHorzBand(self, dc, rect):
"""
Draws horizontal bands.
:param `dc`: an instance of :class:`DC`;
:param `rect`: the horizontal bands client rectangle.
.. todo:: Implement falloff effect for horizontal bands.
"""
horzBands = (self._ledBands > 1 and [self._ledBands] or [self._maxValue*BAND_PERCENT/100])[0]
minHorzLimit = self._minValue*horzBands/self._maxValue
medHorzLimit = self._medValue*horzBands/self._maxValue
maxHorzLimit = horzBands
size = wx.Size(rect.width/horzBands, rect.height/self._numBands)
rectBand = wx.RectPS(rect.GetTopLeft(), size)
# Draw band from top
rectBand.OffsetXY(0, rect.height-size.y*self._numBands)
xDecal = (self._ledBands > 1 and [1] or [0])[0]
yDecal = (self._numBands > 1 and [1] or [0])[0]
for vert in xrange(self._numBands):
self._value = self._meterData[vert]._value
horzLimit = self._value*horzBands/self._maxValue
rectPrev = wx.Rect(*rectBand)
for horz in xrange(horzBands):
rectBand.Deflate(0, yDecal)
# Find colour based on range value
colourRect = self._clrBackground
if self._showGrid:
colourRect = DarkenColour(self._clrBackground, GRID_INCREASEBY)
if self._showGrid and (horz == minHorzLimit or horz == (horzBands-1)):
points = [wx.Point() for i in xrange(2)]
points[0].x = rectBand.GetTopLeft().x + (rectBand.width >> 1)
points[0].y = rectBand.GetTopLeft().y - yDecal
points[1].x = points[0].x
points[1].y = rectBand.GetBottomRight().y + yDecal
dc.DrawLinePoint(points[0], points[1])
if horz < horzLimit:
if InRange(horz, 0, minHorzLimit-1):
colourRect = self._clrNormal
elif InRange(horz, minHorzLimit, medHorzLimit-1):
colourRect = self._clrMedium
elif InRange(horz, medHorzLimit, maxHorzLimit):
colourRect = self._clrHigh
dc.SetBrush(wx.Brush(colourRect))
dc.DrawRectangleRect(rectBand)
rectBand.Inflate(0, yDecal)
rectBand.OffsetXY(size.x, 0)
# Draw falloff effect (Seems to be working now.)
if self._showFalloff:
oldPen = dc.GetPen()
pen = wx.Pen(DarkenColour(self._clrBackground, FALL_INCREASEBY))
maxWidth = size.x*horzBands
points = [wx.Point() for i in xrange(2)]
points[0].y = rectPrev.GetTopRight().y - yDecal
points[0].x = rectPrev.GetBottomLeft().x + self._meterData[vert]._falloff*maxWidth/self._maxValue
points[1].y = rectPrev.GetBottomLeft().y + yDecal
points[1].x = points[0].x
dc.SetPen(pen)
dc.DrawLinePoint(points[0], points[1])
dc.SetPen(oldPen)
# Move to Next Vertical band
rectBand.OffsetXY(-size.x*horzBands, size.y) | [
"def",
"DrawHorzBand",
"(",
"self",
",",
"dc",
",",
"rect",
")",
":",
"horzBands",
"=",
"(",
"self",
".",
"_ledBands",
">",
"1",
"and",
"[",
"self",
".",
"_ledBands",
"]",
"or",
"[",
"self",
".",
"_maxValue",
"*",
"BAND_PERCENT",
"/",
"100",
"]",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/peakmeter.py#L720-L797 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py | python | is_std_string | (type_) | return type_.decl_string in string_equivalences | Returns True, if type represents C++ `std::string`, False otherwise. | Returns True, if type represents C++ `std::string`, False otherwise. | [
"Returns",
"True",
"if",
"type",
"represents",
"C",
"++",
"std",
"::",
"string",
"False",
"otherwise",
"."
] | def is_std_string(type_):
"""
Returns True, if type represents C++ `std::string`, False otherwise.
"""
if utils.is_str(type_):
return type_ in string_equivalences
type_ = remove_alias(type_)
type_ = remove_reference(type_)
type_ = remove_cv(type_)
return type_.decl_string in string_equivalences | [
"def",
"is_std_string",
"(",
"type_",
")",
":",
"if",
"utils",
".",
"is_str",
"(",
"type_",
")",
":",
"return",
"type_",
"in",
"string_equivalences",
"type_",
"=",
"remove_alias",
"(",
"type_",
")",
"type_",
"=",
"remove_reference",
"(",
"type_",
")",
"typ... | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py#L512-L524 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/calendar.py | python | CalendarCtrlBase.AllowMonthChange | (*args, **kwargs) | return _calendar.CalendarCtrlBase_AllowMonthChange(*args, **kwargs) | AllowMonthChange(self) -> bool | AllowMonthChange(self) -> bool | [
"AllowMonthChange",
"(",
"self",
")",
"-",
">",
"bool"
] | def AllowMonthChange(*args, **kwargs):
"""AllowMonthChange(self) -> bool"""
return _calendar.CalendarCtrlBase_AllowMonthChange(*args, **kwargs) | [
"def",
"AllowMonthChange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"CalendarCtrlBase_AllowMonthChange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/calendar.py#L265-L267 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/zipfile.py | python | ZipFile.writestr | (self, zinfo_or_arcname, data,
compress_type=None, compresslevel=None) | Write a file into the archive. The contents is 'data', which
may be either a 'str' or a 'bytes' instance; if it is a 'str',
it is encoded as UTF-8 first.
'zinfo_or_arcname' is either a ZipInfo instance or
the name of the file in the archive. | Write a file into the archive. The contents is 'data', which
may be either a 'str' or a 'bytes' instance; if it is a 'str',
it is encoded as UTF-8 first.
'zinfo_or_arcname' is either a ZipInfo instance or
the name of the file in the archive. | [
"Write",
"a",
"file",
"into",
"the",
"archive",
".",
"The",
"contents",
"is",
"data",
"which",
"may",
"be",
"either",
"a",
"str",
"or",
"a",
"bytes",
"instance",
";",
"if",
"it",
"is",
"a",
"str",
"it",
"is",
"encoded",
"as",
"UTF",
"-",
"8",
"firs... | def writestr(self, zinfo_or_arcname, data,
compress_type=None, compresslevel=None):
"""Write a file into the archive. The contents is 'data', which
may be either a 'str' or a 'bytes' instance; if it is a 'str',
it is encoded as UTF-8 first.
'zinfo_or_arcname' is either a ZipInfo instance or
the name of the file in the archive."""
if isinstance(data, str):
data = data.encode("utf-8")
if not isinstance(zinfo_or_arcname, ZipInfo):
zinfo = ZipInfo(filename=zinfo_or_arcname,
date_time=time.localtime(time.time())[:6])
zinfo.compress_type = self.compression
zinfo._compresslevel = self.compresslevel
if zinfo.filename[-1] == '/':
zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.external_attr = 0o600 << 16 # ?rw-------
else:
zinfo = zinfo_or_arcname
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists."
)
if compress_type is not None:
zinfo.compress_type = compress_type
if compresslevel is not None:
zinfo._compresslevel = compresslevel
zinfo.file_size = len(data) # Uncompressed size
with self._lock:
with self.open(zinfo, mode='w') as dest:
dest.write(data) | [
"def",
"writestr",
"(",
"self",
",",
"zinfo_or_arcname",
",",
"data",
",",
"compress_type",
"=",
"None",
",",
"compresslevel",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"\"utf... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/zipfile.py#L1766-L1805 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/nn.py | python | normalize_moments | (counts, mean_ss, variance_ss, shift, name=None) | return (mean, variance) | Calculate the mean and variance of based on the sufficient statistics.
Args:
counts: A `Tensor` containing a the total count of the data (one value).
mean_ss: A `Tensor` containing the mean sufficient statistics: the (possibly
shifted) sum of the elements to average over.
variance_ss: A `Tensor` containing the variance sufficient statistics: the
(possibly shifted) squared sum of the data to compute the variance over.
shift: A `Tensor` containing the value by which the data is shifted for
numerical stability, or `None` if no shift was performed.
name: Name used to scope the operations that compute the moments.
Returns:
Two `Tensor` objects: `mean` and `variance`. | Calculate the mean and variance of based on the sufficient statistics. | [
"Calculate",
"the",
"mean",
"and",
"variance",
"of",
"based",
"on",
"the",
"sufficient",
"statistics",
"."
] | def normalize_moments(counts, mean_ss, variance_ss, shift, name=None):
"""Calculate the mean and variance of based on the sufficient statistics.
Args:
counts: A `Tensor` containing a the total count of the data (one value).
mean_ss: A `Tensor` containing the mean sufficient statistics: the (possibly
shifted) sum of the elements to average over.
variance_ss: A `Tensor` containing the variance sufficient statistics: the
(possibly shifted) squared sum of the data to compute the variance over.
shift: A `Tensor` containing the value by which the data is shifted for
numerical stability, or `None` if no shift was performed.
name: Name used to scope the operations that compute the moments.
Returns:
Two `Tensor` objects: `mean` and `variance`.
"""
with ops.name_scope(name, "normalize", [counts, mean_ss, variance_ss, shift]):
divisor = math_ops.inv(counts, name="divisor")
if shift is not None:
shifted_mean = math_ops.mul(mean_ss, divisor, name="shifted_mean")
mean = math_ops.add(shifted_mean, shift, name="mean")
else: # no shift.
shifted_mean = math_ops.mul(mean_ss, divisor, name="mean")
mean = shifted_mean
variance = math_ops.sub(math_ops.mul(variance_ss, divisor),
math_ops.square(shifted_mean),
name="variance")
return (mean, variance) | [
"def",
"normalize_moments",
"(",
"counts",
",",
"mean_ss",
",",
"variance_ss",
",",
"shift",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"normalize\"",
",",
"[",
"counts",
",",
"mean_ss",
",",
"variance_ss",
... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/nn.py#L775-L802 | |
opengauss-mirror/openGauss-server | e383f1b77720a00ddbe4c0655bc85914d9b02a2b | src/gausskernel/dbmind/tools/ai_manager/tools/cert_generator.py | python | CertGenerator.create_root_certificate | (ca_password, ca_crt_path, ca_key_path, config_path) | function : create root ca file
input : rand pass, dir path of certificates, config path
output : NA | function : create root ca file
input : rand pass, dir path of certificates, config path
output : NA | [
"function",
":",
"create",
"root",
"ca",
"file",
"input",
":",
"rand",
"pass",
"dir",
"path",
"of",
"certificates",
"config",
"path",
"output",
":",
"NA"
] | def create_root_certificate(ca_password, ca_crt_path, ca_key_path, config_path):
"""
function : create root ca file
input : rand pass, dir path of certificates, config path
output : NA
"""
if not os.path.isfile(config_path):
raise Exception(Errors.FILE_DIR_PATH['gauss_0102'] % config_path)
CommonTools.mkdir_with_mode(os.path.dirname(ca_crt_path), Constant.AUTH_COMMON_DIR_STR)
CommonTools.mkdir_with_mode(os.path.dirname(ca_key_path), Constant.AUTH_COMMON_DIR_STR)
ca_req_path = os.path.realpath(os.path.join(
os.path.dirname(ca_crt_path), Constant.CA_ROOT_REQ))
# create ca key file
cmd = "%s echo '%s' |openssl genrsa -aes256 -passout stdin -out %s 2048" % (
Constant.CMD_PREFIX, ca_password, ca_key_path)
cmd += " && %s" % Constant.SHELL_CMD_DICT['changeMode'] % (
Constant.AUTH_COMMON_FILE_STR, ca_key_path)
status, output = CommonTools.get_status_output_error(cmd, mixed=True)
if status != 0:
raise Exception(Errors.EXECUTE_RESULT['gauss_0414'] % 'ca root key file')
# 2 create ca req file
cmd = "%s echo '%s' | openssl req -new -out %s -key %s -config %s -passin stdin" % (
Constant.CMD_PREFIX, ca_password, ca_req_path, ca_key_path, config_path)
cmd += " && %s" % Constant.SHELL_CMD_DICT['changeMode'] % (
Constant.AUTH_COMMON_FILE_STR, ca_req_path)
status, output = CommonTools.get_status_output_error(cmd, mixed=True)
if status != 0:
raise Exception(Errors.EXECUTE_RESULT['gauss_0414'] % 'ca root req file')
# 3 create ca crt file
cmd = "%s echo '%s' | openssl x509 -req -in %s " \
"-signkey %s -days %s -out %s -passin stdin" % (
Constant.CMD_PREFIX, ca_password, ca_req_path,
ca_key_path, Constant.CA_ROOT_VALID_DATE, ca_crt_path)
cmd += " && %s" % Constant.SHELL_CMD_DICT['changeMode'] % (
Constant.AUTH_COMMON_FILE_STR, ca_crt_path)
status, output = CommonTools.get_status_output_error(cmd, mixed=True)
if status != 0:
raise Exception(Errors.EXECUTE_RESULT['gauss_0414'] % 'ca root crt file')
CommonTools.remove_files([ca_req_path])
g.logger.info('Successfully generate ca root certificate, file path[%s].' % ca_crt_path) | [
"def",
"create_root_certificate",
"(",
"ca_password",
",",
"ca_crt_path",
",",
"ca_key_path",
",",
"config_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"raise",
"Exception",
"(",
"Errors",
".",
"FILE_DIR_PATH",
... | https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/ai_manager/tools/cert_generator.py#L63-L105 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/labelbook.py | python | ImageContainerBase.GetPageImage | (self, page) | return imgInfo.GetImageIndex() | Returns the image index for the given page.
:param `page`: the index of the tab. | Returns the image index for the given page.
:param `page`: the index of the tab. | [
"Returns",
"the",
"image",
"index",
"for",
"the",
"given",
"page",
".",
":",
"param",
"page",
":",
"the",
"index",
"of",
"the",
"tab",
"."
] | def GetPageImage(self, page):
"""
Returns the image index for the given page.
:param `page`: the index of the tab.
"""
imgInfo = self._pagesInfoVec[page]
return imgInfo.GetImageIndex() | [
"def",
"GetPageImage",
"(",
"self",
",",
"page",
")",
":",
"imgInfo",
"=",
"self",
".",
"_pagesInfoVec",
"[",
"page",
"]",
"return",
"imgInfo",
".",
"GetImageIndex",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/labelbook.py#L675-L683 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/utils/find_usb_devices.py | python | USBNode.FindDeviceNumber | (self, findnum) | return None | Find device with given number in tree
Searches the portion of the device tree rooted at this node for
a device with the given device number.
Args:
findnum: [int] Device number to search for.
Returns:
[USBDeviceNode] Node that is found. | Find device with given number in tree | [
"Find",
"device",
"with",
"given",
"number",
"in",
"tree"
] | def FindDeviceNumber(self, findnum):
"""Find device with given number in tree
Searches the portion of the device tree rooted at this node for
a device with the given device number.
Args:
findnum: [int] Device number to search for.
Returns:
[USBDeviceNode] Node that is found.
"""
for node in self.AllNodes():
if node.device_num == findnum:
return node
return None | [
"def",
"FindDeviceNumber",
"(",
"self",
",",
"findnum",
")",
":",
"for",
"node",
"in",
"self",
".",
"AllNodes",
"(",
")",
":",
"if",
"node",
".",
"device_num",
"==",
"findnum",
":",
"return",
"node",
"return",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/utils/find_usb_devices.py#L122-L137 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/symbol/symbol.py | python | Symbol.repeat | (self, *args, **kwargs) | return op.repeat(self, *args, **kwargs) | Convenience fluent method for :py:func:`repeat`.
The arguments are the same as for :py:func:`repeat`, with
this array as data. | Convenience fluent method for :py:func:`repeat`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"repeat",
"."
] | def repeat(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`repeat`.
The arguments are the same as for :py:func:`repeat`, with
this array as data.
"""
return op.repeat(self, *args, **kwargs) | [
"def",
"repeat",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"repeat",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/symbol/symbol.py#L1926-L1932 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Layer.SymDifference | (self, *args, **kwargs) | return _ogr.Layer_SymDifference(self, *args, **kwargs) | r"""
SymDifference(Layer self, Layer method_layer, Layer result_layer, char ** options=None, GDALProgressFunc callback=0, void * callback_data=None) -> OGRErr
OGRErr
OGR_L_SymDifference(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
OGRLayerH pLayerResult, char **papszOptions, GDALProgressFunc
pfnProgress, void *pProgressArg)
Symmetrical difference of two layers.
The result layer contains features whose geometries represent areas
that are in either in the input layer or in the method layer but not
in both. The features in the result layer have attributes from both
input and method layers. For features which represent areas that are
only in the input or in the method layer the respective attributes
have undefined values. The schema of the result layer can be set by
the user or, if it is empty, is initialized to contain all fields in
the input and method layers.
If the schema of the result is set by user and contains fields that
have the same name as a field in input and in method layer, then the
attribute in the result feature will get the value from the feature of
the method layer (even if it is undefined).
For best performance use the minimum amount of features in the method
layer and copy it into a memory layer.
This method relies on GEOS support. Do not use unless the GEOS support
is compiled in. The recognized list of options is :
SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a feature
could not be inserted or a GEOS call failed.
PROMOTE_TO_MULTI=YES/NO. Set it to YES to convert Polygons into
MultiPolygons, or LineStrings to MultiLineStrings.
INPUT_PREFIX=string. Set a prefix for the field names that will be
created from the fields of the input layer.
METHOD_PREFIX=string. Set a prefix for the field names that will be
created from the fields of the method layer.
This function is the same as the C++ method OGRLayer::SymDifference().
Parameters:
-----------
pLayerInput: the input layer. Should not be NULL.
pLayerMethod: the method layer. Should not be NULL.
pLayerResult: the layer where the features resulting from the
operation are inserted. Should not be NULL. See above the note about
the schema.
papszOptions: NULL terminated list of options (may be NULL).
pfnProgress: a GDALProgressFunc() compatible callback function for
reporting progress or NULL.
pProgressArg: argument to be passed to pfnProgress. May be NULL.
an error code if there was an error or the execution was interrupted,
OGRERR_NONE otherwise.
The first geometry field is always used.
OGR 1.10 | r"""
SymDifference(Layer self, Layer method_layer, Layer result_layer, char ** options=None, GDALProgressFunc callback=0, void * callback_data=None) -> OGRErr
OGRErr
OGR_L_SymDifference(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
OGRLayerH pLayerResult, char **papszOptions, GDALProgressFunc
pfnProgress, void *pProgressArg) | [
"r",
"SymDifference",
"(",
"Layer",
"self",
"Layer",
"method_layer",
"Layer",
"result_layer",
"char",
"**",
"options",
"=",
"None",
"GDALProgressFunc",
"callback",
"=",
"0",
"void",
"*",
"callback_data",
"=",
"None",
")",
"-",
">",
"OGRErr",
"OGRErr",
"OGR_L_S... | def SymDifference(self, *args, **kwargs):
r"""
SymDifference(Layer self, Layer method_layer, Layer result_layer, char ** options=None, GDALProgressFunc callback=0, void * callback_data=None) -> OGRErr
OGRErr
OGR_L_SymDifference(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
OGRLayerH pLayerResult, char **papszOptions, GDALProgressFunc
pfnProgress, void *pProgressArg)
Symmetrical difference of two layers.
The result layer contains features whose geometries represent areas
that are in either in the input layer or in the method layer but not
in both. The features in the result layer have attributes from both
input and method layers. For features which represent areas that are
only in the input or in the method layer the respective attributes
have undefined values. The schema of the result layer can be set by
the user or, if it is empty, is initialized to contain all fields in
the input and method layers.
If the schema of the result is set by user and contains fields that
have the same name as a field in input and in method layer, then the
attribute in the result feature will get the value from the feature of
the method layer (even if it is undefined).
For best performance use the minimum amount of features in the method
layer and copy it into a memory layer.
This method relies on GEOS support. Do not use unless the GEOS support
is compiled in. The recognized list of options is :
SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a feature
could not be inserted or a GEOS call failed.
PROMOTE_TO_MULTI=YES/NO. Set it to YES to convert Polygons into
MultiPolygons, or LineStrings to MultiLineStrings.
INPUT_PREFIX=string. Set a prefix for the field names that will be
created from the fields of the input layer.
METHOD_PREFIX=string. Set a prefix for the field names that will be
created from the fields of the method layer.
This function is the same as the C++ method OGRLayer::SymDifference().
Parameters:
-----------
pLayerInput: the input layer. Should not be NULL.
pLayerMethod: the method layer. Should not be NULL.
pLayerResult: the layer where the features resulting from the
operation are inserted. Should not be NULL. See above the note about
the schema.
papszOptions: NULL terminated list of options (may be NULL).
pfnProgress: a GDALProgressFunc() compatible callback function for
reporting progress or NULL.
pProgressArg: argument to be passed to pfnProgress. May be NULL.
an error code if there was an error or the execution was interrupted,
OGRERR_NONE otherwise.
The first geometry field is always used.
OGR 1.10
"""
return _ogr.Layer_SymDifference(self, *args, **kwargs) | [
"def",
"SymDifference",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_ogr",
".",
"Layer_SymDifference",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L2346-L2414 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/rnn_cell.py | python | MultiRNNCell.__call__ | (self, inputs, state, scope=None) | return cur_inp, new_states | Run this multi-layer cell on inputs, starting from state. | Run this multi-layer cell on inputs, starting from state. | [
"Run",
"this",
"multi",
"-",
"layer",
"cell",
"on",
"inputs",
"starting",
"from",
"state",
"."
] | def __call__(self, inputs, state, scope=None):
"""Run this multi-layer cell on inputs, starting from state."""
with vs.variable_scope(scope or type(self).__name__): # "MultiRNNCell"
cur_state_pos = 0
cur_inp = inputs
new_states = []
for i, cell in enumerate(self._cells):
with vs.variable_scope("Cell%d" % i):
if self._state_is_tuple:
if not nest.is_sequence(state):
raise ValueError(
"Expected state to be a tuple of length %d, but received: %s"
% (len(self.state_size), state))
cur_state = state[i]
else:
cur_state = array_ops.slice(
state, [0, cur_state_pos], [-1, cell.state_size])
cur_state_pos += cell.state_size
cur_inp, new_state = cell(cur_inp, cur_state)
new_states.append(new_state)
new_states = (tuple(new_states) if self._state_is_tuple
else array_ops.concat(1, new_states))
return cur_inp, new_states | [
"def",
"__call__",
"(",
"self",
",",
"inputs",
",",
"state",
",",
"scope",
"=",
"None",
")",
":",
"with",
"vs",
".",
"variable_scope",
"(",
"scope",
"or",
"type",
"(",
"self",
")",
".",
"__name__",
")",
":",
"# \"MultiRNNCell\"",
"cur_state_pos",
"=",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/rnn_cell.py#L794-L816 | |
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | amalgamation/python/mxnet_predict.py | python | _check_call | (ret) | Check the return value of API. | Check the return value of API. | [
"Check",
"the",
"return",
"value",
"of",
"API",
"."
] | def _check_call(ret):
"""Check the return value of API."""
if ret != 0:
raise RuntimeError(py_str(_LIB.MXGetLastError())) | [
"def",
"_check_call",
"(",
"ret",
")",
":",
"if",
"ret",
"!=",
"0",
":",
"raise",
"RuntimeError",
"(",
"py_str",
"(",
"_LIB",
".",
"MXGetLastError",
"(",
")",
")",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/amalgamation/python/mxnet_predict.py#L52-L55 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | TurtleScreenBase._window_size | (self) | return width, height | Return the width and height of the turtle window. | Return the width and height of the turtle window. | [
"Return",
"the",
"width",
"and",
"height",
"of",
"the",
"turtle",
"window",
"."
] | def _window_size(self):
""" Return the width and height of the turtle window.
"""
width = self.cv.winfo_width()
if width <= 1: # the window isn't managed by a geometry manager
width = self.cv['width']
height = self.cv.winfo_height()
if height <= 1: # the window isn't managed by a geometry manager
height = self.cv['height']
return width, height | [
"def",
"_window_size",
"(",
"self",
")",
":",
"width",
"=",
"self",
".",
"cv",
".",
"winfo_width",
"(",
")",
"if",
"width",
"<=",
"1",
":",
"# the window isn't managed by a geometry manager",
"width",
"=",
"self",
".",
"cv",
"[",
"'width'",
"]",
"height",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L788-L797 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pubsub/core/topicobj.py | python | Topic.isAll | (self) | return self.__tupleName == (ALL_TOPICS,) | Returns true if this topic is the 'all topics' topic. All root
topics behave as though they are child of that topic. | Returns true if this topic is the 'all topics' topic. All root
topics behave as though they are child of that topic. | [
"Returns",
"true",
"if",
"this",
"topic",
"is",
"the",
"all",
"topics",
"topic",
".",
"All",
"root",
"topics",
"behave",
"as",
"though",
"they",
"are",
"child",
"of",
"that",
"topic",
"."
] | def isAll(self):
"""Returns true if this topic is the 'all topics' topic. All root
topics behave as though they are child of that topic. """
return self.__tupleName == (ALL_TOPICS,) | [
"def",
"isAll",
"(",
"self",
")",
":",
"return",
"self",
".",
"__tupleName",
"==",
"(",
"ALL_TOPICS",
",",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/topicobj.py#L182-L185 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/losses/python/losses/loss_ops.py | python | _num_present | (losses, weight, per_batch=False) | return num_per_batch if per_batch else math_ops.reduce_sum(num_per_batch) | Computes the number of elements in the loss function induced by `weight`.
A given weight tensor induces different numbers of usable elements in the
`losses` tensor. The `weight` tensor is broadcast across `losses` for all
possible dimensions. For example, if `losses` is a tensor of dimension
[4, 5, 6, 3] and weight is a tensor of size [4, 5], then weight is, in effect,
tiled to match the size of `losses`. Following this effective tile, the total
number of present elements is the number of non-zero weights.
Args:
losses: A tensor of size [batch_size, d1, ... dN].
weight: A tensor of size [1] or [batch_size, d1, ... dK] where K < N.
per_batch: Whether to return the number of elements per batch or as a sum
total.
Returns:
The number of present (non-zero) elements in the losses tensor. If
`per_batch` is True, the value is returned as a tensor of size
[batch_size]. Otherwise, a single scalar tensor is returned. | Computes the number of elements in the loss function induced by `weight`. | [
"Computes",
"the",
"number",
"of",
"elements",
"in",
"the",
"loss",
"function",
"induced",
"by",
"weight",
"."
] | def _num_present(losses, weight, per_batch=False):
"""Computes the number of elements in the loss function induced by `weight`.
A given weight tensor induces different numbers of usable elements in the
`losses` tensor. The `weight` tensor is broadcast across `losses` for all
possible dimensions. For example, if `losses` is a tensor of dimension
[4, 5, 6, 3] and weight is a tensor of size [4, 5], then weight is, in effect,
tiled to match the size of `losses`. Following this effective tile, the total
number of present elements is the number of non-zero weights.
Args:
losses: A tensor of size [batch_size, d1, ... dN].
weight: A tensor of size [1] or [batch_size, d1, ... dK] where K < N.
per_batch: Whether to return the number of elements per batch or as a sum
total.
Returns:
The number of present (non-zero) elements in the losses tensor. If
`per_batch` is True, the value is returned as a tensor of size
[batch_size]. Otherwise, a single scalar tensor is returned.
"""
# To ensure that dims of [2, 1] gets mapped to [2,]
weight = array_ops.squeeze(weight)
# If the weight is a scalar, its easy to compute:
if weight.get_shape().ndims == 0:
batch_size = array_ops.reshape(array_ops.slice(array_ops.shape(losses),
[0], [1]), [])
num_per_batch = math_ops.div(math_ops.to_float(array_ops.size(losses)),
math_ops.to_float(batch_size))
num_per_batch = math_ops.select(math_ops.equal(weight, 0),
0.0, num_per_batch)
num_per_batch = math_ops.mul(array_ops.ones(
array_ops.reshape(batch_size, [1])), num_per_batch)
return num_per_batch if per_batch else math_ops.reduce_sum(num_per_batch)
# First, count the number of nonzero weights:
if weight.get_shape().ndims >= 1:
reduction_indices = list(range(1, weight.get_shape().ndims))
num_nonzero_per_batch = math_ops.reduce_sum(
math_ops.to_float(math_ops.not_equal(weight, 0)),
reduction_indices=reduction_indices)
# Next, determine the number of elements that weight would broadcast to:
broadcast_dims = array_ops.slice(array_ops.shape(losses),
[weight.get_shape().ndims], [-1])
num_to_broadcast = math_ops.to_float(math_ops.reduce_prod(broadcast_dims))
num_per_batch = math_ops.mul(num_nonzero_per_batch, num_to_broadcast)
return num_per_batch if per_batch else math_ops.reduce_sum(num_per_batch) | [
"def",
"_num_present",
"(",
"losses",
",",
"weight",
",",
"per_batch",
"=",
"False",
")",
":",
"# To ensure that dims of [2, 1] gets mapped to [2,]",
"weight",
"=",
"array_ops",
".",
"squeeze",
"(",
"weight",
")",
"# If the weight is a scalar, its easy to compute:",
"if",... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/losses/python/losses/loss_ops.py#L143-L192 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/timeout.py | python | Timeout.connect_timeout | (self) | return min(self._connect, self.total) | Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None | Get the value to use when setting a connection timeout. | [
"Get",
"the",
"value",
"to",
"use",
"when",
"setting",
"a",
"connection",
"timeout",
"."
] | def connect_timeout(self):
""" Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
"""
if self.total is None:
return self._connect
if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
return self.total
return min(self._connect, self.total) | [
"def",
"connect_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"total",
"is",
"None",
":",
"return",
"self",
".",
"_connect",
"if",
"self",
".",
"_connect",
"is",
"None",
"or",
"self",
".",
"_connect",
"is",
"self",
".",
"DEFAULT_TIMEOUT",
":",
"r... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/timeout.py#L211-L226 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/functional.py | python | smooth_l1_loss | (
input: Tensor,
target: Tensor,
size_average: Optional[bool] = None,
reduce: Optional[bool] = None,
reduction: str = "mean",
beta: float = 1.0,
) | return torch._C._nn.smooth_l1_loss(expanded_input, expanded_target, _Reduction.get_enum(reduction), beta) | r"""Function that uses a squared term if the absolute
element-wise error falls below beta and an L1 term otherwise.
See :class:`~torch.nn.SmoothL1Loss` for details. | r"""Function that uses a squared term if the absolute
element-wise error falls below beta and an L1 term otherwise. | [
"r",
"Function",
"that",
"uses",
"a",
"squared",
"term",
"if",
"the",
"absolute",
"element",
"-",
"wise",
"error",
"falls",
"below",
"beta",
"and",
"an",
"L1",
"term",
"otherwise",
"."
] | def smooth_l1_loss(
input: Tensor,
target: Tensor,
size_average: Optional[bool] = None,
reduce: Optional[bool] = None,
reduction: str = "mean",
beta: float = 1.0,
) -> Tensor:
r"""Function that uses a squared term if the absolute
element-wise error falls below beta and an L1 term otherwise.
See :class:`~torch.nn.SmoothL1Loss` for details.
"""
if has_torch_function_variadic(input, target):
return handle_torch_function(
smooth_l1_loss,
(input, target),
input,
target,
size_average=size_average,
reduce=reduce,
reduction=reduction,
beta=beta,
)
if not (target.size() == input.size()):
warnings.warn(
"Using a target size ({}) that is different to the input size ({}). "
"This will likely lead to incorrect results due to broadcasting. "
"Please ensure they have the same size.".format(target.size(), input.size()),
stacklevel=2,
)
if size_average is not None or reduce is not None:
reduction = _Reduction.legacy_get_string(size_average, reduce)
expanded_input, expanded_target = torch.broadcast_tensors(input, target)
return torch._C._nn.smooth_l1_loss(expanded_input, expanded_target, _Reduction.get_enum(reduction), beta) | [
"def",
"smooth_l1_loss",
"(",
"input",
":",
"Tensor",
",",
"target",
":",
"Tensor",
",",
"size_average",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"reduce",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"reduction",
":",
"str",
"=",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/functional.py#L3135-L3170 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | win32/scripts/regsetup.py | python | FindPackagePath | (packageName, knownFileName, searchPaths) | Find a package.
Given a ni style package name, check the package is registered.
First place looked is the registry for an existing entry. Then
the searchPaths are searched. | Find a package. | [
"Find",
"a",
"package",
"."
] | def FindPackagePath(packageName, knownFileName, searchPaths):
"""Find a package.
Given a ni style package name, check the package is registered.
First place looked is the registry for an existing entry. Then
the searchPaths are searched.
"""
import regutil, os
pathLook = regutil.GetRegisteredNamedPath(packageName)
if pathLook and IsPackageDir(pathLook, packageName, knownFileName):
return pathLook, None # The currently registered one is good.
# Search down the search paths.
for pathLook in searchPaths:
if IsPackageDir(pathLook, packageName, knownFileName):
# Found it
ret = os.path.abspath(pathLook)
return ret, ret
raise error("The package %s can not be located" % packageName) | [
"def",
"FindPackagePath",
"(",
"packageName",
",",
"knownFileName",
",",
"searchPaths",
")",
":",
"import",
"regutil",
",",
"os",
"pathLook",
"=",
"regutil",
".",
"GetRegisteredNamedPath",
"(",
"packageName",
")",
"if",
"pathLook",
"and",
"IsPackageDir",
"(",
"p... | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/scripts/regsetup.py#L43-L62 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListItemData.SetData | (self, data) | Sets client data for the item.
:param `data`: the client data associated to the item.
:note: Please note that client data is associated with the item and not
with subitems. | Sets client data for the item. | [
"Sets",
"client",
"data",
"for",
"the",
"item",
"."
] | def SetData(self, data):
"""
Sets client data for the item.
:param `data`: the client data associated to the item.
:note: Please note that client data is associated with the item and not
with subitems.
"""
self._data = data | [
"def",
"SetData",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"data"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L2565-L2575 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/tensor_shape.py | python | Dimension.__div__ | (self, other) | return self // other | DEPRECATED: Use `__floordiv__` via `x // y` instead.
This function exists only for backwards compatibility purposes; new code
should use `__floordiv__` via the syntax `x // y`. Using `x // y`
communicates clearly that the result rounds down, and is forward compatible
to Python 3.
Args:
other: Another `Dimension`.
Returns:
A `Dimension` whose value is the integer quotient of `self` and `other`. | DEPRECATED: Use `__floordiv__` via `x // y` instead. | [
"DEPRECATED",
":",
"Use",
"__floordiv__",
"via",
"x",
"//",
"y",
"instead",
"."
] | def __div__(self, other):
"""DEPRECATED: Use `__floordiv__` via `x // y` instead.
This function exists only for backwards compatibility purposes; new code
should use `__floordiv__` via the syntax `x // y`. Using `x // y`
communicates clearly that the result rounds down, and is forward compatible
to Python 3.
Args:
other: Another `Dimension`.
Returns:
A `Dimension` whose value is the integer quotient of `self` and `other`.
"""
return self // other | [
"def",
"__div__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
"//",
"other"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L227-L241 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchComponent.py | python | ViewProviderComponent.areDifferentColors | (self,a,b) | return False | Check if two diffuse colors are almost the same.
Parameters
----------
a: tuple
The first DiffuseColor value to compare.
a: tuple
The second DiffuseColor value to compare.
Returns
-------
bool:
True if colors are different, false if they are similar. | Check if two diffuse colors are almost the same. | [
"Check",
"if",
"two",
"diffuse",
"colors",
"are",
"almost",
"the",
"same",
"."
] | def areDifferentColors(self,a,b):
"""Check if two diffuse colors are almost the same.
Parameters
----------
a: tuple
The first DiffuseColor value to compare.
a: tuple
The second DiffuseColor value to compare.
Returns
-------
bool:
True if colors are different, false if they are similar.
"""
if len(a) != len(b):
return True
for i in range(len(a)):
if abs(sum(a[i]) - sum(b[i])) > 0.00001:
return True
return False | [
"def",
"areDifferentColors",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"return",
"True",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
":",
"if",
"abs",
"(",
"sum",
... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchComponent.py#L1515-L1536 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/PRESUBMIT.py | python | _CheckMacroUndefs | (input_api, output_api) | return [] | Checks that each #define in a .cc file is eventually followed by an #undef.
TODO(clemensh): This check should eventually be enabled for all cc files via
tools/presubmit.py (https://crbug.com/v8/6811). | Checks that each #define in a .cc file is eventually followed by an #undef. | [
"Checks",
"that",
"each",
"#define",
"in",
"a",
".",
"cc",
"file",
"is",
"eventually",
"followed",
"by",
"an",
"#undef",
"."
] | def _CheckMacroUndefs(input_api, output_api):
"""
Checks that each #define in a .cc file is eventually followed by an #undef.
TODO(clemensh): This check should eventually be enabled for all cc files via
tools/presubmit.py (https://crbug.com/v8/6811).
"""
def FilterFile(affected_file):
# Skip header files, as they often define type lists which are used in
# other files.
white_list = (r'.+\.cc',r'.+\.cpp',r'.+\.c')
return input_api.FilterSourceFile(affected_file, white_list=white_list)
def TouchesMacros(f):
for line in f.GenerateScmDiff().splitlines():
if not line.startswith('+') and not line.startswith('-'):
continue
if define_pattern.match(line[1:]) or undef_pattern.match(line[1:]):
return True
return False
define_pattern = input_api.re.compile(r'#define (\w+)')
undef_pattern = input_api.re.compile(r'#undef (\w+)')
errors = []
for f in input_api.AffectedFiles(
file_filter=FilterFile, include_deletes=False):
if not TouchesMacros(f):
continue
defined_macros = dict()
with open(f.LocalPath()) as fh:
line_nr = 0
for line in fh:
line_nr += 1
define_match = define_pattern.match(line)
if define_match:
name = define_match.group(1)
defined_macros[name] = line_nr
undef_match = undef_pattern.match(line)
if undef_match:
if "// NOLINT" in line:
continue
name = undef_match.group(1)
if not name in defined_macros:
errors.append('{}:{}: Macro named \'{}\' was not defined before.'
.format(f.LocalPath(), line_nr, name))
else:
del defined_macros[name]
for name, line_nr in sorted(defined_macros.items(), key=lambda e: e[1]):
errors.append('{}:{}: Macro missing #undef: {}'
.format(f.LocalPath(), line_nr, name))
if errors:
return [output_api.PresubmitPromptOrNotify(
'Detected mismatches in #define / #undef in the file(s) where you '
'modified preprocessor macros.',
errors)]
return [] | [
"def",
"_CheckMacroUndefs",
"(",
"input_api",
",",
"output_api",
")",
":",
"def",
"FilterFile",
"(",
"affected_file",
")",
":",
"# Skip header files, as they often define type lists which are used in",
"# other files.",
"white_list",
"=",
"(",
"r'.+\\.cc'",
",",
"r'.+\\.cpp... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/PRESUBMIT.py#L394-L453 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/virtualenv.py | python | VirtualenvManager.install_pip_package | (self, package) | return self._run_pip(args) | Install a package via pip.
The supplied package is specified using a pip requirement specifier.
e.g. 'foo' or 'foo==1.0'.
If the package is already installed, this is a no-op. | Install a package via pip. | [
"Install",
"a",
"package",
"via",
"pip",
"."
] | def install_pip_package(self, package):
"""Install a package via pip.
The supplied package is specified using a pip requirement specifier.
e.g. 'foo' or 'foo==1.0'.
If the package is already installed, this is a no-op.
"""
from pip.req import InstallRequirement
req = InstallRequirement.from_line(package)
if req.check_if_exists():
return
args = [
'install',
'--use-wheel',
package,
]
return self._run_pip(args) | [
"def",
"install_pip_package",
"(",
"self",
",",
"package",
")",
":",
"from",
"pip",
".",
"req",
"import",
"InstallRequirement",
"req",
"=",
"InstallRequirement",
".",
"from_line",
"(",
"package",
")",
"if",
"req",
".",
"check_if_exists",
"(",
")",
":",
"retu... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/virtualenv.py#L401-L421 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/util/__init__.py | python | SetOutputWholeExtent | (algorithm, extent) | Convenience method to help set the WHOLE_EXTENT() in RequestInformation.
Commonly used by programmable filters. The arguments are the algorithm
and a tuple/list with 6 elements (xmin, xmax, ymin, ymax, zmin, zmax).
Example use::
import paraview.util
# The output will be of dimensions 10, 1, 1
paraview.util.SetOutputWholeExtent(algorithm, (0, 9, 0, 0, 0, 0) | Convenience method to help set the WHOLE_EXTENT() in RequestInformation.
Commonly used by programmable filters. The arguments are the algorithm
and a tuple/list with 6 elements (xmin, xmax, ymin, ymax, zmin, zmax). | [
"Convenience",
"method",
"to",
"help",
"set",
"the",
"WHOLE_EXTENT",
"()",
"in",
"RequestInformation",
".",
"Commonly",
"used",
"by",
"programmable",
"filters",
".",
"The",
"arguments",
"are",
"the",
"algorithm",
"and",
"a",
"tuple",
"/",
"list",
"with",
"6",
... | def SetOutputWholeExtent(algorithm, extent):
"""
Convenience method to help set the WHOLE_EXTENT() in RequestInformation.
Commonly used by programmable filters. The arguments are the algorithm
and a tuple/list with 6 elements (xmin, xmax, ymin, ymax, zmin, zmax).
Example use::
import paraview.util
# The output will be of dimensions 10, 1, 1
paraview.util.SetOutputWholeExtent(algorithm, (0, 9, 0, 0, 0, 0)
"""
if len(extent) != 6:
raise "Expected a sequence of length 6"
from vtkmodules.vtkCommonExecutionModel import vtkStreamingDemandDrivenPipeline
algorithm.GetExecutive().GetOutputInformation(0).Set(vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT(), extent[0], extent[1], extent[2],extent[3], extent[4], extent[5]) | [
"def",
"SetOutputWholeExtent",
"(",
"algorithm",
",",
"extent",
")",
":",
"if",
"len",
"(",
"extent",
")",
"!=",
"6",
":",
"raise",
"\"Expected a sequence of length 6\"",
"from",
"vtkmodules",
".",
"vtkCommonExecutionModel",
"import",
"vtkStreamingDemandDrivenPipeline",... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/util/__init__.py#L4-L19 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/estimators/estimator.py | python | Estimator._call_model_fn | (self, features, labels, mode, metrics=None) | return model_fn_ops | Calls model function with support of 2, 3 or 4 arguments.
Args:
features: features dict.
labels: labels dict.
mode: ModeKeys
metrics: Dict of metrics.
Returns:
A `ModelFnOps` object. If model_fn returns a tuple, wraps them up in a
`ModelFnOps` object.
Raises:
ValueError: if model_fn returns invalid objects. | Calls model function with support of 2, 3 or 4 arguments. | [
"Calls",
"model",
"function",
"with",
"support",
"of",
"2",
"3",
"or",
"4",
"arguments",
"."
] | def _call_model_fn(self, features, labels, mode, metrics=None):
"""Calls model function with support of 2, 3 or 4 arguments.
Args:
features: features dict.
labels: labels dict.
mode: ModeKeys
metrics: Dict of metrics.
Returns:
A `ModelFnOps` object. If model_fn returns a tuple, wraps them up in a
`ModelFnOps` object.
Raises:
ValueError: if model_fn returns invalid objects.
"""
features, labels = self._feature_engineering_fn(features, labels)
model_fn_args = _model_fn_args(self._model_fn)
kwargs = {}
if 'mode' in model_fn_args:
kwargs['mode'] = mode
if 'params' in model_fn_args:
kwargs['params'] = self.params
if 'config' in model_fn_args:
kwargs['config'] = self.config
if 'model_dir' in model_fn_args:
kwargs['model_dir'] = self.model_dir
model_fn_results = self._model_fn(features, labels, **kwargs)
if isinstance(model_fn_results, model_fn_lib.ModelFnOps):
model_fn_ops = model_fn_results
else:
# Here model_fn_results should be a tuple with 3 elements.
if len(model_fn_results) != 3:
raise ValueError('Unrecognized value returned by model_fn, '
'please return ModelFnOps.')
model_fn_ops = model_fn_lib.ModelFnOps(
mode=mode,
predictions=model_fn_results[0],
loss=model_fn_results[1],
train_op=model_fn_results[2])
# Custom metrics should overwrite defaults.
if metrics:
model_fn_ops.eval_metric_ops.update(_make_metrics_ops(
metrics, features, labels, model_fn_ops.predictions))
return model_fn_ops | [
"def",
"_call_model_fn",
"(",
"self",
",",
"features",
",",
"labels",
",",
"mode",
",",
"metrics",
"=",
"None",
")",
":",
"features",
",",
"labels",
"=",
"self",
".",
"_feature_engineering_fn",
"(",
"features",
",",
"labels",
")",
"model_fn_args",
"=",
"_m... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L1138-L1185 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/smtplib.py | python | quoteaddr | (addr) | Quote a subset of the email addresses defined by RFC 821.
Should be able to handle anything rfc822.parseaddr can handle. | Quote a subset of the email addresses defined by RFC 821. | [
"Quote",
"a",
"subset",
"of",
"the",
"email",
"addresses",
"defined",
"by",
"RFC",
"821",
"."
] | def quoteaddr(addr):
"""Quote a subset of the email addresses defined by RFC 821.
Should be able to handle anything rfc822.parseaddr can handle.
"""
m = (None, None)
try:
m = email.utils.parseaddr(addr)[1]
except AttributeError:
pass
if m == (None, None): # Indicates parse failure or AttributeError
# something weird here.. punt -ddm
return "<%s>" % addr
elif m is None:
# the sender wants an empty return address
return "<>"
else:
return "<%s>" % m | [
"def",
"quoteaddr",
"(",
"addr",
")",
":",
"m",
"=",
"(",
"None",
",",
"None",
")",
"try",
":",
"m",
"=",
"email",
".",
"utils",
".",
"parseaddr",
"(",
"addr",
")",
"[",
"1",
"]",
"except",
"AttributeError",
":",
"pass",
"if",
"m",
"==",
"(",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/smtplib.py#L133-L150 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py | python | MaildirMessage.set_flags | (self, flags) | Set the given flags and unset all others. | Set the given flags and unset all others. | [
"Set",
"the",
"given",
"flags",
"and",
"unset",
"all",
"others",
"."
] | def set_flags(self, flags):
"""Set the given flags and unset all others."""
self._info = '2,' + ''.join(sorted(flags)) | [
"def",
"set_flags",
"(",
"self",
",",
"flags",
")",
":",
"self",
".",
"_info",
"=",
"'2,'",
"+",
"''",
".",
"join",
"(",
"sorted",
"(",
"flags",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L1499-L1501 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | MaskedArray.__iadd__ | (self, other) | return self | Add other to self in place. | Add other to self in place. | [
"Add",
"other",
"to",
"self",
"in",
"place",
"."
] | def __iadd__(self, other):
"Add other to self in place."
t = self._data.dtype.char
f = filled(other, 0)
t1 = f.dtype.char
if t == t1:
pass
elif t in typecodes['Integer']:
if t1 in typecodes['Integer']:
f = f.astype(t)
else:
raise TypeError('Incorrect type for in-place operation.')
elif t in typecodes['Float']:
if t1 in typecodes['Integer']:
f = f.astype(t)
elif t1 in typecodes['Float']:
f = f.astype(t)
else:
raise TypeError('Incorrect type for in-place operation.')
elif t in typecodes['Complex']:
if t1 in typecodes['Integer']:
f = f.astype(t)
elif t1 in typecodes['Float']:
f = f.astype(t)
elif t1 in typecodes['Complex']:
f = f.astype(t)
else:
raise TypeError('Incorrect type for in-place operation.')
else:
raise TypeError('Incorrect type for in-place operation.')
if self._mask is nomask:
self._data += f
m = getmask(other)
self._mask = m
self._shared_mask = m is not nomask
else:
result = add(self, masked_array(f, mask=getmask(other)))
self._data = result.data
self._mask = result.mask
self._shared_mask = 1
return self | [
"def",
"__iadd__",
"(",
"self",
",",
"other",
")",
":",
"t",
"=",
"self",
".",
"_data",
".",
"dtype",
".",
"char",
"f",
"=",
"filled",
"(",
"other",
",",
"0",
")",
"t1",
"=",
"f",
".",
"dtype",
".",
"char",
"if",
"t",
"==",
"t1",
":",
"pass",... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L989-L1030 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/format.py | python | FormatRegion.tabify_region_event | (self, event=None) | return "break" | Convert leading spaces to tabs for each line in selected region. | Convert leading spaces to tabs for each line in selected region. | [
"Convert",
"leading",
"spaces",
"to",
"tabs",
"for",
"each",
"line",
"in",
"selected",
"region",
"."
] | def tabify_region_event(self, event=None):
"Convert leading spaces to tabs for each line in selected region."
head, tail, chars, lines = self.get_region()
tabwidth = self._asktabwidth()
if tabwidth is None:
return
for pos in range(len(lines)):
line = lines[pos]
if line:
raw, effective = get_line_indent(line, tabwidth)
ntabs, nspaces = divmod(effective, tabwidth)
lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
self.set_region(head, tail, chars, lines)
return "break" | [
"def",
"tabify_region_event",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"head",
",",
"tail",
",",
"chars",
",",
"lines",
"=",
"self",
".",
"get_region",
"(",
")",
"tabwidth",
"=",
"self",
".",
"_asktabwidth",
"(",
")",
"if",
"tabwidth",
"is",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/format.py#L319-L332 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/utils/sparsefuncs.py | python | mean_variance_axis | (X, axis) | Compute mean and variance along an axix on a CSR or CSC matrix
Parameters
----------
X : CSR or CSC sparse matrix, shape (n_samples, n_features)
Input data.
axis : int (either 0 or 1)
Axis along which the axis should be computed.
Returns
-------
means : float array with shape (n_features,)
Feature-wise means
variances : float array with shape (n_features,)
Feature-wise variances | Compute mean and variance along an axix on a CSR or CSC matrix | [
"Compute",
"mean",
"and",
"variance",
"along",
"an",
"axix",
"on",
"a",
"CSR",
"or",
"CSC",
"matrix"
] | def mean_variance_axis(X, axis):
"""Compute mean and variance along an axix on a CSR or CSC matrix
Parameters
----------
X : CSR or CSC sparse matrix, shape (n_samples, n_features)
Input data.
axis : int (either 0 or 1)
Axis along which the axis should be computed.
Returns
-------
means : float array with shape (n_features,)
Feature-wise means
variances : float array with shape (n_features,)
Feature-wise variances
"""
_raise_error_wrong_axis(axis)
if isinstance(X, sp.csr_matrix):
if axis == 0:
return _csr_mean_var_axis0(X)
else:
return _csc_mean_var_axis0(X.T)
elif isinstance(X, sp.csc_matrix):
if axis == 0:
return _csc_mean_var_axis0(X)
else:
return _csr_mean_var_axis0(X.T)
else:
_raise_typeerror(X) | [
"def",
"mean_variance_axis",
"(",
"X",
",",
"axis",
")",
":",
"_raise_error_wrong_axis",
"(",
"axis",
")",
"if",
"isinstance",
"(",
"X",
",",
"sp",
".",
"csr_matrix",
")",
":",
"if",
"axis",
"==",
"0",
":",
"return",
"_csr_mean_var_axis0",
"(",
"X",
")",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/sparsefuncs.py#L64-L98 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/graph_editor/transform.py | python | transform_op_in_place | (info, op, detach_outputs=False) | return op | Transform a op in-place - experimental!
Transform an operation in place. It reconnects the inputs if they have been
modified. if detach_outputs is True, the outputs of op are also detached.
Args:
info: Transform._Info instance.
op: the op to transform in place.
detach_outputs: if True, the outputs of op are detached, ready for the user
to add more operation.
Returns:
The transformed op. | Transform a op in-place - experimental! | [
"Transform",
"a",
"op",
"in",
"-",
"place",
"-",
"experimental!"
] | def transform_op_in_place(info, op, detach_outputs=False):
"""Transform a op in-place - experimental!
Transform an operation in place. It reconnects the inputs if they have been
modified. if detach_outputs is True, the outputs of op are also detached.
Args:
info: Transform._Info instance.
op: the op to transform in place.
detach_outputs: if True, the outputs of op are detached, ready for the user
to add more operation.
Returns:
The transformed op.
"""
# recursive call to the inputs:
inputs = [info.transformer._transform_t(t) # pylint: disable=protected-access
for t in op.inputs]
# re-connect to the inputs if they have changed:
if inputs != list(op.inputs):
reroute.reroute_a2b_ts(inputs, op.inputs)
# detach op from its consumer first ?
if detach_outputs:
edit.detach_outputs(op)
return op | [
"def",
"transform_op_in_place",
"(",
"info",
",",
"op",
",",
"detach_outputs",
"=",
"False",
")",
":",
"# recursive call to the inputs:",
"inputs",
"=",
"[",
"info",
".",
"transformer",
".",
"_transform_t",
"(",
"t",
")",
"# pylint: disable=protected-access",
"for",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/transform.py#L186-L209 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/saved_model/builder_impl.py | python | _maybe_save_assets | (assets_collection_to_add=None) | return asset_source_filepath_list | Saves assets to the meta graph.
Args:
assets_collection_to_add: The collection where the asset paths are setup.
Returns:
The list of filepaths to the assets in the assets collection.
Raises:
ValueError: Indicating an invalid filepath tensor. | Saves assets to the meta graph. | [
"Saves",
"assets",
"to",
"the",
"meta",
"graph",
"."
] | def _maybe_save_assets(assets_collection_to_add=None):
"""Saves assets to the meta graph.
Args:
assets_collection_to_add: The collection where the asset paths are setup.
Returns:
The list of filepaths to the assets in the assets collection.
Raises:
ValueError: Indicating an invalid filepath tensor.
"""
asset_source_filepath_list = []
if assets_collection_to_add is None:
tf_logging.info("No assets to save.")
return asset_source_filepath_list
# Iterate over the supplied asset collection, build the `AssetFile` proto
# and add them to the collection with key `constants.ASSETS_KEY`, in the
# graph.
for asset_tensor in assets_collection_to_add:
asset_source_filepath = _asset_path_from_tensor(asset_tensor)
if not asset_source_filepath:
raise ValueError("Invalid asset filepath tensor %s" % asset_tensor)
asset_source_filename = os.path.basename(asset_source_filepath)
# Build `AssetFile` proto and add it to the asset collection in the graph.
_add_asset_to_collection(asset_source_filename, asset_tensor)
asset_source_filepath_list.append(asset_source_filepath)
tf_logging.info("Assets added to graph.")
return asset_source_filepath_list | [
"def",
"_maybe_save_assets",
"(",
"assets_collection_to_add",
"=",
"None",
")",
":",
"asset_source_filepath_list",
"=",
"[",
"]",
"if",
"assets_collection_to_add",
"is",
"None",
":",
"tf_logging",
".",
"info",
"(",
"\"No assets to save.\"",
")",
"return",
"asset_sourc... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/saved_model/builder_impl.py#L421-L455 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/io/mmio.py | python | MMFile._init_attrs | (self, **kwargs) | Initialize each attributes with the corresponding keyword arg value
or a default of None | Initialize each attributes with the corresponding keyword arg value
or a default of None | [
"Initialize",
"each",
"attributes",
"with",
"the",
"corresponding",
"keyword",
"arg",
"value",
"or",
"a",
"default",
"of",
"None"
] | def _init_attrs(self, **kwargs):
"""
Initialize each attributes with the corresponding keyword arg value
or a default of None
"""
attrs = self.__class__.__slots__
public_attrs = [attr[1:] for attr in attrs]
invalid_keys = set(kwargs.keys()) - set(public_attrs)
if invalid_keys:
raise ValueError('''found %s invalid keyword arguments, please only
use %s''' % (tuple(invalid_keys),
public_attrs))
for attr in attrs:
setattr(self, attr, kwargs.get(attr[1:], None)) | [
"def",
"_init_attrs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"self",
".",
"__class__",
".",
"__slots__",
"public_attrs",
"=",
"[",
"attr",
"[",
"1",
":",
"]",
"for",
"attr",
"in",
"attrs",
"]",
"invalid_keys",
"=",
"set",
"(",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/mmio.py#L457-L473 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TNEANet.EndNI | (self, *args) | return _snap.TNEANet_EndNI(self, *args) | EndNI(TNEANet self) -> TNEANet::TNodeI
EndNI(TNEANet self) -> TNEANetNodeI
Parameters:
self: TNEANet * | EndNI(TNEANet self) -> TNEANet::TNodeI
EndNI(TNEANet self) -> TNEANetNodeI | [
"EndNI",
"(",
"TNEANet",
"self",
")",
"-",
">",
"TNEANet",
"::",
"TNodeI",
"EndNI",
"(",
"TNEANet",
"self",
")",
"-",
">",
"TNEANetNodeI"
] | def EndNI(self, *args):
"""
EndNI(TNEANet self) -> TNEANet::TNodeI
EndNI(TNEANet self) -> TNEANetNodeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_EndNI(self, *args) | [
"def",
"EndNI",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TNEANet_EndNI",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L22527-L22536 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.