nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | Grid.GetDefaultCellOverflow | (*args, **kwargs) | return _grid.Grid_GetDefaultCellOverflow(*args, **kwargs) | GetDefaultCellOverflow(self) -> bool | GetDefaultCellOverflow(self) -> bool | [
"GetDefaultCellOverflow",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetDefaultCellOverflow(*args, **kwargs):
"""GetDefaultCellOverflow(self) -> bool"""
return _grid.Grid_GetDefaultCellOverflow(*args, **kwargs) | [
"def",
"GetDefaultCellOverflow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetDefaultCellOverflow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L1802-L1804 | |
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | python/dolfinx/fem/function.py | python | Expression.code | (self) | return self._code | C code strings | C code strings | [
"C",
"code",
"strings"
] | def code(self) -> str:
"""C code strings"""
return self._code | [
"def",
"code",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_code"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/function.py#L208-L210 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/name_expansion.py | python | _NameExpansionIterator.WildcardIterator | (self, url_string) | return gslib.wildcard_iterator.CreateWildcardIterator(
url_string, self.gsutil_api, debug=self.debug,
all_versions=self.all_versions,
project_id=self.project_id) | Helper to instantiate gslib.WildcardIterator.
Args are same as gslib.WildcardIterator interface, but this method fills
in most of the values from instance state.
Args:
url_string: URL string naming wildcard objects to iterate.
Returns:
Wildcard iterator over URL string. | Helper to instantiate gslib.WildcardIterator. | [
"Helper",
"to",
"instantiate",
"gslib",
".",
"WildcardIterator",
"."
] | def WildcardIterator(self, url_string):
"""Helper to instantiate gslib.WildcardIterator.
Args are same as gslib.WildcardIterator interface, but this method fills
in most of the values from instance state.
Args:
url_string: URL string naming wildcard objects to iterate.
Returns:
Wildcard iterator over URL string.
"""
return gslib.wildcard_iterator.CreateWildcardIterator(
url_string, self.gsutil_api, debug=self.debug,
all_versions=self.all_versions,
project_id=self.project_id) | [
"def",
"WildcardIterator",
"(",
"self",
",",
"url_string",
")",
":",
"return",
"gslib",
".",
"wildcard_iterator",
".",
"CreateWildcardIterator",
"(",
"url_string",
",",
"self",
".",
"gsutil_api",
",",
"debug",
"=",
"self",
".",
"debug",
",",
"all_versions",
"=",
"self",
".",
"all_versions",
",",
"project_id",
"=",
"self",
".",
"project_id",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/name_expansion.py#L282-L297 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/glob.py | python | iglob | (pathname) | Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns. | Return an iterator which yields the paths matching a pathname pattern. | [
"Return",
"an",
"iterator",
"which",
"yields",
"the",
"paths",
"matching",
"a",
"pathname",
"pattern",
"."
] | def iglob(pathname):
"""Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
"""
dirname, basename = os.path.split(pathname)
if not has_magic(pathname):
if basename:
if os.path.lexists(pathname):
yield pathname
else:
# Patterns ending with a slash should match only directories
if os.path.isdir(dirname):
yield pathname
return
if not dirname:
for name in glob1(os.curdir, basename):
yield name
return
# `os.path.split()` returns the argument itself as a dirname if it is a
# drive or UNC path. Prevent an infinite recursion if a drive or UNC path
# contains magic characters (i.e. r'\\?\C:').
if dirname != pathname and has_magic(dirname):
dirs = iglob(dirname)
else:
dirs = [dirname]
if has_magic(basename):
glob_in_dir = glob1
else:
glob_in_dir = glob0
for dirname in dirs:
for name in glob_in_dir(dirname, basename):
yield os.path.join(dirname, name) | [
"def",
"iglob",
"(",
"pathname",
")",
":",
"dirname",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"pathname",
")",
"if",
"not",
"has_magic",
"(",
"pathname",
")",
":",
"if",
"basename",
":",
"if",
"os",
".",
"path",
".",
"lexists",
"(",
"pathname",
")",
":",
"yield",
"pathname",
"else",
":",
"# Patterns ending with a slash should match only directories",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"yield",
"pathname",
"return",
"if",
"not",
"dirname",
":",
"for",
"name",
"in",
"glob1",
"(",
"os",
".",
"curdir",
",",
"basename",
")",
":",
"yield",
"name",
"return",
"# `os.path.split()` returns the argument itself as a dirname if it is a",
"# drive or UNC path. Prevent an infinite recursion if a drive or UNC path",
"# contains magic characters (i.e. r'\\\\?\\C:').",
"if",
"dirname",
"!=",
"pathname",
"and",
"has_magic",
"(",
"dirname",
")",
":",
"dirs",
"=",
"iglob",
"(",
"dirname",
")",
"else",
":",
"dirs",
"=",
"[",
"dirname",
"]",
"if",
"has_magic",
"(",
"basename",
")",
":",
"glob_in_dir",
"=",
"glob1",
"else",
":",
"glob_in_dir",
"=",
"glob0",
"for",
"dirname",
"in",
"dirs",
":",
"for",
"name",
"in",
"glob_in_dir",
"(",
"dirname",
",",
"basename",
")",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"name",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/glob.py#L29-L65 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/xrc.py | python | XmlDocument.LoadFromStream | (*args, **kwargs) | return _xrc.XmlDocument_LoadFromStream(*args, **kwargs) | LoadFromStream(self, InputStream stream, String encoding=UTF8String, int flags=XMLDOC_NONE) -> bool | LoadFromStream(self, InputStream stream, String encoding=UTF8String, int flags=XMLDOC_NONE) -> bool | [
"LoadFromStream",
"(",
"self",
"InputStream",
"stream",
"String",
"encoding",
"=",
"UTF8String",
"int",
"flags",
"=",
"XMLDOC_NONE",
")",
"-",
">",
"bool"
] | def LoadFromStream(*args, **kwargs):
"""LoadFromStream(self, InputStream stream, String encoding=UTF8String, int flags=XMLDOC_NONE) -> bool"""
return _xrc.XmlDocument_LoadFromStream(*args, **kwargs) | [
"def",
"LoadFromStream",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlDocument_LoadFromStream",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L519-L521 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/swgbcc/ability_subprocessor.py | python | SWGBCCAbilitySubprocessor.death_ability | (line) | return ability_forward_ref | Adds the Death ability to a line that is used to make entities die.
:param line: Unit/Building line that gets the ability.
:type line: ...dataformat.converter_object.ConverterObjectGroup
:returns: The forward reference for the ability.
:rtype: ...dataformat.forward_ref.ForwardRef | Adds the Death ability to a line that is used to make entities die. | [
"Adds",
"the",
"Death",
"ability",
"to",
"a",
"line",
"that",
"is",
"used",
"to",
"make",
"entities",
"die",
"."
] | def death_ability(line):
"""
Adds the Death ability to a line that is used to make entities die.
:param line: Unit/Building line that gets the ability.
:type line: ...dataformat.converter_object.ConverterObjectGroup
:returns: The forward reference for the ability.
:rtype: ...dataformat.forward_ref.ForwardRef
"""
ability_forward_ref = AoCAbilitySubprocessor.death_ability(line)
# TODO: Implement diffing of civ lines
return ability_forward_ref | [
"def",
"death_ability",
"(",
"line",
")",
":",
"ability_forward_ref",
"=",
"AoCAbilitySubprocessor",
".",
"death_ability",
"(",
"line",
")",
"# TODO: Implement diffing of civ lines",
"return",
"ability_forward_ref"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/swgbcc/ability_subprocessor.py#L500-L513 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/filters.py | python | do_urlencode | (
value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]
) | return "&".join(
f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
) | Quote data for use in a URL path or query using UTF-8.
Basic wrapper around :func:`urllib.parse.quote` when given a
string, or :func:`urllib.parse.urlencode` for a dict or iterable.
:param value: Data to quote. A string will be quoted directly. A
dict or iterable of ``(key, value)`` pairs will be joined as a
query string.
When given a string, "/" is not quoted. HTTP servers treat "/" and
"%2F" equivalently in paths. If you need quoted slashes, use the
``|replace("/", "%2F")`` filter.
.. versionadded:: 2.7 | Quote data for use in a URL path or query using UTF-8. | [
"Quote",
"data",
"for",
"use",
"in",
"a",
"URL",
"path",
"or",
"query",
"using",
"UTF",
"-",
"8",
"."
] | def do_urlencode(
value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]
) -> str:
"""Quote data for use in a URL path or query using UTF-8.
Basic wrapper around :func:`urllib.parse.quote` when given a
string, or :func:`urllib.parse.urlencode` for a dict or iterable.
:param value: Data to quote. A string will be quoted directly. A
dict or iterable of ``(key, value)`` pairs will be joined as a
query string.
When given a string, "/" is not quoted. HTTP servers treat "/" and
"%2F" equivalently in paths. If you need quoted slashes, use the
``|replace("/", "%2F")`` filter.
.. versionadded:: 2.7
"""
if isinstance(value, str) or not isinstance(value, abc.Iterable):
return url_quote(value)
if isinstance(value, dict):
items: t.Iterable[t.Tuple[str, t.Any]] = value.items()
else:
items = value # type: ignore
return "&".join(
f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
) | [
"def",
"do_urlencode",
"(",
"value",
":",
"t",
".",
"Union",
"[",
"str",
",",
"t",
".",
"Mapping",
"[",
"str",
",",
"t",
".",
"Any",
"]",
",",
"t",
".",
"Iterable",
"[",
"t",
".",
"Tuple",
"[",
"str",
",",
"t",
".",
"Any",
"]",
"]",
"]",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
"or",
"not",
"isinstance",
"(",
"value",
",",
"abc",
".",
"Iterable",
")",
":",
"return",
"url_quote",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"items",
":",
"t",
".",
"Iterable",
"[",
"t",
".",
"Tuple",
"[",
"str",
",",
"t",
".",
"Any",
"]",
"]",
"=",
"value",
".",
"items",
"(",
")",
"else",
":",
"items",
"=",
"value",
"# type: ignore",
"return",
"\"&\"",
".",
"join",
"(",
"f\"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}\"",
"for",
"k",
",",
"v",
"in",
"items",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L197-L225 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_workflow/command_interface.py | python | ReductionSingleton.__getattr__ | (self, attr) | return getattr(self.__instance, attr) | Delegate access to implementation | Delegate access to implementation | [
"Delegate",
"access",
"to",
"implementation"
] | def __getattr__(self, attr):
""" Delegate access to implementation """
return getattr(self.__instance, attr) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"__instance",
",",
"attr",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_workflow/command_interface.py#L61-L63 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/stats.py | python | f_value_multivariate | (ER, EF, dfnum, dfden) | return n_um / d_en | Returns a multivariate F-statistic.
Parameters
----------
ER : ndarray
Error associated with the null hypothesis (the Restricted model).
From a multivariate F calculation.
EF : ndarray
Error associated with the alternate hypothesis (the Full model)
From a multivariate F calculation.
dfnum : int
Degrees of freedom the Restricted model.
dfden : int
Degrees of freedom associated with the Restricted model.
Returns
-------
fstat : float
The computed F-statistic. | Returns a multivariate F-statistic. | [
"Returns",
"a",
"multivariate",
"F",
"-",
"statistic",
"."
] | def f_value_multivariate(ER, EF, dfnum, dfden):
"""
Returns a multivariate F-statistic.
Parameters
----------
ER : ndarray
Error associated with the null hypothesis (the Restricted model).
From a multivariate F calculation.
EF : ndarray
Error associated with the alternate hypothesis (the Full model)
From a multivariate F calculation.
dfnum : int
Degrees of freedom the Restricted model.
dfden : int
Degrees of freedom associated with the Restricted model.
Returns
-------
fstat : float
The computed F-statistic.
"""
if isinstance(ER, (int, float)):
ER = array([[ER]])
if isinstance(EF, (int, float)):
EF = array([[EF]])
n_um = (linalg.det(ER) - linalg.det(EF)) / float(dfnum)
d_en = linalg.det(EF) / float(dfden)
return n_um / d_en | [
"def",
"f_value_multivariate",
"(",
"ER",
",",
"EF",
",",
"dfnum",
",",
"dfden",
")",
":",
"if",
"isinstance",
"(",
"ER",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"ER",
"=",
"array",
"(",
"[",
"[",
"ER",
"]",
"]",
")",
"if",
"isinstance",
"(",
"EF",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"EF",
"=",
"array",
"(",
"[",
"[",
"EF",
"]",
"]",
")",
"n_um",
"=",
"(",
"linalg",
".",
"det",
"(",
"ER",
")",
"-",
"linalg",
".",
"det",
"(",
"EF",
")",
")",
"/",
"float",
"(",
"dfnum",
")",
"d_en",
"=",
"linalg",
".",
"det",
"(",
"EF",
")",
"/",
"float",
"(",
"dfden",
")",
"return",
"n_um",
"/",
"d_en"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L5142-L5171 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | BooleanParser.Convert | (self, argument) | Converts the argument to a boolean; raise ValueError on errors. | Converts the argument to a boolean; raise ValueError on errors. | [
"Converts",
"the",
"argument",
"to",
"a",
"boolean",
";",
"raise",
"ValueError",
"on",
"errors",
"."
] | def Convert(self, argument):
"""Converts the argument to a boolean; raise ValueError on errors."""
if type(argument) == str:
if argument.lower() in ['true', 't', '1']:
return True
elif argument.lower() in ['false', 'f', '0']:
return False
bool_argument = bool(argument)
if argument == bool_argument:
# The argument is a valid boolean (True, False, 0, or 1), and not just
# something that always converts to bool (list, string, int, etc.).
return bool_argument
raise ValueError('Non-boolean argument to boolean flag', argument) | [
"def",
"Convert",
"(",
"self",
",",
"argument",
")",
":",
"if",
"type",
"(",
"argument",
")",
"==",
"str",
":",
"if",
"argument",
".",
"lower",
"(",
")",
"in",
"[",
"'true'",
",",
"'t'",
",",
"'1'",
"]",
":",
"return",
"True",
"elif",
"argument",
".",
"lower",
"(",
")",
"in",
"[",
"'false'",
",",
"'f'",
",",
"'0'",
"]",
":",
"return",
"False",
"bool_argument",
"=",
"bool",
"(",
"argument",
")",
"if",
"argument",
"==",
"bool_argument",
":",
"# The argument is a valid boolean (True, False, 0, or 1), and not just",
"# something that always converts to bool (list, string, int, etc.).",
"return",
"bool_argument",
"raise",
"ValueError",
"(",
"'Non-boolean argument to boolean flag'",
",",
"argument",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L2324-L2338 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | Distribution.__getattr__ | (self, attr) | return getattr(self._provider, attr) | Delegate all unrecognized public attributes to .metadata provider | Delegate all unrecognized public attributes to .metadata provider | [
"Delegate",
"all",
"unrecognized",
"public",
"attributes",
"to",
".",
"metadata",
"provider"
] | def __getattr__(self, attr):
"""Delegate all unrecognized public attributes to .metadata provider"""
if attr.startswith('_'):
raise AttributeError(attr)
return getattr(self._provider, attr) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
".",
"startswith",
"(",
"'_'",
")",
":",
"raise",
"AttributeError",
"(",
"attr",
")",
"return",
"getattr",
"(",
"self",
".",
"_provider",
",",
"attr",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L2728-L2732 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py | python | PtyProcess.isalive | (self) | return False | This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status. | This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status. | [
"This",
"tests",
"if",
"the",
"child",
"process",
"is",
"running",
"or",
"not",
".",
"This",
"is",
"non",
"-",
"blocking",
".",
"If",
"the",
"child",
"was",
"terminated",
"then",
"this",
"will",
"read",
"the",
"exitstatus",
"or",
"signalstatus",
"of",
"the",
"child",
".",
"This",
"returns",
"True",
"if",
"the",
"child",
"process",
"appears",
"to",
"be",
"running",
"or",
"False",
"if",
"not",
".",
"It",
"can",
"take",
"literally",
"SECONDS",
"for",
"Solaris",
"to",
"return",
"the",
"right",
"status",
"."
] | def isalive(self):
'''This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status. '''
if self.terminated:
return False
if self.flag_eof:
# This is for Linux, which requires the blocking form
# of waitpid to get the status of a defunct process.
# This is super-lame. The flag_eof would have been set
# in read_nonblocking(), so this should be safe.
waitpid_options = 0
else:
waitpid_options = os.WNOHANG
try:
pid, status = os.waitpid(self.pid, waitpid_options)
except OSError as e:
# No child processes
if e.errno == errno.ECHILD:
raise PtyProcessError('isalive() encountered condition ' +
'where "terminated" is 0, but there was no child ' +
'process. Did someone else call waitpid() ' +
'on our process?')
else:
raise
# I have to do this twice for Solaris.
# I can't even believe that I figured this out...
# If waitpid() returns 0 it means that no child process
# wishes to report, and the value of status is undefined.
if pid == 0:
try:
### os.WNOHANG) # Solaris!
pid, status = os.waitpid(self.pid, waitpid_options)
except OSError as e: # pragma: no cover
# This should never happen...
if e.errno == errno.ECHILD:
raise PtyProcessError('isalive() encountered condition ' +
'that should never happen. There was no child ' +
'process. Did someone else call waitpid() ' +
'on our process?')
else:
raise
# If pid is still 0 after two calls to waitpid() then the process
# really is alive. This seems to work on all platforms, except for
# Irix which seems to require a blocking call on waitpid or select,
# so I let read_nonblocking take care of this situation
# (unfortunately, this requires waiting through the timeout).
if pid == 0:
return True
if pid == 0:
return True
if os.WIFEXITED(status):
self.status = status
self.exitstatus = os.WEXITSTATUS(status)
self.signalstatus = None
self.terminated = True
elif os.WIFSIGNALED(status):
self.status = status
self.exitstatus = None
self.signalstatus = os.WTERMSIG(status)
self.terminated = True
elif os.WIFSTOPPED(status):
raise PtyProcessError('isalive() encountered condition ' +
'where child process is stopped. This is not ' +
'supported. Is some other process attempting ' +
'job control with our child pid?')
return False | [
"def",
"isalive",
"(",
"self",
")",
":",
"if",
"self",
".",
"terminated",
":",
"return",
"False",
"if",
"self",
".",
"flag_eof",
":",
"# This is for Linux, which requires the blocking form",
"# of waitpid to get the status of a defunct process.",
"# This is super-lame. The flag_eof would have been set",
"# in read_nonblocking(), so this should be safe.",
"waitpid_options",
"=",
"0",
"else",
":",
"waitpid_options",
"=",
"os",
".",
"WNOHANG",
"try",
":",
"pid",
",",
"status",
"=",
"os",
".",
"waitpid",
"(",
"self",
".",
"pid",
",",
"waitpid_options",
")",
"except",
"OSError",
"as",
"e",
":",
"# No child processes",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ECHILD",
":",
"raise",
"PtyProcessError",
"(",
"'isalive() encountered condition '",
"+",
"'where \"terminated\" is 0, but there was no child '",
"+",
"'process. Did someone else call waitpid() '",
"+",
"'on our process?'",
")",
"else",
":",
"raise",
"# I have to do this twice for Solaris.",
"# I can't even believe that I figured this out...",
"# If waitpid() returns 0 it means that no child process",
"# wishes to report, and the value of status is undefined.",
"if",
"pid",
"==",
"0",
":",
"try",
":",
"### os.WNOHANG) # Solaris!",
"pid",
",",
"status",
"=",
"os",
".",
"waitpid",
"(",
"self",
".",
"pid",
",",
"waitpid_options",
")",
"except",
"OSError",
"as",
"e",
":",
"# pragma: no cover",
"# This should never happen...",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ECHILD",
":",
"raise",
"PtyProcessError",
"(",
"'isalive() encountered condition '",
"+",
"'that should never happen. There was no child '",
"+",
"'process. Did someone else call waitpid() '",
"+",
"'on our process?'",
")",
"else",
":",
"raise",
"# If pid is still 0 after two calls to waitpid() then the process",
"# really is alive. This seems to work on all platforms, except for",
"# Irix which seems to require a blocking call on waitpid or select,",
"# so I let read_nonblocking take care of this situation",
"# (unfortunately, this requires waiting through the timeout).",
"if",
"pid",
"==",
"0",
":",
"return",
"True",
"if",
"pid",
"==",
"0",
":",
"return",
"True",
"if",
"os",
".",
"WIFEXITED",
"(",
"status",
")",
":",
"self",
".",
"status",
"=",
"status",
"self",
".",
"exitstatus",
"=",
"os",
".",
"WEXITSTATUS",
"(",
"status",
")",
"self",
".",
"signalstatus",
"=",
"None",
"self",
".",
"terminated",
"=",
"True",
"elif",
"os",
".",
"WIFSIGNALED",
"(",
"status",
")",
":",
"self",
".",
"status",
"=",
"status",
"self",
".",
"exitstatus",
"=",
"None",
"self",
".",
"signalstatus",
"=",
"os",
".",
"WTERMSIG",
"(",
"status",
")",
"self",
".",
"terminated",
"=",
"True",
"elif",
"os",
".",
"WIFSTOPPED",
"(",
"status",
")",
":",
"raise",
"PtyProcessError",
"(",
"'isalive() encountered condition '",
"+",
"'where child process is stopped. This is not '",
"+",
"'supported. Is some other process attempting '",
"+",
"'job control with our child pid?'",
")",
"return",
"False"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L685-L760 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | contrib/src/sceneeditor/seAnimPanel.py | python | LoadAnimPanel.onDestroy | (self, event) | If you have open any thing, please rewrite here! | If you have open any thing, please rewrite here! | [
"If",
"you",
"have",
"open",
"any",
"thing",
"please",
"rewrite",
"here!"
] | def onDestroy(self, event):
messenger.send('AWL_close',[self.nodeName])
'''
If you have open any thing, please rewrite here!
'''
pass | [
"def",
"onDestroy",
"(",
"self",
",",
"event",
")",
":",
"messenger",
".",
"send",
"(",
"'AWL_close'",
",",
"[",
"self",
".",
"nodeName",
"]",
")",
"pass"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/contrib/src/sceneeditor/seAnimPanel.py#L539-L544 | ||
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/tools/scan-build-py/libscanbuild/analyze.py | python | filter_debug_flags | (opts, continuation=run_analyzer) | return continuation(opts) | Filter out nondebug macros when requested. | Filter out nondebug macros when requested. | [
"Filter",
"out",
"nondebug",
"macros",
"when",
"requested",
"."
] | def filter_debug_flags(opts, continuation=run_analyzer):
""" Filter out nondebug macros when requested. """
if opts.pop('force_debug'):
# lazy implementation just append an undefine macro at the end
opts.update({'flags': opts['flags'] + ['-UNDEBUG']})
return continuation(opts) | [
"def",
"filter_debug_flags",
"(",
"opts",
",",
"continuation",
"=",
"run_analyzer",
")",
":",
"if",
"opts",
".",
"pop",
"(",
"'force_debug'",
")",
":",
"# lazy implementation just append an undefine macro at the end",
"opts",
".",
"update",
"(",
"{",
"'flags'",
":",
"opts",
"[",
"'flags'",
"]",
"+",
"[",
"'-UNDEBUG'",
"]",
"}",
")",
"return",
"continuation",
"(",
"opts",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/tools/scan-build-py/libscanbuild/analyze.py#L411-L418 | |
mickem/nscp | 79f89fdbb6da63f91bc9dedb7aea202fe938f237 | scripts/python/lib/google/protobuf/internal/cpp_message.py | python | CompositeProperty | (cdescriptor, message_type) | return property(Getter) | Returns a Python property the given composite field. | Returns a Python property the given composite field. | [
"Returns",
"a",
"Python",
"property",
"the",
"given",
"composite",
"field",
"."
] | def CompositeProperty(cdescriptor, message_type):
"""Returns a Python property the given composite field."""
def Getter(self):
sub_message = self._composite_fields.get(cdescriptor.name, None)
if sub_message is None:
cmessage = self._cmsg.NewSubMessage(cdescriptor)
sub_message = message_type._concrete_class(__cmessage=cmessage)
self._composite_fields[cdescriptor.name] = sub_message
return sub_message
return property(Getter) | [
"def",
"CompositeProperty",
"(",
"cdescriptor",
",",
"message_type",
")",
":",
"def",
"Getter",
"(",
"self",
")",
":",
"sub_message",
"=",
"self",
".",
"_composite_fields",
".",
"get",
"(",
"cdescriptor",
".",
"name",
",",
"None",
")",
"if",
"sub_message",
"is",
"None",
":",
"cmessage",
"=",
"self",
".",
"_cmsg",
".",
"NewSubMessage",
"(",
"cdescriptor",
")",
"sub_message",
"=",
"message_type",
".",
"_concrete_class",
"(",
"__cmessage",
"=",
"cmessage",
")",
"self",
".",
"_composite_fields",
"[",
"cdescriptor",
".",
"name",
"]",
"=",
"sub_message",
"return",
"sub_message",
"return",
"property",
"(",
"Getter",
")"
] | https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/cpp_message.py#L88-L99 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHandler.py | python | IdleConf.CurrentTheme | (self) | return self.GetOption('main','Theme','name',default='') | Returns the name of the currently active theme | Returns the name of the currently active theme | [
"Returns",
"the",
"name",
"of",
"the",
"currently",
"active",
"theme"
] | def CurrentTheme(self):
"""
Returns the name of the currently active theme
"""
return self.GetOption('main','Theme','name',default='') | [
"def",
"CurrentTheme",
"(",
"self",
")",
":",
"return",
"self",
".",
"GetOption",
"(",
"'main'",
",",
"'Theme'",
",",
"'name'",
",",
"default",
"=",
"''",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHandler.py#L388-L392 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/operator/_abstract_operator.py | python | AbstractOperator.T | (self) | return self.transpose() | Returns the transposed operator | Returns the transposed operator | [
"Returns",
"the",
"transposed",
"operator"
] | def T(self) -> "AbstractOperator":
"""Returns the transposed operator"""
return self.transpose() | [
"def",
"T",
"(",
"self",
")",
"->",
"\"AbstractOperator\"",
":",
"return",
"self",
".",
"transpose",
"(",
")"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/operator/_abstract_operator.py#L62-L64 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/lib.py | python | parse_idl | (idl_path: str, import_directories: List[str]) | return parsed_doc | Parse an IDL file or throw an error. | Parse an IDL file or throw an error. | [
"Parse",
"an",
"IDL",
"file",
"or",
"throw",
"an",
"error",
"."
] | def parse_idl(idl_path: str, import_directories: List[str]) -> syntax.IDLParsedSpec:
"""Parse an IDL file or throw an error."""
parsed_doc = parser.parse(open(idl_path), idl_path, CompilerImportResolver(import_directories))
if parsed_doc.errors:
parsed_doc.errors.dump_errors()
raise ValueError(f"Cannot parse {idl_path}")
return parsed_doc | [
"def",
"parse_idl",
"(",
"idl_path",
":",
"str",
",",
"import_directories",
":",
"List",
"[",
"str",
"]",
")",
"->",
"syntax",
".",
"IDLParsedSpec",
":",
"parsed_doc",
"=",
"parser",
".",
"parse",
"(",
"open",
"(",
"idl_path",
")",
",",
"idl_path",
",",
"CompilerImportResolver",
"(",
"import_directories",
")",
")",
"if",
"parsed_doc",
".",
"errors",
":",
"parsed_doc",
".",
"errors",
".",
"dump_errors",
"(",
")",
"raise",
"ValueError",
"(",
"f\"Cannot parse {idl_path}\"",
")",
"return",
"parsed_doc"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/lib.py#L50-L58 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.put_abs | (self, r, c, ch) | Screen array starts at 1 index. | Screen array starts at 1 index. | [
"Screen",
"array",
"starts",
"at",
"1",
"index",
"."
] | def put_abs (self, r, c, ch):
'''Screen array starts at 1 index.'''
r = constrain (r, 1, self.rows)
c = constrain (c, 1, self.cols)
if isinstance(ch, bytes):
ch = self._decode(ch)[0]
else:
ch = ch[0]
self.w[r-1][c-1] = ch | [
"def",
"put_abs",
"(",
"self",
",",
"r",
",",
"c",
",",
"ch",
")",
":",
"r",
"=",
"constrain",
"(",
"r",
",",
"1",
",",
"self",
".",
"rows",
")",
"c",
"=",
"constrain",
"(",
"c",
",",
"1",
",",
"self",
".",
"cols",
")",
"if",
"isinstance",
"(",
"ch",
",",
"bytes",
")",
":",
"ch",
"=",
"self",
".",
"_decode",
"(",
"ch",
")",
"[",
"0",
"]",
"else",
":",
"ch",
"=",
"ch",
"[",
"0",
"]",
"self",
".",
"w",
"[",
"r",
"-",
"1",
"]",
"[",
"c",
"-",
"1",
"]",
"=",
"ch"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L200-L209 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py | python | BaseContext.Value | (self, typecode_or_type, *args, lock=True) | return Value(typecode_or_type, *args, lock=lock,
ctx=self.get_context()) | Returns a synchronized shared object | Returns a synchronized shared object | [
"Returns",
"a",
"synchronized",
"shared",
"object"
] | def Value(self, typecode_or_type, *args, lock=True):
'''Returns a synchronized shared object'''
from .sharedctypes import Value
return Value(typecode_or_type, *args, lock=lock,
ctx=self.get_context()) | [
"def",
"Value",
"(",
"self",
",",
"typecode_or_type",
",",
"*",
"args",
",",
"lock",
"=",
"True",
")",
":",
"from",
".",
"sharedctypes",
"import",
"Value",
"return",
"Value",
"(",
"typecode_or_type",
",",
"*",
"args",
",",
"lock",
"=",
"lock",
",",
"ctx",
"=",
"self",
".",
"get_context",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/context.py#L131-L135 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py | python | ConfigDialog.ok | (self) | Apply config changes, then dismiss dialog.
Methods:
apply
destroy: inherited | Apply config changes, then dismiss dialog. | [
"Apply",
"config",
"changes",
"then",
"dismiss",
"dialog",
"."
] | def ok(self):
"""Apply config changes, then dismiss dialog.
Methods:
apply
destroy: inherited
"""
self.apply()
self.destroy() | [
"def",
"ok",
"(",
"self",
")",
":",
"self",
".",
"apply",
"(",
")",
"self",
".",
"destroy",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L167-L175 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/response.py | python | HTTPResponse.supports_chunked_reads | (self) | return hasattr(self._fp, 'fp') | Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked(). | Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked(). | [
"Checks",
"if",
"the",
"underlying",
"file",
"-",
"like",
"object",
"looks",
"like",
"a",
"httplib",
".",
"HTTPResponse",
"object",
".",
"We",
"do",
"this",
"by",
"testing",
"for",
"the",
"fp",
"attribute",
".",
"If",
"it",
"is",
"present",
"we",
"assume",
"it",
"returns",
"raw",
"chunks",
"as",
"processed",
"by",
"read_chunked",
"()",
"."
] | def supports_chunked_reads(self):
"""
Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
"""
return hasattr(self._fp, 'fp') | [
"def",
"supports_chunked_reads",
"(",
"self",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"_fp",
",",
"'fp'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/response.py#L526-L533 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py | python | dictOf | ( key, value ) | return Dict( ZeroOrMore( Group ( key + value ) ) ) | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields. | [
"Helper",
"to",
"easily",
"and",
"clearly",
"define",
"a",
"dictionary",
"by",
"specifying",
"the",
"respective",
"patterns",
"for",
"the",
"key",
"and",
"value",
".",
"Takes",
"care",
"of",
"defining",
"the",
"C",
"{",
"L",
"{",
"Dict",
"}}",
"C",
"{",
"L",
"{",
"ZeroOrMore",
"}}",
"and",
"C",
"{",
"L",
"{",
"Group",
"}}",
"tokens",
"in",
"the",
"proper",
"order",
".",
"The",
"key",
"pattern",
"can",
"include",
"delimiting",
"markers",
"or",
"punctuation",
"as",
"long",
"as",
"they",
"are",
"suppressed",
"thereby",
"leaving",
"the",
"significant",
"key",
"text",
".",
"The",
"value",
"pattern",
"can",
"include",
"named",
"results",
"so",
"that",
"the",
"C",
"{",
"Dict",
"}",
"results",
"can",
"include",
"named",
"token",
"fields",
"."
] | def dictOf( key, value ):
"""
Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
"""
return Dict( ZeroOrMore( Group ( key + value ) ) ) | [
"def",
"dictOf",
"(",
"key",
",",
"value",
")",
":",
"return",
"Dict",
"(",
"ZeroOrMore",
"(",
"Group",
"(",
"key",
"+",
"value",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py#L4646-L4679 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py | python | Message.__init__ | (self, message=None) | Initialize a Message instance. | Initialize a Message instance. | [
"Initialize",
"a",
"Message",
"instance",
"."
] | def __init__(self, message=None):
"""Initialize a Message instance."""
if isinstance(message, email.message.Message):
self._become_message(copy.deepcopy(message))
if isinstance(message, Message):
message._explain_to(self)
elif isinstance(message, str):
self._become_message(email.message_from_string(message))
elif hasattr(message, "read"):
self._become_message(email.message_from_file(message))
elif message is None:
email.message.Message.__init__(self)
else:
raise TypeError('Invalid message type: %s' % type(message)) | [
"def",
"__init__",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"email",
".",
"message",
".",
"Message",
")",
":",
"self",
".",
"_become_message",
"(",
"copy",
".",
"deepcopy",
"(",
"message",
")",
")",
"if",
"isinstance",
"(",
"message",
",",
"Message",
")",
":",
"message",
".",
"_explain_to",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"message",
",",
"str",
")",
":",
"self",
".",
"_become_message",
"(",
"email",
".",
"message_from_string",
"(",
"message",
")",
")",
"elif",
"hasattr",
"(",
"message",
",",
"\"read\"",
")",
":",
"self",
".",
"_become_message",
"(",
"email",
".",
"message_from_file",
"(",
"message",
")",
")",
"elif",
"message",
"is",
"None",
":",
"email",
".",
"message",
".",
"Message",
".",
"__init__",
"(",
"self",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Invalid message type: %s'",
"%",
"type",
"(",
"message",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py#L1442-L1455 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/config.py | python | DictConfigurator.configure_handler | (self, config) | return result | Configure a handler from a dictionary. | Configure a handler from a dictionary. | [
"Configure",
"a",
"handler",
"from",
"a",
"dictionary",
"."
] | def configure_handler(self, config):
"""Configure a handler from a dictionary."""
formatter = config.pop('formatter', None)
if formatter:
try:
formatter = self.config['formatters'][formatter]
except StandardError, e:
raise ValueError('Unable to set formatter '
'%r: %s' % (formatter, e))
level = config.pop('level', None)
filters = config.pop('filters', None)
if '()' in config:
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
factory = c
else:
cname = config.pop('class')
klass = self.resolve(cname)
#Special case for handler which refers to another handler
if issubclass(klass, logging.handlers.MemoryHandler) and\
'target' in config:
try:
th = self.config['handlers'][config['target']]
if not isinstance(th, logging.Handler):
config['class'] = cname # restore for deferred configuration
raise StandardError('target not configured yet')
config['target'] = th
except StandardError, e:
raise ValueError('Unable to set target handler '
'%r: %s' % (config['target'], e))
elif issubclass(klass, logging.handlers.SMTPHandler) and\
'mailhost' in config:
config['mailhost'] = self.as_tuple(config['mailhost'])
elif issubclass(klass, logging.handlers.SysLogHandler) and\
'address' in config:
config['address'] = self.as_tuple(config['address'])
factory = klass
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
try:
result = factory(**kwargs)
except TypeError, te:
if "'stream'" not in str(te):
raise
#The argument name changed from strm to stream
#Retry with old name.
#This is so that code can be used with older Python versions
#(e.g. by Django)
kwargs['strm'] = kwargs.pop('stream')
result = factory(**kwargs)
if formatter:
result.setFormatter(formatter)
if level is not None:
result.setLevel(logging._checkLevel(level))
if filters:
self.add_filters(result, filters)
return result | [
"def",
"configure_handler",
"(",
"self",
",",
"config",
")",
":",
"formatter",
"=",
"config",
".",
"pop",
"(",
"'formatter'",
",",
"None",
")",
"if",
"formatter",
":",
"try",
":",
"formatter",
"=",
"self",
".",
"config",
"[",
"'formatters'",
"]",
"[",
"formatter",
"]",
"except",
"StandardError",
",",
"e",
":",
"raise",
"ValueError",
"(",
"'Unable to set formatter '",
"'%r: %s'",
"%",
"(",
"formatter",
",",
"e",
")",
")",
"level",
"=",
"config",
".",
"pop",
"(",
"'level'",
",",
"None",
")",
"filters",
"=",
"config",
".",
"pop",
"(",
"'filters'",
",",
"None",
")",
"if",
"'()'",
"in",
"config",
":",
"c",
"=",
"config",
".",
"pop",
"(",
"'()'",
")",
"if",
"not",
"hasattr",
"(",
"c",
",",
"'__call__'",
")",
"and",
"hasattr",
"(",
"types",
",",
"'ClassType'",
")",
"and",
"type",
"(",
"c",
")",
"!=",
"types",
".",
"ClassType",
":",
"c",
"=",
"self",
".",
"resolve",
"(",
"c",
")",
"factory",
"=",
"c",
"else",
":",
"cname",
"=",
"config",
".",
"pop",
"(",
"'class'",
")",
"klass",
"=",
"self",
".",
"resolve",
"(",
"cname",
")",
"#Special case for handler which refers to another handler",
"if",
"issubclass",
"(",
"klass",
",",
"logging",
".",
"handlers",
".",
"MemoryHandler",
")",
"and",
"'target'",
"in",
"config",
":",
"try",
":",
"th",
"=",
"self",
".",
"config",
"[",
"'handlers'",
"]",
"[",
"config",
"[",
"'target'",
"]",
"]",
"if",
"not",
"isinstance",
"(",
"th",
",",
"logging",
".",
"Handler",
")",
":",
"config",
"[",
"'class'",
"]",
"=",
"cname",
"# restore for deferred configuration",
"raise",
"StandardError",
"(",
"'target not configured yet'",
")",
"config",
"[",
"'target'",
"]",
"=",
"th",
"except",
"StandardError",
",",
"e",
":",
"raise",
"ValueError",
"(",
"'Unable to set target handler '",
"'%r: %s'",
"%",
"(",
"config",
"[",
"'target'",
"]",
",",
"e",
")",
")",
"elif",
"issubclass",
"(",
"klass",
",",
"logging",
".",
"handlers",
".",
"SMTPHandler",
")",
"and",
"'mailhost'",
"in",
"config",
":",
"config",
"[",
"'mailhost'",
"]",
"=",
"self",
".",
"as_tuple",
"(",
"config",
"[",
"'mailhost'",
"]",
")",
"elif",
"issubclass",
"(",
"klass",
",",
"logging",
".",
"handlers",
".",
"SysLogHandler",
")",
"and",
"'address'",
"in",
"config",
":",
"config",
"[",
"'address'",
"]",
"=",
"self",
".",
"as_tuple",
"(",
"config",
"[",
"'address'",
"]",
")",
"factory",
"=",
"klass",
"kwargs",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"config",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"config",
"if",
"valid_ident",
"(",
"k",
")",
"]",
")",
"try",
":",
"result",
"=",
"factory",
"(",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
",",
"te",
":",
"if",
"\"'stream'\"",
"not",
"in",
"str",
"(",
"te",
")",
":",
"raise",
"#The argument name changed from strm to stream",
"#Retry with old name.",
"#This is so that code can be used with older Python versions",
"#(e.g. by Django)",
"kwargs",
"[",
"'strm'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'stream'",
")",
"result",
"=",
"factory",
"(",
"*",
"*",
"kwargs",
")",
"if",
"formatter",
":",
"result",
".",
"setFormatter",
"(",
"formatter",
")",
"if",
"level",
"is",
"not",
"None",
":",
"result",
".",
"setLevel",
"(",
"logging",
".",
"_checkLevel",
"(",
"level",
")",
")",
"if",
"filters",
":",
"self",
".",
"add_filters",
"(",
"result",
",",
"filters",
")",
"return",
"result"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/config.py#L702-L758 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | build_scripts/build_usd.py | python | GetCommandOutput | (command) | return None | Executes the specified command and returns output or None. | Executes the specified command and returns output or None. | [
"Executes",
"the",
"specified",
"command",
"and",
"returns",
"output",
"or",
"None",
"."
] | def GetCommandOutput(command):
"""Executes the specified command and returns output or None."""
try:
return subprocess.check_output(
shlex.split(command),
stderr=subprocess.STDOUT).decode(GetLocale(), 'replace').strip()
except subprocess.CalledProcessError:
pass
return None | [
"def",
"GetCommandOutput",
"(",
"command",
")",
":",
"try",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"shlex",
".",
"split",
"(",
"command",
")",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
".",
"decode",
"(",
"GetLocale",
"(",
")",
",",
"'replace'",
")",
".",
"strip",
"(",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"pass",
"return",
"None"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/build_scripts/build_usd.py#L100-L108 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/driver.py | python | load_packaged_grammar | (package, grammar_source) | return g | Normally, loads a pickled grammar by doing
pkgutil.get_data(package, pickled_grammar)
where *pickled_grammar* is computed from *grammar_source* by adding the
Python version and using a ``.pickle`` extension.
However, if *grammar_source* is an extant file, load_grammar(grammar_source)
is called instead. This facilitates using a packaged grammar file when needed
but preserves load_grammar's automatic regeneration behavior when possible. | Normally, loads a pickled grammar by doing
pkgutil.get_data(package, pickled_grammar)
where *pickled_grammar* is computed from *grammar_source* by adding the
Python version and using a ``.pickle`` extension. | [
"Normally",
"loads",
"a",
"pickled",
"grammar",
"by",
"doing",
"pkgutil",
".",
"get_data",
"(",
"package",
"pickled_grammar",
")",
"where",
"*",
"pickled_grammar",
"*",
"is",
"computed",
"from",
"*",
"grammar_source",
"*",
"by",
"adding",
"the",
"Python",
"version",
"and",
"using",
"a",
".",
"pickle",
"extension",
"."
] | def load_packaged_grammar(package, grammar_source):
"""Normally, loads a pickled grammar by doing
pkgutil.get_data(package, pickled_grammar)
where *pickled_grammar* is computed from *grammar_source* by adding the
Python version and using a ``.pickle`` extension.
However, if *grammar_source* is an extant file, load_grammar(grammar_source)
is called instead. This facilitates using a packaged grammar file when needed
but preserves load_grammar's automatic regeneration behavior when possible.
"""
if os.path.isfile(grammar_source):
return load_grammar(grammar_source)
pickled_name = _generate_pickle_name(os.path.basename(grammar_source))
data = pkgutil.get_data(package, pickled_name)
g = grammar.Grammar()
g.loads(data)
return g | [
"def",
"load_packaged_grammar",
"(",
"package",
",",
"grammar_source",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"grammar_source",
")",
":",
"return",
"load_grammar",
"(",
"grammar_source",
")",
"pickled_name",
"=",
"_generate_pickle_name",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"grammar_source",
")",
")",
"data",
"=",
"pkgutil",
".",
"get_data",
"(",
"package",
",",
"pickled_name",
")",
"g",
"=",
"grammar",
".",
"Grammar",
"(",
")",
"g",
".",
"loads",
"(",
"data",
")",
"return",
"g"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/driver.py#L144-L161 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/coverage/coverage/parser.py | python | _opcode | (name) | return dis.opmap[name] | Return the opcode by name from the dis module. | Return the opcode by name from the dis module. | [
"Return",
"the",
"opcode",
"by",
"name",
"from",
"the",
"dis",
"module",
"."
] | def _opcode(name):
"""Return the opcode by name from the dis module."""
return dis.opmap[name] | [
"def",
"_opcode",
"(",
"name",
")",
":",
"return",
"dis",
".",
"opmap",
"[",
"name",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/parser.py#L276-L278 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | ppapi/generators/idl_gen_wrapper.py | python | WrapperGen.DeclareWrapperInfos | (self, iface_releases, out) | The wrapper methods usually need access to the real_iface, so we must
declare these wrapper infos ahead of time (there is a circular dependency). | The wrapper methods usually need access to the real_iface, so we must
declare these wrapper infos ahead of time (there is a circular dependency). | [
"The",
"wrapper",
"methods",
"usually",
"need",
"access",
"to",
"the",
"real_iface",
"so",
"we",
"must",
"declare",
"these",
"wrapper",
"infos",
"ahead",
"of",
"time",
"(",
"there",
"is",
"a",
"circular",
"dependency",
")",
"."
] | def DeclareWrapperInfos(self, iface_releases, out):
"""The wrapper methods usually need access to the real_iface, so we must
declare these wrapper infos ahead of time (there is a circular dependency).
"""
out.Write('/* BEGIN Declarations for all Wrapper Infos */\n\n')
for iface in iface_releases:
out.Write('static struct %s %s;\n' %
(self.GetWrapperMetadataName(), self.GetWrapperInfoName(iface)))
out.Write('/* END Declarations for all Wrapper Infos. */\n\n') | [
"def",
"DeclareWrapperInfos",
"(",
"self",
",",
"iface_releases",
",",
"out",
")",
":",
"out",
".",
"Write",
"(",
"'/* BEGIN Declarations for all Wrapper Infos */\\n\\n'",
")",
"for",
"iface",
"in",
"iface_releases",
":",
"out",
".",
"Write",
"(",
"'static struct %s %s;\\n'",
"%",
"(",
"self",
".",
"GetWrapperMetadataName",
"(",
")",
",",
"self",
".",
"GetWrapperInfoName",
"(",
"iface",
")",
")",
")",
"out",
".",
"Write",
"(",
"'/* END Declarations for all Wrapper Infos. */\\n\\n'",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/ppapi/generators/idl_gen_wrapper.py#L402-L410 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/prt/wxgui.py | python | AddPrtCompressorTool.deactivate | (self) | This call by metacanvas signals that the tool has been
deactivated and can now interact with metacanvas. | This call by metacanvas signals that the tool has been
deactivated and can now interact with metacanvas. | [
"This",
"call",
"by",
"metacanvas",
"signals",
"that",
"the",
"tool",
"has",
"been",
"deactivated",
"and",
"can",
"now",
"interact",
"with",
"metacanvas",
"."
] | def deactivate(self):
"""
This call by metacanvas signals that the tool has been
deactivated and can now interact with metacanvas.
"""
self._is_active = False
# self.unhighlight()
# reset lane visibility
if self._is_lane_visible_before is not None:
lanedraws = self.get_drawobj_by_ident('lanedraws')
if lanedraws:
lanedraws.set_visible(self._is_lane_visible_before)
self._canvas.draw()
self.deactivate_select() | [
"def",
"deactivate",
"(",
"self",
")",
":",
"self",
".",
"_is_active",
"=",
"False",
"# self.unhighlight()",
"# reset lane visibility",
"if",
"self",
".",
"_is_lane_visible_before",
"is",
"not",
"None",
":",
"lanedraws",
"=",
"self",
".",
"get_drawobj_by_ident",
"(",
"'lanedraws'",
")",
"if",
"lanedraws",
":",
"lanedraws",
".",
"set_visible",
"(",
"self",
".",
"_is_lane_visible_before",
")",
"self",
".",
"_canvas",
".",
"draw",
"(",
")",
"self",
".",
"deactivate_select",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/prt/wxgui.py#L112-L128 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/mesa/MesaLib/src/mesa/main/APIspec.py | python | Function.param_node_size | (self, param) | return size | Return the size of a vector. | Return the size of a vector. | [
"Return",
"the",
"size",
"of",
"a",
"vector",
"."
] | def param_node_size(self, param):
"""Return the size of a vector."""
if param.name != "vector":
return 0
size = param.prop("size")
if size.isdigit():
size = int(size)
else:
size = 0
if not size:
size = self._vector_size
if not size and self._expand_vector:
# return the number of named parameters
size = param.lsCountNode()
return size | [
"def",
"param_node_size",
"(",
"self",
",",
"param",
")",
":",
"if",
"param",
".",
"name",
"!=",
"\"vector\"",
":",
"return",
"0",
"size",
"=",
"param",
".",
"prop",
"(",
"\"size\"",
")",
"if",
"size",
".",
"isdigit",
"(",
")",
":",
"size",
"=",
"int",
"(",
"size",
")",
"else",
":",
"size",
"=",
"0",
"if",
"not",
"size",
":",
"size",
"=",
"self",
".",
"_vector_size",
"if",
"not",
"size",
"and",
"self",
".",
"_expand_vector",
":",
"# return the number of named parameters",
"size",
"=",
"param",
".",
"lsCountNode",
"(",
")",
"return",
"size"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/mesa/MesaLib/src/mesa/main/APIspec.py#L243-L258 | |
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/pycocotools/cocoeval.py | python | COCOeval._prepare | (self) | Prepare ._gts and ._dts for evaluation based on params
:return: None | Prepare ._gts and ._dts for evaluation based on params
:return: None | [
"Prepare",
".",
"_gts",
"and",
".",
"_dts",
"for",
"evaluation",
"based",
"on",
"params",
":",
"return",
":",
"None"
] | def _prepare(self):
'''
Prepare ._gts and ._dts for evaluation based on params
:return: None
'''
#
def _toMask(objs, coco):
# modify segmentation by reference
for obj in objs:
t = coco.imgs[obj['image_id']]
if type(obj['segmentation']) == list:
if type(obj['segmentation'][0]) == dict:
print 'debug'
obj['segmentation'] = mask.frPyObjects(obj['segmentation'],t['height'],t['width'])
if len(obj['segmentation']) == 1:
obj['segmentation'] = obj['segmentation'][0]
else:
# an object can have multiple polygon regions
# merge them into one RLE mask
obj['segmentation'] = mask.merge(obj['segmentation'])
elif type(obj['segmentation']) == dict and type(obj['segmentation']['counts']) == list:
obj['segmentation'] = mask.frPyObjects([obj['segmentation']],t['height'],t['width'])[0]
elif type(obj['segmentation']) == dict and \
type(obj['segmentation']['counts'] == unicode or type(obj['segmentation']['counts']) == str):
pass
else:
raise Exception('segmentation format not supported.')
p = self.params
if p.useCats:
gts=self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds))
dts=self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds))
else:
gts=self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds))
dts=self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))
if p.useSegm:
_toMask(gts, self.cocoGt)
_toMask(dts, self.cocoDt)
self._gts = defaultdict(list) # gt for evaluation
self._dts = defaultdict(list) # dt for evaluation
for gt in gts:
self._gts[gt['image_id'], gt['category_id']].append(gt)
for dt in dts:
self._dts[dt['image_id'], dt['category_id']].append(dt)
self.evalImgs = defaultdict(list) # per-image per-category evaluation results
self.eval = {} | [
"def",
"_prepare",
"(",
"self",
")",
":",
"#",
"def",
"_toMask",
"(",
"objs",
",",
"coco",
")",
":",
"# modify segmentation by reference",
"for",
"obj",
"in",
"objs",
":",
"t",
"=",
"coco",
".",
"imgs",
"[",
"obj",
"[",
"'image_id'",
"]",
"]",
"if",
"type",
"(",
"obj",
"[",
"'segmentation'",
"]",
")",
"==",
"list",
":",
"if",
"type",
"(",
"obj",
"[",
"'segmentation'",
"]",
"[",
"0",
"]",
")",
"==",
"dict",
":",
"print",
"'debug'",
"obj",
"[",
"'segmentation'",
"]",
"=",
"mask",
".",
"frPyObjects",
"(",
"obj",
"[",
"'segmentation'",
"]",
",",
"t",
"[",
"'height'",
"]",
",",
"t",
"[",
"'width'",
"]",
")",
"if",
"len",
"(",
"obj",
"[",
"'segmentation'",
"]",
")",
"==",
"1",
":",
"obj",
"[",
"'segmentation'",
"]",
"=",
"obj",
"[",
"'segmentation'",
"]",
"[",
"0",
"]",
"else",
":",
"# an object can have multiple polygon regions",
"# merge them into one RLE mask",
"obj",
"[",
"'segmentation'",
"]",
"=",
"mask",
".",
"merge",
"(",
"obj",
"[",
"'segmentation'",
"]",
")",
"elif",
"type",
"(",
"obj",
"[",
"'segmentation'",
"]",
")",
"==",
"dict",
"and",
"type",
"(",
"obj",
"[",
"'segmentation'",
"]",
"[",
"'counts'",
"]",
")",
"==",
"list",
":",
"obj",
"[",
"'segmentation'",
"]",
"=",
"mask",
".",
"frPyObjects",
"(",
"[",
"obj",
"[",
"'segmentation'",
"]",
"]",
",",
"t",
"[",
"'height'",
"]",
",",
"t",
"[",
"'width'",
"]",
")",
"[",
"0",
"]",
"elif",
"type",
"(",
"obj",
"[",
"'segmentation'",
"]",
")",
"==",
"dict",
"and",
"type",
"(",
"obj",
"[",
"'segmentation'",
"]",
"[",
"'counts'",
"]",
"==",
"unicode",
"or",
"type",
"(",
"obj",
"[",
"'segmentation'",
"]",
"[",
"'counts'",
"]",
")",
"==",
"str",
")",
":",
"pass",
"else",
":",
"raise",
"Exception",
"(",
"'segmentation format not supported.'",
")",
"p",
"=",
"self",
".",
"params",
"if",
"p",
".",
"useCats",
":",
"gts",
"=",
"self",
".",
"cocoGt",
".",
"loadAnns",
"(",
"self",
".",
"cocoGt",
".",
"getAnnIds",
"(",
"imgIds",
"=",
"p",
".",
"imgIds",
",",
"catIds",
"=",
"p",
".",
"catIds",
")",
")",
"dts",
"=",
"self",
".",
"cocoDt",
".",
"loadAnns",
"(",
"self",
".",
"cocoDt",
".",
"getAnnIds",
"(",
"imgIds",
"=",
"p",
".",
"imgIds",
",",
"catIds",
"=",
"p",
".",
"catIds",
")",
")",
"else",
":",
"gts",
"=",
"self",
".",
"cocoGt",
".",
"loadAnns",
"(",
"self",
".",
"cocoGt",
".",
"getAnnIds",
"(",
"imgIds",
"=",
"p",
".",
"imgIds",
")",
")",
"dts",
"=",
"self",
".",
"cocoDt",
".",
"loadAnns",
"(",
"self",
".",
"cocoDt",
".",
"getAnnIds",
"(",
"imgIds",
"=",
"p",
".",
"imgIds",
")",
")",
"if",
"p",
".",
"useSegm",
":",
"_toMask",
"(",
"gts",
",",
"self",
".",
"cocoGt",
")",
"_toMask",
"(",
"dts",
",",
"self",
".",
"cocoDt",
")",
"self",
".",
"_gts",
"=",
"defaultdict",
"(",
"list",
")",
"# gt for evaluation",
"self",
".",
"_dts",
"=",
"defaultdict",
"(",
"list",
")",
"# dt for evaluation",
"for",
"gt",
"in",
"gts",
":",
"self",
".",
"_gts",
"[",
"gt",
"[",
"'image_id'",
"]",
",",
"gt",
"[",
"'category_id'",
"]",
"]",
".",
"append",
"(",
"gt",
")",
"for",
"dt",
"in",
"dts",
":",
"self",
".",
"_dts",
"[",
"dt",
"[",
"'image_id'",
"]",
",",
"dt",
"[",
"'category_id'",
"]",
"]",
".",
"append",
"(",
"dt",
")",
"self",
".",
"evalImgs",
"=",
"defaultdict",
"(",
"list",
")",
"# per-image per-category evaluation results",
"self",
".",
"eval",
"=",
"{",
"}"
] | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/pycocotools/cocoeval.py#L82-L127 | ||
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetCflagsCC | (self, configname) | return cflags_cc | Returns flags that need to be added to .cc, and .mm compilations. | Returns flags that need to be added to .cc, and .mm compilations. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"cc",
"and",
".",
"mm",
"compilations",
"."
] | def GetCflagsCC(self, configname):
"""Returns flags that need to be added to .cc, and .mm compilations."""
self.configname = configname
cflags_cc = []
if self._Test('GCC_ENABLE_CPP_RTTI', 'NO', default='YES'):
cflags_cc.append('-fno-rtti')
if self._Test('GCC_ENABLE_CPP_EXCEPTIONS', 'NO', default='YES'):
cflags_cc.append('-fno-exceptions')
if self._Test('GCC_INLINES_ARE_PRIVATE_EXTERN', 'YES', default='NO'):
cflags_cc.append('-fvisibility-inlines-hidden')
if self._Test('GCC_THREADSAFE_STATICS', 'NO', default='YES'):
cflags_cc.append('-fno-threadsafe-statics')
if self._Test('GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO', 'NO', default='YES'):
cflags_cc.append('-Wno-invalid-offsetof')
other_ccflags = []
for flag in self._Settings().get('OTHER_CPLUSPLUSFLAGS', ['$(inherited)']):
# TODO: More general variable expansion. Missing in many other places too.
if flag in ('$inherited', '$(inherited)', '${inherited}'):
flag = '$OTHER_CFLAGS'
if flag in ('$OTHER_CFLAGS', '$(OTHER_CFLAGS)', '${OTHER_CFLAGS}'):
other_ccflags += self._Settings().get('OTHER_CFLAGS', [])
else:
other_ccflags.append(flag)
cflags_cc += other_ccflags
self.configname = None
return cflags_cc | [
"def",
"GetCflagsCC",
"(",
"self",
",",
"configname",
")",
":",
"self",
".",
"configname",
"=",
"configname",
"cflags_cc",
"=",
"[",
"]",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_CPP_RTTI'",
",",
"'NO'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags_cc",
".",
"append",
"(",
"'-fno-rtti'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_CPP_EXCEPTIONS'",
",",
"'NO'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags_cc",
".",
"append",
"(",
"'-fno-exceptions'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_INLINES_ARE_PRIVATE_EXTERN'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags_cc",
".",
"append",
"(",
"'-fvisibility-inlines-hidden'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_THREADSAFE_STATICS'",
",",
"'NO'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags_cc",
".",
"append",
"(",
"'-fno-threadsafe-statics'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO'",
",",
"'NO'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags_cc",
".",
"append",
"(",
"'-Wno-invalid-offsetof'",
")",
"other_ccflags",
"=",
"[",
"]",
"for",
"flag",
"in",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'OTHER_CPLUSPLUSFLAGS'",
",",
"[",
"'$(inherited)'",
"]",
")",
":",
"# TODO: More general variable expansion. Missing in many other places too.",
"if",
"flag",
"in",
"(",
"'$inherited'",
",",
"'$(inherited)'",
",",
"'${inherited}'",
")",
":",
"flag",
"=",
"'$OTHER_CFLAGS'",
"if",
"flag",
"in",
"(",
"'$OTHER_CFLAGS'",
",",
"'$(OTHER_CFLAGS)'",
",",
"'${OTHER_CFLAGS}'",
")",
":",
"other_ccflags",
"+=",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'OTHER_CFLAGS'",
",",
"[",
"]",
")",
"else",
":",
"other_ccflags",
".",
"append",
"(",
"flag",
")",
"cflags_cc",
"+=",
"other_ccflags",
"self",
".",
"configname",
"=",
"None",
"return",
"cflags_cc"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcode_emulation.py#L353-L381 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py | python | Context.Etiny | (self) | return int(self.Emin - self.prec + 1) | Returns Etiny (= Emin - prec + 1) | Returns Etiny (= Emin - prec + 1) | [
"Returns",
"Etiny",
"(",
"=",
"Emin",
"-",
"prec",
"+",
"1",
")"
] | def Etiny(self):
"""Returns Etiny (= Emin - prec + 1)"""
return int(self.Emin - self.prec + 1) | [
"def",
"Etiny",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"Emin",
"-",
"self",
".",
"prec",
"+",
"1",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L3895-L3897 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/qemu.py | python | _setup_nfs_mount | (remote, client, service_name, mount_dir) | Sets up an nfs mount on the remote that the guest can use to
store logs. This nfs mount is also used to touch a file
at the end of the test to indicate if the test was successful
or not. | Sets up an nfs mount on the remote that the guest can use to
store logs. This nfs mount is also used to touch a file
at the end of the test to indicate if the test was successful
or not. | [
"Sets",
"up",
"an",
"nfs",
"mount",
"on",
"the",
"remote",
"that",
"the",
"guest",
"can",
"use",
"to",
"store",
"logs",
".",
"This",
"nfs",
"mount",
"is",
"also",
"used",
"to",
"touch",
"a",
"file",
"at",
"the",
"end",
"of",
"the",
"test",
"to",
"indicate",
"if",
"the",
"test",
"was",
"successful",
"or",
"not",
"."
] | def _setup_nfs_mount(remote, client, service_name, mount_dir):
"""
Sets up an nfs mount on the remote that the guest can use to
store logs. This nfs mount is also used to touch a file
at the end of the test to indicate if the test was successful
or not.
"""
export_dir = "/export/{client}".format(client=client)
log.info("Creating the nfs export directory...")
remote.run(args=[
'sudo', 'mkdir', '-p', export_dir,
])
log.info("Mounting the test directory...")
remote.run(args=[
'sudo', 'mount', '--bind', mount_dir, export_dir,
])
log.info("Adding mount to /etc/exports...")
export = "{dir} *(rw,no_root_squash,no_subtree_check,insecure)".format(
dir=export_dir
)
log.info("Deleting export from /etc/exports...")
remote.run(args=[
'sudo', 'sed', '-i', "\|{export_dir}|d".format(export_dir=export_dir),
'/etc/exports'
])
remote.run(args=[
'echo', export, run.Raw("|"),
'sudo', 'tee', '-a', "/etc/exports",
])
log.info("Restarting NFS...")
if remote.os.package_type == "deb":
remote.run(args=['sudo', 'service', 'nfs-kernel-server', 'restart'])
else:
remote.run(args=['sudo', 'systemctl', 'restart', service_name]) | [
"def",
"_setup_nfs_mount",
"(",
"remote",
",",
"client",
",",
"service_name",
",",
"mount_dir",
")",
":",
"export_dir",
"=",
"\"/export/{client}\"",
".",
"format",
"(",
"client",
"=",
"client",
")",
"log",
".",
"info",
"(",
"\"Creating the nfs export directory...\"",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'sudo'",
",",
"'mkdir'",
",",
"'-p'",
",",
"export_dir",
",",
"]",
")",
"log",
".",
"info",
"(",
"\"Mounting the test directory...\"",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'sudo'",
",",
"'mount'",
",",
"'--bind'",
",",
"mount_dir",
",",
"export_dir",
",",
"]",
")",
"log",
".",
"info",
"(",
"\"Adding mount to /etc/exports...\"",
")",
"export",
"=",
"\"{dir} *(rw,no_root_squash,no_subtree_check,insecure)\"",
".",
"format",
"(",
"dir",
"=",
"export_dir",
")",
"log",
".",
"info",
"(",
"\"Deleting export from /etc/exports...\"",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'sudo'",
",",
"'sed'",
",",
"'-i'",
",",
"\"\\|{export_dir}|d\"",
".",
"format",
"(",
"export_dir",
"=",
"export_dir",
")",
",",
"'/etc/exports'",
"]",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'echo'",
",",
"export",
",",
"run",
".",
"Raw",
"(",
"\"|\"",
")",
",",
"'sudo'",
",",
"'tee'",
",",
"'-a'",
",",
"\"/etc/exports\"",
",",
"]",
")",
"log",
".",
"info",
"(",
"\"Restarting NFS...\"",
")",
"if",
"remote",
".",
"os",
".",
"package_type",
"==",
"\"deb\"",
":",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'sudo'",
",",
"'service'",
",",
"'nfs-kernel-server'",
",",
"'restart'",
"]",
")",
"else",
":",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'sudo'",
",",
"'systemctl'",
",",
"'restart'",
",",
"service_name",
"]",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/qemu.py#L369-L402 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/Bastion.py | python | BastionClass.__getattr__ | (self, name) | return attribute | Get an as-yet undefined attribute value.
This calls the get() function that was passed to the
constructor. The result is stored as an instance variable so
that the next time the same attribute is requested,
__getattr__() won't be invoked.
If the get() function raises an exception, this is simply
passed on -- exceptions are not cached. | Get an as-yet undefined attribute value. | [
"Get",
"an",
"as",
"-",
"yet",
"undefined",
"attribute",
"value",
"."
] | def __getattr__(self, name):
"""Get an as-yet undefined attribute value.
This calls the get() function that was passed to the
constructor. The result is stored as an instance variable so
that the next time the same attribute is requested,
__getattr__() won't be invoked.
If the get() function raises an exception, this is simply
passed on -- exceptions are not cached.
"""
attribute = self._get_(name)
self.__dict__[name] = attribute
return attribute | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"attribute",
"=",
"self",
".",
"_get_",
"(",
"name",
")",
"self",
".",
"__dict__",
"[",
"name",
"]",
"=",
"attribute",
"return",
"attribute"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/Bastion.py#L70-L84 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/findertools.py | python | _seticon | (object_alias, icondata) | set the icondata for object, formatted as produced by _geticon() | set the icondata for object, formatted as produced by _geticon() | [
"set",
"the",
"icondata",
"for",
"object",
"formatted",
"as",
"produced",
"by",
"_geticon",
"()"
] | def _seticon(object_alias, icondata):
"""set the icondata for object, formatted as produced by _geticon()"""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'),
form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00)
args['----'] = aeobj_01
args["data"] = icondata
_reply, args, attrs = finder.send("core", "setd", args, attrs)
if 'errn' in args:
raise Error, aetools.decodeerror(args)
if '----' in args:
return args['----'].data | [
"def",
"_seticon",
"(",
"object_alias",
",",
"icondata",
")",
":",
"finder",
"=",
"_getfinder",
"(",
")",
"args",
"=",
"{",
"}",
"attrs",
"=",
"{",
"}",
"aeobj_00",
"=",
"aetypes",
".",
"ObjectSpecifier",
"(",
"want",
"=",
"aetypes",
".",
"Type",
"(",
"'cobj'",
")",
",",
"form",
"=",
"\"alis\"",
",",
"seld",
"=",
"object_alias",
",",
"fr",
"=",
"None",
")",
"aeobj_01",
"=",
"aetypes",
".",
"ObjectSpecifier",
"(",
"want",
"=",
"aetypes",
".",
"Type",
"(",
"'prop'",
")",
",",
"form",
"=",
"\"prop\"",
",",
"seld",
"=",
"aetypes",
".",
"Type",
"(",
"'iimg'",
")",
",",
"fr",
"=",
"aeobj_00",
")",
"args",
"[",
"'----'",
"]",
"=",
"aeobj_01",
"args",
"[",
"\"data\"",
"]",
"=",
"icondata",
"_reply",
",",
"args",
",",
"attrs",
"=",
"finder",
".",
"send",
"(",
"\"core\"",
",",
"\"setd\"",
",",
"args",
",",
"attrs",
")",
"if",
"'errn'",
"in",
"args",
":",
"raise",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"args",
")",
"if",
"'----'",
"in",
"args",
":",
"return",
"args",
"[",
"'----'",
"]",
".",
"data"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/findertools.py#L560-L575 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/legendre.py | python | legline | (off, scl) | Legendre series whose graph is a straight line.
Parameters
----------
off, scl : scalars
The specified line is given by ``off + scl*x``.
Returns
-------
y : ndarray
This module's representation of the Legendre series for
``off + scl*x``.
See Also
--------
polyline, chebline
Examples
--------
>>> import numpy.polynomial.legendre as L
>>> L.legline(3,2)
array([3, 2])
>>> L.legval(-3, L.legline(3,2)) # should be -3
-3.0 | Legendre series whose graph is a straight line. | [
"Legendre",
"series",
"whose",
"graph",
"is",
"a",
"straight",
"line",
"."
] | def legline(off, scl):
"""
Legendre series whose graph is a straight line.
Parameters
----------
off, scl : scalars
The specified line is given by ``off + scl*x``.
Returns
-------
y : ndarray
This module's representation of the Legendre series for
``off + scl*x``.
See Also
--------
polyline, chebline
Examples
--------
>>> import numpy.polynomial.legendre as L
>>> L.legline(3,2)
array([3, 2])
>>> L.legval(-3, L.legline(3,2)) # should be -3
-3.0
"""
if scl != 0:
return np.array([off, scl])
else:
return np.array([off]) | [
"def",
"legline",
"(",
"off",
",",
"scl",
")",
":",
"if",
"scl",
"!=",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"off",
",",
"scl",
"]",
")",
"else",
":",
"return",
"np",
".",
"array",
"(",
"[",
"off",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/legendre.py#L232-L265 | ||
SmartisanTech/Wrench | 27f3c17692910997bba3a3c9fd88c8717497aac6 | extra-cmake-modules/usr/share/ECM/find-modules/rules_engine.py | python | RuleSet.function_rules | (self) | Return a compiled list of rules for functions.
:return: A FunctionRuleDb instance | Return a compiled list of rules for functions. | [
"Return",
"a",
"compiled",
"list",
"of",
"rules",
"for",
"functions",
"."
] | def function_rules(self):
"""
Return a compiled list of rules for functions.
:return: A FunctionRuleDb instance
"""
raise NotImplemented(_("Missing subclass implementation")) | [
"def",
"function_rules",
"(",
"self",
")",
":",
"raise",
"NotImplemented",
"(",
"_",
"(",
"\"Missing subclass implementation\"",
")",
")"
] | https://github.com/SmartisanTech/Wrench/blob/27f3c17692910997bba3a3c9fd88c8717497aac6/extra-cmake-modules/usr/share/ECM/find-modules/rules_engine.py#L449-L455 | ||
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/dox/write_html.py | python | TemplateManager.loadTemplate | (self, path) | Load template string at path. | Load template string at path. | [
"Load",
"template",
"string",
"at",
"path",
"."
] | def loadTemplate(self, path):
"""Load template string at path."""
self.tpls[path] = self.env.get_template(path) | [
"def",
"loadTemplate",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"tpls",
"[",
"path",
"]",
"=",
"self",
".",
"env",
".",
"get_template",
"(",
"path",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/write_html.py#L215-L217 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/req/req_set.py | python | RequirementSet._to_install | (self) | return order | Create the installation order.
The installation order is topological - requirements are installed
before the requiring thing. We break cycles at an arbitrary point,
and make no other guarantees. | Create the installation order. | [
"Create",
"the",
"installation",
"order",
"."
] | def _to_install(self):
"""Create the installation order.
The installation order is topological - requirements are installed
before the requiring thing. We break cycles at an arbitrary point,
and make no other guarantees.
"""
# The current implementation, which we may change at any point
# installs the user specified things in the order given, except when
# dependencies must come earlier to achieve topological order.
order = []
ordered_reqs = set()
def schedule(req):
if req.satisfied_by or req in ordered_reqs:
return
ordered_reqs.add(req)
for dep in self._dependencies[req]:
schedule(dep)
order.append(req)
for install_req in self.requirements.values():
schedule(install_req)
return order | [
"def",
"_to_install",
"(",
"self",
")",
":",
"# The current implementation, which we may change at any point",
"# installs the user specified things in the order given, except when",
"# dependencies must come earlier to achieve topological order.",
"order",
"=",
"[",
"]",
"ordered_reqs",
"=",
"set",
"(",
")",
"def",
"schedule",
"(",
"req",
")",
":",
"if",
"req",
".",
"satisfied_by",
"or",
"req",
"in",
"ordered_reqs",
":",
"return",
"ordered_reqs",
".",
"add",
"(",
"req",
")",
"for",
"dep",
"in",
"self",
".",
"_dependencies",
"[",
"req",
"]",
":",
"schedule",
"(",
"dep",
")",
"order",
".",
"append",
"(",
"req",
")",
"for",
"install_req",
"in",
"self",
".",
"requirements",
".",
"values",
"(",
")",
":",
"schedule",
"(",
"install_req",
")",
"return",
"order"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/req/req_set.py#L571-L593 | |
Alexhuszagh/rust-lexical | 01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0 | scripts/timings.py | python | clean | (directory=home) | Clean the project | Clean the project | [
"Clean",
"the",
"project"
] | def clean(directory=home):
'''Clean the project'''
os.chdir(directory)
subprocess.check_call(
['cargo', '+nightly', 'clean'],
shell=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
) | [
"def",
"clean",
"(",
"directory",
"=",
"home",
")",
":",
"os",
".",
"chdir",
"(",
"directory",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"'cargo'",
",",
"'+nightly'",
",",
"'clean'",
"]",
",",
"shell",
"=",
"False",
",",
"stdout",
"=",
"subprocess",
".",
"DEVNULL",
",",
"stderr",
"=",
"subprocess",
".",
"DEVNULL",
",",
")"
] | https://github.com/Alexhuszagh/rust-lexical/blob/01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0/scripts/timings.py#L44-L53 | ||
sideeffects/HoudiniEngineForUnreal | a52be617d90495bda6072fe732f0d2eec33b54f3 | Content/Python/HoudiniEngineV2/asyncprocessor.py | python | ProcessHDA._handle_on_pre_process | (self, wrapper) | Called during pre_process. Calls self.on_pre_process(). | Called during pre_process. Calls self.on_pre_process(). | [
"Called",
"during",
"pre_process",
".",
"Calls",
"self",
".",
"on_pre_process",
"()",
"."
] | def _handle_on_pre_process(self, wrapper):
""" Called during pre_process. Calls self.on_pre_process().
"""
if not self._check_wrapper(wrapper):
return
self.on_pre_process() | [
"def",
"_handle_on_pre_process",
"(",
"self",
",",
"wrapper",
")",
":",
"if",
"not",
"self",
".",
"_check_wrapper",
"(",
"wrapper",
")",
":",
"return",
"self",
".",
"on_pre_process",
"(",
")"
] | https://github.com/sideeffects/HoudiniEngineForUnreal/blob/a52be617d90495bda6072fe732f0d2eec33b54f3/Content/Python/HoudiniEngineV2/asyncprocessor.py#L419-L426 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Text.window_cget | (self, index, option) | return self.tk.call(self._w, 'window', 'cget', index, option) | Return the value of OPTION of an embedded window at INDEX. | Return the value of OPTION of an embedded window at INDEX. | [
"Return",
"the",
"value",
"of",
"OPTION",
"of",
"an",
"embedded",
"window",
"at",
"INDEX",
"."
] | def window_cget(self, index, option):
"""Return the value of OPTION of an embedded window at INDEX."""
if option[:1] != '-':
option = '-' + option
if option[-1:] == '_':
option = option[:-1]
return self.tk.call(self._w, 'window', 'cget', index, option) | [
"def",
"window_cget",
"(",
"self",
",",
"index",
",",
"option",
")",
":",
"if",
"option",
"[",
":",
"1",
"]",
"!=",
"'-'",
":",
"option",
"=",
"'-'",
"+",
"option",
"if",
"option",
"[",
"-",
"1",
":",
"]",
"==",
"'_'",
":",
"option",
"=",
"option",
"[",
":",
"-",
"1",
"]",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'window'",
",",
"'cget'",
",",
"index",
",",
"option",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3166-L3172 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/mock/mock.py | python | _patch.start | (self) | return result | Activate a patch, returning any created mock. | Activate a patch, returning any created mock. | [
"Activate",
"a",
"patch",
"returning",
"any",
"created",
"mock",
"."
] | def start(self):
"""Activate a patch, returning any created mock."""
result = self.__enter__()
self._active_patches.add(self)
return result | [
"def",
"start",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"__enter__",
"(",
")",
"self",
".",
"_active_patches",
".",
"add",
"(",
"self",
")",
"return",
"result"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/mock/mock.py#L1394-L1398 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/memory_inspector/memory_inspector/core/backends.py | python | Process.Freeze | (self) | Stops the process and all its threads. | Stops the process and all its threads. | [
"Stops",
"the",
"process",
"and",
"all",
"its",
"threads",
"."
] | def Freeze(self):
"""Stops the process and all its threads."""
raise NotImplementedError() | [
"def",
"Freeze",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/memory_inspector/memory_inspector/core/backends.py#L137-L139 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TextCtrl.IsMultiLine | (*args, **kwargs) | return _controls_.TextCtrl_IsMultiLine(*args, **kwargs) | IsMultiLine(self) -> bool | IsMultiLine(self) -> bool | [
"IsMultiLine",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsMultiLine(*args, **kwargs):
"""IsMultiLine(self) -> bool"""
return _controls_.TextCtrl_IsMultiLine(*args, **kwargs) | [
"def",
"IsMultiLine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextCtrl_IsMultiLine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L2035-L2037 | |
ComputationalRadiationPhysics/picongpu | 59e9b53605f9a5c1bf271eeb055bc74370a99052 | lib/python/picongpu/plugins/plot_mpl/transition_radiation_visualizer.py | python | Visualizer.visualize | (self, **kwargs) | Creates a plot on the provided axes object for
the data of the given iteration using matpotlib.
Parameters
----------
kwargs: dictionary with further keyword arguments, valid are:
species: string
short name of the particle species, e.g. 'e' for electrons
(defined in ``speciesDefinition.param``)
iteration: int
number of the iteration
time: float
simulation time.
Only one of 'iteration' or 'time' should be passed!
type: string
name of figure type. valid figure types are:
'spectrum' - (default) plots transition radiation spectrum
at angles theta and phi over the frequency omega
'sliceovertheta' - shows angular distribution of
transition radiation
at a fixed angle phi and frequency omega
'sliceoverphi' - shows angular distribution of
transition radiation
at a fixed angle theta and frequency omega
'heatmap' - shows angular distribution as heatmap over
both observation angles
phi: int
index of polar angle for a fixed value
theta: int
index of azimuth angle for a fixed value
omega: int
index of frequency for a fixed value, pointless in a spectrum | Creates a plot on the provided axes object for
the data of the given iteration using matpotlib. | [
"Creates",
"a",
"plot",
"on",
"the",
"provided",
"axes",
"object",
"for",
"the",
"data",
"of",
"the",
"given",
"iteration",
"using",
"matpotlib",
"."
] | def visualize(self, **kwargs):
"""
Creates a plot on the provided axes object for
the data of the given iteration using matpotlib.
Parameters
----------
kwargs: dictionary with further keyword arguments, valid are:
species: string
short name of the particle species, e.g. 'e' for electrons
(defined in ``speciesDefinition.param``)
iteration: int
number of the iteration
time: float
simulation time.
Only one of 'iteration' or 'time' should be passed!
type: string
name of figure type. valid figure types are:
'spectrum' - (default) plots transition radiation spectrum
at angles theta and phi over the frequency omega
'sliceovertheta' - shows angular distribution of
transition radiation
at a fixed angle phi and frequency omega
'sliceoverphi' - shows angular distribution of
transition radiation
at a fixed angle theta and frequency omega
'heatmap' - shows angular distribution as heatmap over
both observation angles
phi: int
index of polar angle for a fixed value
theta: int
index of azimuth angle for a fixed value
omega: int
index of frequency for a fixed value, pointless in a spectrum
"""
self.type = kwargs["type"]
super().visualize(**kwargs) | [
"def",
"visualize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"type",
"=",
"kwargs",
"[",
"\"type\"",
"]",
"super",
"(",
")",
".",
"visualize",
"(",
"*",
"*",
"kwargs",
")"
] | https://github.com/ComputationalRadiationPhysics/picongpu/blob/59e9b53605f9a5c1bf271eeb055bc74370a99052/lib/python/picongpu/plugins/plot_mpl/transition_radiation_visualizer.py#L68-L104 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/email/message.py | python | Message.get_content_type | (self) | return ctype | Return the message's content type.
The returned string is coerced to lower case of the form
`maintype/subtype'. If there was no Content-Type header in the
message, the default type as given by get_default_type() will be
returned. Since according to RFC 2045, messages always have a default
type this will always return a value.
RFC 2045 defines a message's default type to be text/plain unless it
appears inside a multipart/digest container, in which case it would be
message/rfc822. | Return the message's content type. | [
"Return",
"the",
"message",
"s",
"content",
"type",
"."
] | def get_content_type(self):
"""Return the message's content type.
The returned string is coerced to lower case of the form
`maintype/subtype'. If there was no Content-Type header in the
message, the default type as given by get_default_type() will be
returned. Since according to RFC 2045, messages always have a default
type this will always return a value.
RFC 2045 defines a message's default type to be text/plain unless it
appears inside a multipart/digest container, in which case it would be
message/rfc822.
"""
missing = object()
value = self.get('content-type', missing)
if value is missing:
# This should have no parameters
return self.get_default_type()
ctype = _splitparam(value)[0].lower()
# RFC 2045, section 5.2 says if its invalid, use text/plain
if ctype.count('/') != 1:
return 'text/plain'
return ctype | [
"def",
"get_content_type",
"(",
"self",
")",
":",
"missing",
"=",
"object",
"(",
")",
"value",
"=",
"self",
".",
"get",
"(",
"'content-type'",
",",
"missing",
")",
"if",
"value",
"is",
"missing",
":",
"# This should have no parameters",
"return",
"self",
".",
"get_default_type",
"(",
")",
"ctype",
"=",
"_splitparam",
"(",
"value",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"# RFC 2045, section 5.2 says if its invalid, use text/plain",
"if",
"ctype",
".",
"count",
"(",
"'/'",
")",
"!=",
"1",
":",
"return",
"'text/plain'",
"return",
"ctype"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/email/message.py#L425-L447 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/matching.py | python | _convert_matches_to_vector | (matches) | return matches_vector | Convert Dmatch object to matrix form. | Convert Dmatch object to matrix form. | [
"Convert",
"Dmatch",
"object",
"to",
"matrix",
"form",
"."
] | def _convert_matches_to_vector(matches):
"""Convert Dmatch object to matrix form."""
matches_vector = np.zeros((len(matches), 2), dtype=np.int)
k = 0
for mm in matches:
matches_vector[k, 0] = mm.queryIdx
matches_vector[k, 1] = mm.trainIdx
k = k+1
return matches_vector | [
"def",
"_convert_matches_to_vector",
"(",
"matches",
")",
":",
"matches_vector",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"matches",
")",
",",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"k",
"=",
"0",
"for",
"mm",
"in",
"matches",
":",
"matches_vector",
"[",
"k",
",",
"0",
"]",
"=",
"mm",
".",
"queryIdx",
"matches_vector",
"[",
"k",
",",
"1",
"]",
"=",
"mm",
".",
"trainIdx",
"k",
"=",
"k",
"+",
"1",
"return",
"matches_vector"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/matching.py#L51-L59 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchIFC.py | python | IfcContext.getIfcSchema | (self) | return ArchIFCSchema.IfcContexts | Get the IFC schema of all IFC types that inherit from IfcContexts.
Returns
-------
dict
The schema of all the types relevant to this class. | Get the IFC schema of all IFC types that inherit from IfcContexts. | [
"Get",
"the",
"IFC",
"schema",
"of",
"all",
"IFC",
"types",
"that",
"inherit",
"from",
"IfcContexts",
"."
] | def getIfcSchema(self):
"""Get the IFC schema of all IFC types that inherit from IfcContexts.
Returns
-------
dict
The schema of all the types relevant to this class.
"""
return ArchIFCSchema.IfcContexts | [
"def",
"getIfcSchema",
"(",
"self",
")",
":",
"return",
"ArchIFCSchema",
".",
"IfcContexts"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchIFC.py#L480-L488 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | StaticBitmap.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticBitmapNameStr) -> StaticBitmap | __init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticBitmapNameStr) -> StaticBitmap | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Bitmap",
"bitmap",
"=",
"wxNullBitmap",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
"String",
"name",
"=",
"StaticBitmapNameStr",
")",
"-",
">",
"StaticBitmap"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=0, String name=StaticBitmapNameStr) -> StaticBitmap
"""
_controls_.StaticBitmap_swiginit(self,_controls_.new_StaticBitmap(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_controls_",
".",
"StaticBitmap_swiginit",
"(",
"self",
",",
"_controls_",
".",
"new_StaticBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L1071-L1078 | ||
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | python-threatexchange/threatexchange/cli/command_base.py | python | Command.get_help | (cls) | return line | The short help of the command | The short help of the command | [
"The",
"short",
"help",
"of",
"the",
"command"
] | def get_help(cls) -> str:
"""The short help of the command"""
line = cls.get_description().strip().partition("\n")[0]
# Good luck debugging this! Slightly reformat short description
# (toplevel --help)
if line[0].isupper():
first_word, sp, rem = line.partition(" ")
line = f"{first_word.lower()}{sp}{rem}"
if line[-1] == ".":
line = line[:-1]
return line | [
"def",
"get_help",
"(",
"cls",
")",
"->",
"str",
":",
"line",
"=",
"cls",
".",
"get_description",
"(",
")",
".",
"strip",
"(",
")",
".",
"partition",
"(",
"\"\\n\"",
")",
"[",
"0",
"]",
"# Good luck debugging this! Slightly reformat short description",
"# (toplevel --help)",
"if",
"line",
"[",
"0",
"]",
".",
"isupper",
"(",
")",
":",
"first_word",
",",
"sp",
",",
"rem",
"=",
"line",
".",
"partition",
"(",
"\" \"",
")",
"line",
"=",
"f\"{first_word.lower()}{sp}{rem}\"",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"\".\"",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"return",
"line"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/cli/command_base.py#L72-L82 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParserElement.ignore | ( self, other ) | return self | Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] | Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] | [
"Define",
"expression",
"to",
"be",
"ignored",
"(",
"e",
".",
"g",
".",
"comments",
")",
"while",
"doing",
"pattern",
"matching",
";",
"may",
"be",
"called",
"repeatedly",
"to",
"define",
"multiple",
"comment",
"or",
"other",
"ignorable",
"patterns",
".",
"Example",
"::",
"patt",
"=",
"OneOrMore",
"(",
"Word",
"(",
"alphas",
"))",
"patt",
".",
"parseString",
"(",
"ablaj",
"/",
"*",
"comment",
"*",
"/",
"lskjd",
")",
"#",
"-",
">",
"[",
"ablaj",
"]",
"patt",
".",
"ignore",
"(",
"cStyleComment",
")",
"patt",
".",
"parseString",
"(",
"ablaj",
"/",
"*",
"comment",
"*",
"/",
"lskjd",
")",
"#",
"-",
">",
"[",
"ablaj",
"lskjd",
"]"
] | def ignore( self, other ):
"""
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
"""
if isinstance(other, basestring):
other = Suppress(other)
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
self.ignoreExprs.append(other)
else:
self.ignoreExprs.append( Suppress( other.copy() ) )
return self | [
"def",
"ignore",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"Suppress",
"(",
"other",
")",
"if",
"isinstance",
"(",
"other",
",",
"Suppress",
")",
":",
"if",
"other",
"not",
"in",
"self",
".",
"ignoreExprs",
":",
"self",
".",
"ignoreExprs",
".",
"append",
"(",
"other",
")",
"else",
":",
"self",
".",
"ignoreExprs",
".",
"append",
"(",
"Suppress",
"(",
"other",
".",
"copy",
"(",
")",
")",
")",
"return",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L2079-L2100 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/tools/scan-build-py/libscanbuild/analyze.py | python | prefix_with | (constant, pieces) | return [elem for piece in pieces for elem in [constant, piece]] | From a sequence create another sequence where every second element
is from the original sequence and the odd elements are the prefix.
eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] | From a sequence create another sequence where every second element
is from the original sequence and the odd elements are the prefix. | [
"From",
"a",
"sequence",
"create",
"another",
"sequence",
"where",
"every",
"second",
"element",
"is",
"from",
"the",
"original",
"sequence",
"and",
"the",
"odd",
"elements",
"are",
"the",
"prefix",
"."
] | def prefix_with(constant, pieces):
""" From a sequence create another sequence where every second element
is from the original sequence and the odd elements are the prefix.
eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """
return [elem for piece in pieces for elem in [constant, piece]] | [
"def",
"prefix_with",
"(",
"constant",
",",
"pieces",
")",
":",
"return",
"[",
"elem",
"for",
"piece",
"in",
"pieces",
"for",
"elem",
"in",
"[",
"constant",
",",
"piece",
"]",
"]"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/tools/scan-build-py/libscanbuild/analyze.py#L103-L109 | |
clementine-player/Clementine | 111379dfd027802b59125829fcf87e3e1d0ad73b | dist/cpplint.py | python | FileInfo.FullName | (self) | return os.path.abspath(self._filename).replace('\\', '/') | Make Windows paths like Unix. | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix",
"."
] | def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/') | [
"def",
"FullName",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L978-L980 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | Function.WriteDestinationInitalizationValidation | (self, f) | Writes the client side destintion initialization validation. | Writes the client side destintion initialization validation. | [
"Writes",
"the",
"client",
"side",
"destintion",
"initialization",
"validation",
"."
] | def WriteDestinationInitalizationValidation(self, f):
"""Writes the client side destintion initialization validation."""
self.type_handler.WriteDestinationInitalizationValidation(self, f) | [
"def",
"WriteDestinationInitalizationValidation",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"type_handler",
".",
"WriteDestinationInitalizationValidation",
"(",
"self",
",",
"f",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9667-L9669 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | greater_equal | (x1, x2, out=None) | return _ufunc_helper(x1, x2, _npi.greater_equal, _np.greater_equal, _npi.greater_equal_scalar,
_npi.less_equal_scalar, out) | Return the truth value of (x1 >= x2) element-wise.
Parameters
----------
x1, x2 : _Symbol or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : Dummy parameter, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : _Symbol or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.greater_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[ True, True, True],
[ True, True, True]])
>>> np.greater_equal(1, np.ones(1))
array([True]) | Return the truth value of (x1 >= x2) element-wise.
Parameters
----------
x1, x2 : _Symbol or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : Dummy parameter, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : _Symbol or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.greater_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[ True, True, True],
[ True, True, True]])
>>> np.greater_equal(1, np.ones(1))
array([True]) | [
"Return",
"the",
"truth",
"value",
"of",
"(",
"x1",
">",
"=",
"x2",
")",
"element",
"-",
"wise",
".",
"Parameters",
"----------",
"x1",
"x2",
":",
"_Symbol",
"or",
"scalars",
"Input",
"arrays",
".",
"If",
"x1",
".",
"shape",
"!",
"=",
"x2",
".",
"shape",
"they",
"must",
"be",
"broadcastable",
"to",
"a",
"common",
"shape",
"(",
"which",
"becomes",
"the",
"shape",
"of",
"the",
"output",
")",
".",
"out",
":",
"Dummy",
"parameter",
"optional",
"A",
"location",
"into",
"which",
"the",
"result",
"is",
"stored",
".",
"If",
"provided",
"it",
"must",
"have",
"a",
"shape",
"that",
"the",
"inputs",
"broadcast",
"to",
".",
"If",
"not",
"provided",
"or",
"None",
"a",
"freshly",
"-",
"allocated",
"array",
"is",
"returned",
".",
"Returns",
"-------",
"out",
":",
"_Symbol",
"or",
"scalar",
"Output",
"array",
"of",
"type",
"bool",
"element",
"-",
"wise",
"comparison",
"of",
"x1",
"and",
"x2",
".",
"This",
"is",
"a",
"scalar",
"if",
"both",
"x1",
"and",
"x2",
"are",
"scalars",
".",
"See",
"Also",
"--------",
"equal",
"greater",
"greater_equal",
"less",
"less_equal",
"Examples",
"--------",
">>>",
"np",
".",
"greater_equal",
"(",
"np",
".",
"ones",
"(",
"2",
"1",
"))",
"np",
".",
"zeros",
"(",
"1",
"3",
"))",
"array",
"(",
"[[",
"True",
"True",
"True",
"]",
"[",
"True",
"True",
"True",
"]]",
")",
">>>",
"np",
".",
"greater_equal",
"(",
"1",
"np",
".",
"ones",
"(",
"1",
"))",
"array",
"(",
"[",
"True",
"]",
")"
] | def greater_equal(x1, x2, out=None):
"""
Return the truth value of (x1 >= x2) element-wise.
Parameters
----------
x1, x2 : _Symbol or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : Dummy parameter, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : _Symbol or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
equal, greater, greater_equal, less, less_equal
Examples
--------
>>> np.greater_equal(np.ones(2, 1)), np.zeros(1, 3))
array([[ True, True, True],
[ True, True, True]])
>>> np.greater_equal(1, np.ones(1))
array([True])
"""
return _ufunc_helper(x1, x2, _npi.greater_equal, _np.greater_equal, _npi.greater_equal_scalar,
_npi.less_equal_scalar, out) | [
"def",
"greater_equal",
"(",
"x1",
",",
"x2",
",",
"out",
"=",
"None",
")",
":",
"return",
"_ufunc_helper",
"(",
"x1",
",",
"x2",
",",
"_npi",
".",
"greater_equal",
",",
"_np",
".",
"greater_equal",
",",
"_npi",
".",
"greater_equal_scalar",
",",
"_npi",
".",
"less_equal_scalar",
",",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L6470-L6499 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xpathParserContext.xpathNextParent | (self, cur) | return __tmp | Traversal function for the "parent" direction The parent
axis contains the parent of the context node, if there is
one. | Traversal function for the "parent" direction The parent
axis contains the parent of the context node, if there is
one. | [
"Traversal",
"function",
"for",
"the",
"parent",
"direction",
"The",
"parent",
"axis",
"contains",
"the",
"parent",
"of",
"the",
"context",
"node",
"if",
"there",
"is",
"one",
"."
] | def xpathNextParent(self, cur):
"""Traversal function for the "parent" direction The parent
axis contains the parent of the context node, if there is
one. """
if cur is None: cur__o = None
else: cur__o = cur._o
ret = libxml2mod.xmlXPathNextParent(self._o, cur__o)
if ret is None:raise xpathError('xmlXPathNextParent() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"xpathNextParent",
"(",
"self",
",",
"cur",
")",
":",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",
"else",
":",
"cur__o",
"=",
"cur",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathNextParent",
"(",
"self",
".",
"_o",
",",
"cur__o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathNextParent() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L7708-L7717 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.IndicatorStart | (*args, **kwargs) | return _stc.StyledTextCtrl_IndicatorStart(*args, **kwargs) | IndicatorStart(self, int indicator, int position) -> int
Where does a particular indicator start? | IndicatorStart(self, int indicator, int position) -> int | [
"IndicatorStart",
"(",
"self",
"int",
"indicator",
"int",
"position",
")",
"-",
">",
"int"
] | def IndicatorStart(*args, **kwargs):
"""
IndicatorStart(self, int indicator, int position) -> int
Where does a particular indicator start?
"""
return _stc.StyledTextCtrl_IndicatorStart(*args, **kwargs) | [
"def",
"IndicatorStart",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_IndicatorStart",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L5711-L5717 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/input/euphonicloader.py | python | EuphonicLoader.read_vibrational_or_phonon_data | (self) | return self._rearrange_data(data=file_data) | Get AbinsData (structure and modes) from force constants data.
Frequencies/displacements are interpolated using the Euphonic library
over a regular q-point mesh. The mesh is determined by a Moreno-Soler
realspace cutoff, related to the size of an equivalent
supercell. Meshes are rounded up so a very small cutoff will yield
gamma-point-only sampling. | Get AbinsData (structure and modes) from force constants data. | [
"Get",
"AbinsData",
"(",
"structure",
"and",
"modes",
")",
"from",
"force",
"constants",
"data",
"."
] | def read_vibrational_or_phonon_data(self):
"""Get AbinsData (structure and modes) from force constants data.
Frequencies/displacements are interpolated using the Euphonic library
over a regular q-point mesh. The mesh is determined by a Moreno-Soler
realspace cutoff, related to the size of an equivalent
supercell. Meshes are rounded up so a very small cutoff will yield
gamma-point-only sampling.
"""
if not euphonic_available():
raise ImportError("Could not import Euphonic library; this is "
"required to import force constants from Phonopy or .castep_bin.")
cutoff = sampling_parameters['force_constants']['qpt_cutoff']
modes = euphonic_calculate_modes(filename=self._clerk.get_input_filename(), cutoff=cutoff)
unit_cell = modes.crystal.cell_vectors.to('angstrom').magnitude
atoms = {f'atom_{atom_index}': {'symbol': str(atom_type),
'sort': atom_index,
'coord': unit_cell.T.dot(atom_r),
'mass': mass}
for atom_index, atom_type, atom_r, mass in zip(range(modes.crystal.n_atoms),
modes.crystal.atom_type,
modes.crystal.atom_r,
modes.crystal.atom_mass.to('amu').magnitude)}
file_data = {'frequencies': modes.frequencies.to('1/cm').magnitude,
'weights': modes.weights,
'k_vectors': modes.qpts,
'atomic_displacements': np.swapaxes(modes.eigenvectors, 1, 2),
'unit_cell': unit_cell,
'atoms': atoms}
# save stuff to hdf file
save_keys = ["frequencies", "weights", "k_vectors", "atomic_displacements", "unit_cell", "atoms"]
data_to_save = {key: file_data[key] for key in save_keys}
self.save_ab_initio_data(data=data_to_save)
return self._rearrange_data(data=file_data) | [
"def",
"read_vibrational_or_phonon_data",
"(",
"self",
")",
":",
"if",
"not",
"euphonic_available",
"(",
")",
":",
"raise",
"ImportError",
"(",
"\"Could not import Euphonic library; this is \"",
"\"required to import force constants from Phonopy or .castep_bin.\"",
")",
"cutoff",
"=",
"sampling_parameters",
"[",
"'force_constants'",
"]",
"[",
"'qpt_cutoff'",
"]",
"modes",
"=",
"euphonic_calculate_modes",
"(",
"filename",
"=",
"self",
".",
"_clerk",
".",
"get_input_filename",
"(",
")",
",",
"cutoff",
"=",
"cutoff",
")",
"unit_cell",
"=",
"modes",
".",
"crystal",
".",
"cell_vectors",
".",
"to",
"(",
"'angstrom'",
")",
".",
"magnitude",
"atoms",
"=",
"{",
"f'atom_{atom_index}'",
":",
"{",
"'symbol'",
":",
"str",
"(",
"atom_type",
")",
",",
"'sort'",
":",
"atom_index",
",",
"'coord'",
":",
"unit_cell",
".",
"T",
".",
"dot",
"(",
"atom_r",
")",
",",
"'mass'",
":",
"mass",
"}",
"for",
"atom_index",
",",
"atom_type",
",",
"atom_r",
",",
"mass",
"in",
"zip",
"(",
"range",
"(",
"modes",
".",
"crystal",
".",
"n_atoms",
")",
",",
"modes",
".",
"crystal",
".",
"atom_type",
",",
"modes",
".",
"crystal",
".",
"atom_r",
",",
"modes",
".",
"crystal",
".",
"atom_mass",
".",
"to",
"(",
"'amu'",
")",
".",
"magnitude",
")",
"}",
"file_data",
"=",
"{",
"'frequencies'",
":",
"modes",
".",
"frequencies",
".",
"to",
"(",
"'1/cm'",
")",
".",
"magnitude",
",",
"'weights'",
":",
"modes",
".",
"weights",
",",
"'k_vectors'",
":",
"modes",
".",
"qpts",
",",
"'atomic_displacements'",
":",
"np",
".",
"swapaxes",
"(",
"modes",
".",
"eigenvectors",
",",
"1",
",",
"2",
")",
",",
"'unit_cell'",
":",
"unit_cell",
",",
"'atoms'",
":",
"atoms",
"}",
"# save stuff to hdf file",
"save_keys",
"=",
"[",
"\"frequencies\"",
",",
"\"weights\"",
",",
"\"k_vectors\"",
",",
"\"atomic_displacements\"",
",",
"\"unit_cell\"",
",",
"\"atoms\"",
"]",
"data_to_save",
"=",
"{",
"key",
":",
"file_data",
"[",
"key",
"]",
"for",
"key",
"in",
"save_keys",
"}",
"self",
".",
"save_ab_initio_data",
"(",
"data",
"=",
"data_to_save",
")",
"return",
"self",
".",
"_rearrange_data",
"(",
"data",
"=",
"file_data",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/input/euphonicloader.py#L32-L71 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Entry.__init__ | (self, master=None, cnf={}, **kw) | Construct an entry widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, cursor,
exportselection, fg, font, foreground, highlightbackground,
highlightcolor, highlightthickness, insertbackground,
insertborderwidth, insertofftime, insertontime, insertwidth,
invalidcommand, invcmd, justify, relief, selectbackground,
selectborderwidth, selectforeground, show, state, takefocus,
textvariable, validate, validatecommand, vcmd, width,
xscrollcommand. | Construct an entry widget with the parent MASTER. | [
"Construct",
"an",
"entry",
"widget",
"with",
"the",
"parent",
"MASTER",
"."
] | def __init__(self, master=None, cnf={}, **kw):
"""Construct an entry widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, cursor,
exportselection, fg, font, foreground, highlightbackground,
highlightcolor, highlightthickness, insertbackground,
insertborderwidth, insertofftime, insertontime, insertwidth,
invalidcommand, invcmd, justify, relief, selectbackground,
selectborderwidth, selectforeground, show, state, takefocus,
textvariable, validate, validatecommand, vcmd, width,
xscrollcommand."""
Widget.__init__(self, master, 'entry', cnf, kw) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"cnf",
"=",
"{",
"}",
",",
"*",
"*",
"kw",
")",
":",
"Widget",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"'entry'",
",",
"cnf",
",",
"kw",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2436-L2447 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/_tstutils.py | python | aps11_f | (x, n) | return (n * x - 1) / ((n - 1) * x) | r"""Rational function with a zero at x=1/n and a pole at x=0 | r"""Rational function with a zero at x=1/n and a pole at x=0 | [
"r",
"Rational",
"function",
"with",
"a",
"zero",
"at",
"x",
"=",
"1",
"/",
"n",
"and",
"a",
"pole",
"at",
"x",
"=",
"0"
] | def aps11_f(x, n):
r"""Rational function with a zero at x=1/n and a pole at x=0"""
return (n * x - 1) / ((n - 1) * x) | [
"def",
"aps11_f",
"(",
"x",
",",
"n",
")",
":",
"return",
"(",
"n",
"*",
"x",
"-",
"1",
")",
"/",
"(",
"(",
"n",
"-",
"1",
")",
"*",
"x",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_tstutils.py#L294-L296 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_arrays.py | python | _get_num_samples_or_steps | (ins, batch_size, steps_per_epoch) | return training_utils.check_num_samples(ins, batch_size, steps_per_epoch,
'steps_per_epoch') | Returns total number of samples (when training in batch mode) or steps. | Returns total number of samples (when training in batch mode) or steps. | [
"Returns",
"total",
"number",
"of",
"samples",
"(",
"when",
"training",
"in",
"batch",
"mode",
")",
"or",
"steps",
"."
] | def _get_num_samples_or_steps(ins, batch_size, steps_per_epoch):
"""Returns total number of samples (when training in batch mode) or steps."""
if steps_per_epoch:
return steps_per_epoch
return training_utils.check_num_samples(ins, batch_size, steps_per_epoch,
'steps_per_epoch') | [
"def",
"_get_num_samples_or_steps",
"(",
"ins",
",",
"batch_size",
",",
"steps_per_epoch",
")",
":",
"if",
"steps_per_epoch",
":",
"return",
"steps_per_epoch",
"return",
"training_utils",
".",
"check_num_samples",
"(",
"ins",
",",
"batch_size",
",",
"steps_per_epoch",
",",
"'steps_per_epoch'",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_arrays.py#L489-L494 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/cookies.py | python | RequestsCookieJar.iteritems | (self) | Dict-like iteritems() that returns an iterator of name-value tuples
from the jar.
.. seealso:: iterkeys() and itervalues(). | Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. | [
"Dict",
"-",
"like",
"iteritems",
"()",
"that",
"returns",
"an",
"iterator",
"of",
"name",
"-",
"value",
"tuples",
"from",
"the",
"jar",
"."
] | def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
from the jar.
.. seealso:: iterkeys() and itervalues().
"""
for cookie in iter(self):
yield cookie.name, cookie.value | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"name",
",",
"cookie",
".",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/cookies.py#L252-L259 | ||
facebookresearch/habitat-sim | 63b6c71d9ca8adaefb140b198196f5d0ca1f1e34 | src_python/habitat_sim/utils/common.py | python | angle_between_quats | (q1: qt.quaternion, q2: qt.quaternion) | return 2 * np.arctan2(np.linalg.norm(dq.imag), np.abs(dq.real)) | r"""Computes the angular distance between two quaternions
:return: The angular distance between q1 and q2 in radians | r"""Computes the angular distance between two quaternions | [
"r",
"Computes",
"the",
"angular",
"distance",
"between",
"two",
"quaternions"
] | def angle_between_quats(q1: qt.quaternion, q2: qt.quaternion) -> float:
r"""Computes the angular distance between two quaternions
:return: The angular distance between q1 and q2 in radians
"""
q1_inv = np.conjugate(q1)
dq = q1_inv * q2
return 2 * np.arctan2(np.linalg.norm(dq.imag), np.abs(dq.real)) | [
"def",
"angle_between_quats",
"(",
"q1",
":",
"qt",
".",
"quaternion",
",",
"q2",
":",
"qt",
".",
"quaternion",
")",
"->",
"float",
":",
"q1_inv",
"=",
"np",
".",
"conjugate",
"(",
"q1",
")",
"dq",
"=",
"q1_inv",
"*",
"q2",
"return",
"2",
"*",
"np",
".",
"arctan2",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"dq",
".",
"imag",
")",
",",
"np",
".",
"abs",
"(",
"dq",
".",
"real",
")",
")"
] | https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/src_python/habitat_sim/utils/common.py#L121-L130 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xmlDoc.newEntity | (self, name, type, ExternalID, SystemID, content) | return __tmp | Create a new entity, this differs from xmlAddDocEntity()
that if the document is None or has no internal subset
defined, then an unlinked entity structure will be
returned, it is then the responsability of the caller to
link it to the document later or free it when not needed
anymore. | Create a new entity, this differs from xmlAddDocEntity()
that if the document is None or has no internal subset
defined, then an unlinked entity structure will be
returned, it is then the responsability of the caller to
link it to the document later or free it when not needed
anymore. | [
"Create",
"a",
"new",
"entity",
"this",
"differs",
"from",
"xmlAddDocEntity",
"()",
"that",
"if",
"the",
"document",
"is",
"None",
"or",
"has",
"no",
"internal",
"subset",
"defined",
"then",
"an",
"unlinked",
"entity",
"structure",
"will",
"be",
"returned",
"it",
"is",
"then",
"the",
"responsability",
"of",
"the",
"caller",
"to",
"link",
"it",
"to",
"the",
"document",
"later",
"or",
"free",
"it",
"when",
"not",
"needed",
"anymore",
"."
] | def newEntity(self, name, type, ExternalID, SystemID, content):
"""Create a new entity, this differs from xmlAddDocEntity()
that if the document is None or has no internal subset
defined, then an unlinked entity structure will be
returned, it is then the responsability of the caller to
link it to the document later or free it when not needed
anymore. """
ret = libxml2mod.xmlNewEntity(self._o, name, type, ExternalID, SystemID, content)
if ret is None:raise treeError('xmlNewEntity() failed')
__tmp = xmlEntity(_obj=ret)
return __tmp | [
"def",
"newEntity",
"(",
"self",
",",
"name",
",",
"type",
",",
"ExternalID",
",",
"SystemID",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewEntity",
"(",
"self",
".",
"_o",
",",
"name",
",",
"type",
",",
"ExternalID",
",",
"SystemID",
",",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewEntity() failed'",
")",
"__tmp",
"=",
"xmlEntity",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4154-L4164 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/xrc.py | python | XmlResource.ClearHandlers | (*args, **kwargs) | return _xrc.XmlResource_ClearHandlers(*args, **kwargs) | ClearHandlers(self) | ClearHandlers(self) | [
"ClearHandlers",
"(",
"self",
")"
] | def ClearHandlers(*args, **kwargs):
"""ClearHandlers(self)"""
return _xrc.XmlResource_ClearHandlers(*args, **kwargs) | [
"def",
"ClearHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResource_ClearHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L110-L112 | |
CleverRaven/Cataclysm-DDA | 03e7363df0835ec1b39da973ea29f26f27833b38 | tools/json_tools/util.py | python | ui_counts_to_columns | (counts) | Take a Counter instance and display in single fixed width key:value
column. | Take a Counter instance and display in single fixed width key:value
column. | [
"Take",
"a",
"Counter",
"instance",
"and",
"display",
"in",
"single",
"fixed",
"width",
"key",
":",
"value",
"column",
"."
] | def ui_counts_to_columns(counts):
"""Take a Counter instance and display in single fixed width key:value
column.
"""
# Values in left column, counts in right, left
# column as wide as longest string length.
key_vals = counts.most_common()
key_field_len = len(max(list(counts.keys()), key=len)) + 1
output_template = "%%-%ds: %%s" % key_field_len
for k_v in key_vals:
print(output_template % k_v) | [
"def",
"ui_counts_to_columns",
"(",
"counts",
")",
":",
"# Values in left column, counts in right, left",
"# column as wide as longest string length.",
"key_vals",
"=",
"counts",
".",
"most_common",
"(",
")",
"key_field_len",
"=",
"len",
"(",
"max",
"(",
"list",
"(",
"counts",
".",
"keys",
"(",
")",
")",
",",
"key",
"=",
"len",
")",
")",
"+",
"1",
"output_template",
"=",
"\"%%-%ds: %%s\"",
"%",
"key_field_len",
"for",
"k_v",
"in",
"key_vals",
":",
"print",
"(",
"output_template",
"%",
"k_v",
")"
] | https://github.com/CleverRaven/Cataclysm-DDA/blob/03e7363df0835ec1b39da973ea29f26f27833b38/tools/json_tools/util.py#L305-L315 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/procrouting/proc.py | python | run_fnodfcc | (name, **kwargs) | return fnocc_wfn | Function encoding sequence of PSI module calls for
a DF-CCSD(T) computation.
>>> set cc_type df
>>> energy('fno-ccsd(t)') | Function encoding sequence of PSI module calls for
a DF-CCSD(T) computation. | [
"Function",
"encoding",
"sequence",
"of",
"PSI",
"module",
"calls",
"for",
"a",
"DF",
"-",
"CCSD",
"(",
"T",
")",
"computation",
"."
] | def run_fnodfcc(name, **kwargs):
"""Function encoding sequence of PSI module calls for
a DF-CCSD(T) computation.
>>> set cc_type df
>>> energy('fno-ccsd(t)')
"""
kwargs = p4util.kwargs_lower(kwargs)
# stash user options
optstash = p4util.OptionsState(
['FNOCC', 'COMPUTE_TRIPLES'],
['FNOCC', 'DFCC'],
['FNOCC', 'NAT_ORBS'],
['FNOCC', 'RUN_CEPA'],
['FNOCC', 'DF_BASIS_CC'],
['SCF', 'DF_BASIS_SCF'],
['SCF', 'DF_INTS_IO'])
core.set_local_option('FNOCC', 'DFCC', True)
core.set_local_option('FNOCC', 'RUN_CEPA', False)
# throw an exception for open-shells
if core.get_option('SCF', 'REFERENCE') != 'RHF':
raise ValidationError(f"""Error: {name} requires 'reference rhf'.""")
def set_cholesky_from(mtd_type):
type_val = core.get_global_option(mtd_type)
if type_val == 'CD':
core.set_local_option('FNOCC', 'DF_BASIS_CC', 'CHOLESKY')
# Alter default algorithm
if not core.has_global_option_changed('SCF_TYPE'):
optstash.add_option(['SCF_TYPE'])
core.set_global_option('SCF_TYPE', 'CD')
core.print_out(""" SCF Algorithm Type (re)set to CD.\n""")
elif type_val in ['DISK_DF', 'DF']:
if core.get_option('FNOCC', 'DF_BASIS_CC') == 'CHOLESKY':
core.set_local_option('FNOCC', 'DF_BASIS_CC', '')
proc_util.check_disk_df(name.upper(), optstash)
else:
raise ValidationError("""Invalid type '%s' for DFCC""" % type_val)
# triples?
if name == 'ccsd':
core.set_local_option('FNOCC', 'COMPUTE_TRIPLES', False)
set_cholesky_from('CC_TYPE')
elif name == 'ccsd(t)':
core.set_local_option('FNOCC', 'COMPUTE_TRIPLES', True)
set_cholesky_from('CC_TYPE')
elif name == 'fno-ccsd':
core.set_local_option('FNOCC', 'COMPUTE_TRIPLES', False)
core.set_local_option('FNOCC', 'NAT_ORBS', True)
set_cholesky_from('CC_TYPE')
elif name == 'fno-ccsd(t)':
core.set_local_option('FNOCC', 'COMPUTE_TRIPLES', True)
core.set_local_option('FNOCC', 'NAT_ORBS', True)
set_cholesky_from('CC_TYPE')
if core.get_global_option('SCF_TYPE') not in ['CD', 'DISK_DF']:
raise ValidationError("""Invalid scf_type for DFCC.""")
# save DF or CD ints generated by SCF for use in CC
core.set_local_option('SCF', 'DF_INTS_IO', 'SAVE')
ref_wfn = kwargs.get('ref_wfn', None)
if ref_wfn is None:
ref_wfn = scf_helper(name, use_c1=True, **kwargs) # C1 certified
else:
if ref_wfn.molecule().schoenflies_symbol() != 'c1':
raise ValidationError(""" FNOCC does not make use of molecular symmetry: """
"""reference wavefunction must be C1.\n""")
core.print_out(" Constructing Basis Sets for FNOCC...\n\n")
scf_aux_basis = core.BasisSet.build(ref_wfn.molecule(), "DF_BASIS_SCF",
core.get_option("SCF", "DF_BASIS_SCF"),
"JKFIT", core.get_global_option('BASIS'),
puream=ref_wfn.basisset().has_puream())
ref_wfn.set_basisset("DF_BASIS_SCF", scf_aux_basis)
aux_basis = core.BasisSet.build(ref_wfn.molecule(), "DF_BASIS_CC",
core.get_global_option("DF_BASIS_CC"),
"RIFIT", core.get_global_option("BASIS"))
ref_wfn.set_basisset("DF_BASIS_CC", aux_basis)
if core.get_global_option("RELATIVISTIC") in ["X2C", "DKH"]:
rel_bas = core.BasisSet.build(ref_wfn.molecule(), "BASIS_RELATIVISTIC",
core.get_option("SCF", "BASIS_RELATIVISTIC"),
"DECON", core.get_global_option('BASIS'),
puream=ref_wfn.basisset().has_puream())
ref_wfn.set_basisset('BASIS_RELATIVISTIC',rel_bas)
fnocc_wfn = core.fnocc(ref_wfn)
# Shove variables into global space
for k, v in fnocc_wfn.variables().items():
core.set_variable(k, v)
optstash.restore()
return fnocc_wfn | [
"def",
"run_fnodfcc",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"p4util",
".",
"kwargs_lower",
"(",
"kwargs",
")",
"# stash user options",
"optstash",
"=",
"p4util",
".",
"OptionsState",
"(",
"[",
"'FNOCC'",
",",
"'COMPUTE_TRIPLES'",
"]",
",",
"[",
"'FNOCC'",
",",
"'DFCC'",
"]",
",",
"[",
"'FNOCC'",
",",
"'NAT_ORBS'",
"]",
",",
"[",
"'FNOCC'",
",",
"'RUN_CEPA'",
"]",
",",
"[",
"'FNOCC'",
",",
"'DF_BASIS_CC'",
"]",
",",
"[",
"'SCF'",
",",
"'DF_BASIS_SCF'",
"]",
",",
"[",
"'SCF'",
",",
"'DF_INTS_IO'",
"]",
")",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'DFCC'",
",",
"True",
")",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'RUN_CEPA'",
",",
"False",
")",
"# throw an exception for open-shells",
"if",
"core",
".",
"get_option",
"(",
"'SCF'",
",",
"'REFERENCE'",
")",
"!=",
"'RHF'",
":",
"raise",
"ValidationError",
"(",
"f\"\"\"Error: {name} requires 'reference rhf'.\"\"\"",
")",
"def",
"set_cholesky_from",
"(",
"mtd_type",
")",
":",
"type_val",
"=",
"core",
".",
"get_global_option",
"(",
"mtd_type",
")",
"if",
"type_val",
"==",
"'CD'",
":",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'DF_BASIS_CC'",
",",
"'CHOLESKY'",
")",
"# Alter default algorithm",
"if",
"not",
"core",
".",
"has_global_option_changed",
"(",
"'SCF_TYPE'",
")",
":",
"optstash",
".",
"add_option",
"(",
"[",
"'SCF_TYPE'",
"]",
")",
"core",
".",
"set_global_option",
"(",
"'SCF_TYPE'",
",",
"'CD'",
")",
"core",
".",
"print_out",
"(",
"\"\"\" SCF Algorithm Type (re)set to CD.\\n\"\"\"",
")",
"elif",
"type_val",
"in",
"[",
"'DISK_DF'",
",",
"'DF'",
"]",
":",
"if",
"core",
".",
"get_option",
"(",
"'FNOCC'",
",",
"'DF_BASIS_CC'",
")",
"==",
"'CHOLESKY'",
":",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'DF_BASIS_CC'",
",",
"''",
")",
"proc_util",
".",
"check_disk_df",
"(",
"name",
".",
"upper",
"(",
")",
",",
"optstash",
")",
"else",
":",
"raise",
"ValidationError",
"(",
"\"\"\"Invalid type '%s' for DFCC\"\"\"",
"%",
"type_val",
")",
"# triples?",
"if",
"name",
"==",
"'ccsd'",
":",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'COMPUTE_TRIPLES'",
",",
"False",
")",
"set_cholesky_from",
"(",
"'CC_TYPE'",
")",
"elif",
"name",
"==",
"'ccsd(t)'",
":",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'COMPUTE_TRIPLES'",
",",
"True",
")",
"set_cholesky_from",
"(",
"'CC_TYPE'",
")",
"elif",
"name",
"==",
"'fno-ccsd'",
":",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'COMPUTE_TRIPLES'",
",",
"False",
")",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'NAT_ORBS'",
",",
"True",
")",
"set_cholesky_from",
"(",
"'CC_TYPE'",
")",
"elif",
"name",
"==",
"'fno-ccsd(t)'",
":",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'COMPUTE_TRIPLES'",
",",
"True",
")",
"core",
".",
"set_local_option",
"(",
"'FNOCC'",
",",
"'NAT_ORBS'",
",",
"True",
")",
"set_cholesky_from",
"(",
"'CC_TYPE'",
")",
"if",
"core",
".",
"get_global_option",
"(",
"'SCF_TYPE'",
")",
"not",
"in",
"[",
"'CD'",
",",
"'DISK_DF'",
"]",
":",
"raise",
"ValidationError",
"(",
"\"\"\"Invalid scf_type for DFCC.\"\"\"",
")",
"# save DF or CD ints generated by SCF for use in CC",
"core",
".",
"set_local_option",
"(",
"'SCF'",
",",
"'DF_INTS_IO'",
",",
"'SAVE'",
")",
"ref_wfn",
"=",
"kwargs",
".",
"get",
"(",
"'ref_wfn'",
",",
"None",
")",
"if",
"ref_wfn",
"is",
"None",
":",
"ref_wfn",
"=",
"scf_helper",
"(",
"name",
",",
"use_c1",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"# C1 certified",
"else",
":",
"if",
"ref_wfn",
".",
"molecule",
"(",
")",
".",
"schoenflies_symbol",
"(",
")",
"!=",
"'c1'",
":",
"raise",
"ValidationError",
"(",
"\"\"\" FNOCC does not make use of molecular symmetry: \"\"\"",
"\"\"\"reference wavefunction must be C1.\\n\"\"\"",
")",
"core",
".",
"print_out",
"(",
"\" Constructing Basis Sets for FNOCC...\\n\\n\"",
")",
"scf_aux_basis",
"=",
"core",
".",
"BasisSet",
".",
"build",
"(",
"ref_wfn",
".",
"molecule",
"(",
")",
",",
"\"DF_BASIS_SCF\"",
",",
"core",
".",
"get_option",
"(",
"\"SCF\"",
",",
"\"DF_BASIS_SCF\"",
")",
",",
"\"JKFIT\"",
",",
"core",
".",
"get_global_option",
"(",
"'BASIS'",
")",
",",
"puream",
"=",
"ref_wfn",
".",
"basisset",
"(",
")",
".",
"has_puream",
"(",
")",
")",
"ref_wfn",
".",
"set_basisset",
"(",
"\"DF_BASIS_SCF\"",
",",
"scf_aux_basis",
")",
"aux_basis",
"=",
"core",
".",
"BasisSet",
".",
"build",
"(",
"ref_wfn",
".",
"molecule",
"(",
")",
",",
"\"DF_BASIS_CC\"",
",",
"core",
".",
"get_global_option",
"(",
"\"DF_BASIS_CC\"",
")",
",",
"\"RIFIT\"",
",",
"core",
".",
"get_global_option",
"(",
"\"BASIS\"",
")",
")",
"ref_wfn",
".",
"set_basisset",
"(",
"\"DF_BASIS_CC\"",
",",
"aux_basis",
")",
"if",
"core",
".",
"get_global_option",
"(",
"\"RELATIVISTIC\"",
")",
"in",
"[",
"\"X2C\"",
",",
"\"DKH\"",
"]",
":",
"rel_bas",
"=",
"core",
".",
"BasisSet",
".",
"build",
"(",
"ref_wfn",
".",
"molecule",
"(",
")",
",",
"\"BASIS_RELATIVISTIC\"",
",",
"core",
".",
"get_option",
"(",
"\"SCF\"",
",",
"\"BASIS_RELATIVISTIC\"",
")",
",",
"\"DECON\"",
",",
"core",
".",
"get_global_option",
"(",
"'BASIS'",
")",
",",
"puream",
"=",
"ref_wfn",
".",
"basisset",
"(",
")",
".",
"has_puream",
"(",
")",
")",
"ref_wfn",
".",
"set_basisset",
"(",
"'BASIS_RELATIVISTIC'",
",",
"rel_bas",
")",
"fnocc_wfn",
"=",
"core",
".",
"fnocc",
"(",
"ref_wfn",
")",
"# Shove variables into global space",
"for",
"k",
",",
"v",
"in",
"fnocc_wfn",
".",
"variables",
"(",
")",
".",
"items",
"(",
")",
":",
"core",
".",
"set_variable",
"(",
"k",
",",
"v",
")",
"optstash",
".",
"restore",
"(",
")",
"return",
"fnocc_wfn"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/proc.py#L4796-L4897 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/rpc/__init__.py | python | RpcServer.start | (
self,
rep_address: str,
pub_address: str,
server_secretkey_path: str = "",
username: str = "",
password: str = ""
) | Start RpcServer | Start RpcServer | [
"Start",
"RpcServer"
] | def start(
self,
rep_address: str,
pub_address: str,
server_secretkey_path: str = "",
username: str = "",
password: str = ""
) -> None:
"""
Start RpcServer
"""
if self.__active:
return
# Start authenticator
if server_secretkey_path:
self.__authenticator = ThreadAuthenticator(self.__context)
self.__authenticator.start()
self.__authenticator.configure_curve(
domain="*",
location=zmq.auth.CURVE_ALLOW_ANY
)
publickey, secretkey = zmq.auth.load_certificate(server_secretkey_path)
self.__socket_pub.curve_secretkey = secretkey
self.__socket_pub.curve_publickey = publickey
self.__socket_pub.curve_server = True
self.__socket_rep.curve_secretkey = secretkey
self.__socket_rep.curve_publickey = publickey
self.__socket_rep.curve_server = True
elif username and password:
self.__authenticator = ThreadAuthenticator(self.__context)
self.__authenticator.start()
self.__authenticator.configure_plain(
domain="*",
passwords={username: password}
)
self.__socket_pub.plain_server = True
self.__socket_rep.plain_server = True
# Bind socket address
self.__socket_rep.bind(rep_address)
self.__socket_pub.bind(pub_address)
# Start RpcServer status
self.__active = True
# Start RpcServer thread
self.__thread = threading.Thread(target=self.run)
self.__thread.start() | [
"def",
"start",
"(",
"self",
",",
"rep_address",
":",
"str",
",",
"pub_address",
":",
"str",
",",
"server_secretkey_path",
":",
"str",
"=",
"\"\"",
",",
"username",
":",
"str",
"=",
"\"\"",
",",
"password",
":",
"str",
"=",
"\"\"",
")",
"->",
"None",
":",
"if",
"self",
".",
"__active",
":",
"return",
"# Start authenticator",
"if",
"server_secretkey_path",
":",
"self",
".",
"__authenticator",
"=",
"ThreadAuthenticator",
"(",
"self",
".",
"__context",
")",
"self",
".",
"__authenticator",
".",
"start",
"(",
")",
"self",
".",
"__authenticator",
".",
"configure_curve",
"(",
"domain",
"=",
"\"*\"",
",",
"location",
"=",
"zmq",
".",
"auth",
".",
"CURVE_ALLOW_ANY",
")",
"publickey",
",",
"secretkey",
"=",
"zmq",
".",
"auth",
".",
"load_certificate",
"(",
"server_secretkey_path",
")",
"self",
".",
"__socket_pub",
".",
"curve_secretkey",
"=",
"secretkey",
"self",
".",
"__socket_pub",
".",
"curve_publickey",
"=",
"publickey",
"self",
".",
"__socket_pub",
".",
"curve_server",
"=",
"True",
"self",
".",
"__socket_rep",
".",
"curve_secretkey",
"=",
"secretkey",
"self",
".",
"__socket_rep",
".",
"curve_publickey",
"=",
"publickey",
"self",
".",
"__socket_rep",
".",
"curve_server",
"=",
"True",
"elif",
"username",
"and",
"password",
":",
"self",
".",
"__authenticator",
"=",
"ThreadAuthenticator",
"(",
"self",
".",
"__context",
")",
"self",
".",
"__authenticator",
".",
"start",
"(",
")",
"self",
".",
"__authenticator",
".",
"configure_plain",
"(",
"domain",
"=",
"\"*\"",
",",
"passwords",
"=",
"{",
"username",
":",
"password",
"}",
")",
"self",
".",
"__socket_pub",
".",
"plain_server",
"=",
"True",
"self",
".",
"__socket_rep",
".",
"plain_server",
"=",
"True",
"# Bind socket address",
"self",
".",
"__socket_rep",
".",
"bind",
"(",
"rep_address",
")",
"self",
".",
"__socket_pub",
".",
"bind",
"(",
"pub_address",
")",
"# Start RpcServer status",
"self",
".",
"__active",
"=",
"True",
"# Start RpcServer thread",
"self",
".",
"__thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"run",
")",
"self",
".",
"__thread",
".",
"start",
"(",
")"
] | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/rpc/__init__.py#L75-L127 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListMainWindow.ScrollList | (self, dx, dy) | return True | Scrolls the :class:`UltimateListCtrl`.
:param `dx`: if in icon, small icon or report view mode, specifies the number
of pixels to scroll. If in list view mode, `dx` specifies the number of
columns to scroll.
:param `dy`: always specifies the number of pixels to scroll vertically. | Scrolls the :class:`UltimateListCtrl`. | [
"Scrolls",
"the",
":",
"class",
":",
"UltimateListCtrl",
"."
] | def ScrollList(self, dx, dy):
"""
Scrolls the :class:`UltimateListCtrl`.
:param `dx`: if in icon, small icon or report view mode, specifies the number
of pixels to scroll. If in list view mode, `dx` specifies the number of
columns to scroll.
:param `dy`: always specifies the number of pixels to scroll vertically.
"""
if not self.InReportView():
# TODO: this should work in all views but is not implemented now
return False
top, bottom = self.GetVisibleLinesRange()
if bottom == -1:
return 0
self.ResetVisibleLinesRange()
if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
hLine = self.GetLineHeight()
self.Scroll(-1, top + dy/hLine)
else:
self.Scroll(-1, top + dy/SCROLL_UNIT_Y)
if wx.Platform == "__WXMAC__":
# see comment in MoveToItem() for why we do this
self.ResetVisibleLinesRange()
return True | [
"def",
"ScrollList",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"if",
"not",
"self",
".",
"InReportView",
"(",
")",
":",
"# TODO: this should work in all views but is not implemented now",
"return",
"False",
"top",
",",
"bottom",
"=",
"self",
".",
"GetVisibleLinesRange",
"(",
")",
"if",
"bottom",
"==",
"-",
"1",
":",
"return",
"0",
"self",
".",
"ResetVisibleLinesRange",
"(",
")",
"if",
"not",
"self",
".",
"HasAGWFlag",
"(",
"ULC_HAS_VARIABLE_ROW_HEIGHT",
")",
":",
"hLine",
"=",
"self",
".",
"GetLineHeight",
"(",
")",
"self",
".",
"Scroll",
"(",
"-",
"1",
",",
"top",
"+",
"dy",
"/",
"hLine",
")",
"else",
":",
"self",
".",
"Scroll",
"(",
"-",
"1",
",",
"top",
"+",
"dy",
"/",
"SCROLL_UNIT_Y",
")",
"if",
"wx",
".",
"Platform",
"==",
"\"__WXMAC__\"",
":",
"# see comment in MoveToItem() for why we do this",
"self",
".",
"ResetVisibleLinesRange",
"(",
")",
"return",
"True"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L10796-L10827 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecManifestWrapper | (self, arch, *args) | return popen.returncode | Run manifest tool with environment set. Strip out undesirable warning
(some XML blocks are recognized by the OS loader, but not the manifest
tool). | Run manifest tool with environment set. Strip out undesirable warning
(some XML blocks are recognized by the OS loader, but not the manifest
tool). | [
"Run",
"manifest",
"tool",
"with",
"environment",
"set",
".",
"Strip",
"out",
"undesirable",
"warning",
"(",
"some",
"XML",
"blocks",
"are",
"recognized",
"by",
"the",
"OS",
"loader",
"but",
"not",
"the",
"manifest",
"tool",
")",
"."
] | def ExecManifestWrapper(self, arch, *args):
"""Run manifest tool with environment set. Strip out undesirable warning
(some XML blocks are recognized by the OS loader, but not the manifest
tool)."""
env = self._GetEnv(arch)
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = popen.communicate()
for line in out.splitlines():
if line and 'manifest authoring warning 81010002' not in line:
print line
return popen.returncode | [
"def",
"ExecManifestWrapper",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"out",
",",
"_",
"=",
"popen",
".",
"communicate",
"(",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
"and",
"'manifest authoring warning 81010002'",
"not",
"in",
"line",
":",
"print",
"line",
"return",
"popen",
".",
"returncode"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/win_tool.py#L109-L120 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | GridTableBase.GetNumberCols | (*args, **kwargs) | return _grid.GridTableBase_GetNumberCols(*args, **kwargs) | GetNumberCols(self) -> int | GetNumberCols(self) -> int | [
"GetNumberCols",
"(",
"self",
")",
"-",
">",
"int"
] | def GetNumberCols(*args, **kwargs):
"""GetNumberCols(self) -> int"""
return _grid.GridTableBase_GetNumberCols(*args, **kwargs) | [
"def",
"GetNumberCols",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_GetNumberCols",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L806-L808 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py | python | RefVariable.__init__ | (
self, # pylint: disable=super-init-not-called
initial_value=None,
trainable=None,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None,
synchronization=None,
aggregation=None,
shape=None) | Creates a new variable with value `initial_value`.
The new variable is added to the graph collections listed in `collections`,
which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
If `trainable` is `True` the variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
This constructor creates both a `variable` Op and an `assign` Op to set the
variable to its initial value.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, `dtype` must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)
trainable: If `True`, also adds the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default
list of variables to use by the `Optimizer` classes. Defaults to `True`,
unless `synchronization` is set to `ON_READ`, in which case it defaults
to `False`.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device. If not
`None`, caches on another device. Typical use is to cache on the device
where the Ops using the Variable reside, to deduplicate copying through
`Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
variable_def: `VariableDef` protocol buffer. If not `None`, recreates the
Variable object with its contents, referencing the variable's nodes in
the graph, which must already exist. The graph is not changed.
`variable_def` and the other arguments are mutually exclusive.
dtype: If set, initial_value will be converted to the given type. If
`None`, either the datatype will be kept (if `initial_value` is a
Tensor), or `convert_to_tensor` will decide.
expected_shape: A TensorShape. If set, initial_value is expected to have
this shape.
import_scope: Optional `string`. Name scope to add to the `Variable.` Only
used when initializing from protocol buffer.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
shape: (optional) The shape of this variable. If None, the shape of
`initial_value` will be used. When setting this argument to
`tf.TensorShape(None)` (representing an unspecified shape), the variable
can be assigned with values of different shapes.
Raises:
ValueError: If both `variable_def` and initial_value are specified.
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If eager execution is enabled. | Creates a new variable with value `initial_value`. | [
"Creates",
"a",
"new",
"variable",
"with",
"value",
"initial_value",
"."
] | def __init__(
self, # pylint: disable=super-init-not-called
initial_value=None,
trainable=None,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None,
synchronization=None,
aggregation=None,
shape=None):
"""Creates a new variable with value `initial_value`.
The new variable is added to the graph collections listed in `collections`,
which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
If `trainable` is `True` the variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
This constructor creates both a `variable` Op and an `assign` Op to set the
variable to its initial value.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, `dtype` must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)
trainable: If `True`, also adds the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default
list of variables to use by the `Optimizer` classes. Defaults to `True`,
unless `synchronization` is set to `ON_READ`, in which case it defaults
to `False`.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device. If not
`None`, caches on another device. Typical use is to cache on the device
where the Ops using the Variable reside, to deduplicate copying through
`Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
variable_def: `VariableDef` protocol buffer. If not `None`, recreates the
Variable object with its contents, referencing the variable's nodes in
the graph, which must already exist. The graph is not changed.
`variable_def` and the other arguments are mutually exclusive.
dtype: If set, initial_value will be converted to the given type. If
`None`, either the datatype will be kept (if `initial_value` is a
Tensor), or `convert_to_tensor` will decide.
expected_shape: A TensorShape. If set, initial_value is expected to have
this shape.
import_scope: Optional `string`. Name scope to add to the `Variable.` Only
used when initializing from protocol buffer.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
shape: (optional) The shape of this variable. If None, the shape of
`initial_value` will be used. When setting this argument to
`tf.TensorShape(None)` (representing an unspecified shape), the variable
can be assigned with values of different shapes.
Raises:
ValueError: If both `variable_def` and initial_value are specified.
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If eager execution is enabled.
"""
self._in_graph_mode = True
if variable_def:
# If variable_def is provided, recreates the variable from its fields.
if initial_value:
raise ValueError("variable_def and initial_value are mutually "
"exclusive.")
self._init_from_proto(variable_def, import_scope=import_scope)
else:
# Create from initial_value.
self._init_from_args(
initial_value=initial_value,
trainable=trainable,
collections=collections,
validate_shape=validate_shape,
caching_device=caching_device,
name=name,
dtype=dtype,
expected_shape=expected_shape,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation,
shape=shape) | [
"def",
"__init__",
"(",
"self",
",",
"# pylint: disable=super-init-not-called",
"initial_value",
"=",
"None",
",",
"trainable",
"=",
"None",
",",
"collections",
"=",
"None",
",",
"validate_shape",
"=",
"True",
",",
"caching_device",
"=",
"None",
",",
"name",
"=",
"None",
",",
"variable_def",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"expected_shape",
"=",
"None",
",",
"import_scope",
"=",
"None",
",",
"constraint",
"=",
"None",
",",
"synchronization",
"=",
"None",
",",
"aggregation",
"=",
"None",
",",
"shape",
"=",
"None",
")",
":",
"self",
".",
"_in_graph_mode",
"=",
"True",
"if",
"variable_def",
":",
"# If variable_def is provided, recreates the variable from its fields.",
"if",
"initial_value",
":",
"raise",
"ValueError",
"(",
"\"variable_def and initial_value are mutually \"",
"\"exclusive.\"",
")",
"self",
".",
"_init_from_proto",
"(",
"variable_def",
",",
"import_scope",
"=",
"import_scope",
")",
"else",
":",
"# Create from initial_value.",
"self",
".",
"_init_from_args",
"(",
"initial_value",
"=",
"initial_value",
",",
"trainable",
"=",
"trainable",
",",
"collections",
"=",
"collections",
",",
"validate_shape",
"=",
"validate_shape",
",",
"caching_device",
"=",
"caching_device",
",",
"name",
"=",
"name",
",",
"dtype",
"=",
"dtype",
",",
"expected_shape",
"=",
"expected_shape",
",",
"constraint",
"=",
"constraint",
",",
"synchronization",
"=",
"synchronization",
",",
"aggregation",
"=",
"aggregation",
",",
"shape",
"=",
"shape",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py#L1579-L1688 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/common.py | python | is_true_slices | (l) | return [isinstance(k, slice) and not is_null_slice(k) for k in l] | Find non-trivial slices in "l": return a list of booleans with same length. | Find non-trivial slices in "l": return a list of booleans with same length. | [
"Find",
"non",
"-",
"trivial",
"slices",
"in",
"l",
":",
"return",
"a",
"list",
"of",
"booleans",
"with",
"same",
"length",
"."
] | def is_true_slices(l):
"""
Find non-trivial slices in "l": return a list of booleans with same length.
"""
return [isinstance(k, slice) and not is_null_slice(k) for k in l] | [
"def",
"is_true_slices",
"(",
"l",
")",
":",
"return",
"[",
"isinstance",
"(",
"k",
",",
"slice",
")",
"and",
"not",
"is_null_slice",
"(",
"k",
")",
"for",
"k",
"in",
"l",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/common.py#L296-L300 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | benchmarks/operator_benchmark/benchmark_core.py | python | BenchmarkRunner._launch_backward | (self, test_case, iters, print_per_iter=False) | return backward_time | This function runs forward path of an op to get an output. Then the backward path is executed
and the execution time is reported | This function runs forward path of an op to get an output. Then the backward path is executed
and the execution time is reported | [
"This",
"function",
"runs",
"forward",
"path",
"of",
"an",
"op",
"to",
"get",
"an",
"output",
".",
"Then",
"the",
"backward",
"path",
"is",
"executed",
"and",
"the",
"execution",
"time",
"is",
"reported"
] | def _launch_backward(self, test_case, iters, print_per_iter=False):
""" This function runs forward path of an op to get an output. Then the backward path is executed
and the execution time is reported
"""
test_case.run_forward(num_runs=1, print_per_iter=False, cuda_sync=False)
if test_case.framework == "PyTorch":
test_case._output_mean()
backward_time = timeit.timeit(functools.partial(test_case.run_backward, iters,
print_per_iter),
number=1)
return backward_time | [
"def",
"_launch_backward",
"(",
"self",
",",
"test_case",
",",
"iters",
",",
"print_per_iter",
"=",
"False",
")",
":",
"test_case",
".",
"run_forward",
"(",
"num_runs",
"=",
"1",
",",
"print_per_iter",
"=",
"False",
",",
"cuda_sync",
"=",
"False",
")",
"if",
"test_case",
".",
"framework",
"==",
"\"PyTorch\"",
":",
"test_case",
".",
"_output_mean",
"(",
")",
"backward_time",
"=",
"timeit",
".",
"timeit",
"(",
"functools",
".",
"partial",
"(",
"test_case",
".",
"run_backward",
",",
"iters",
",",
"print_per_iter",
")",
",",
"number",
"=",
"1",
")",
"return",
"backward_time"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/operator_benchmark/benchmark_core.py#L261-L271 | |
WeitaoVan/L-GM-loss | 598582f0631bac876b3eeb8d6c4cd1d780269e03 | python/caffe/coord_map.py | python | coord_map_from_to | (top_from, top_to) | Determine the coordinate mapping betweeen a top (from) and a top (to).
Walk the graph to find a common ancestor while composing the coord maps for
from and to until they meet. As a last step the from map is inverted. | Determine the coordinate mapping betweeen a top (from) and a top (to).
Walk the graph to find a common ancestor while composing the coord maps for
from and to until they meet. As a last step the from map is inverted. | [
"Determine",
"the",
"coordinate",
"mapping",
"betweeen",
"a",
"top",
"(",
"from",
")",
"and",
"a",
"top",
"(",
"to",
")",
".",
"Walk",
"the",
"graph",
"to",
"find",
"a",
"common",
"ancestor",
"while",
"composing",
"the",
"coord",
"maps",
"for",
"from",
"and",
"to",
"until",
"they",
"meet",
".",
"As",
"a",
"last",
"step",
"the",
"from",
"map",
"is",
"inverted",
"."
] | def coord_map_from_to(top_from, top_to):
"""
Determine the coordinate mapping betweeen a top (from) and a top (to).
Walk the graph to find a common ancestor while composing the coord maps for
from and to until they meet. As a last step the from map is inverted.
"""
# We need to find a common ancestor of top_from and top_to.
# We'll assume that all ancestors are equivalent here (otherwise the graph
# is an inconsistent state (which we could improve this to check for)).
# For now use a brute-force algorithm.
def collect_bottoms(top):
"""
Collect the bottoms to walk for the coordinate mapping.
The general rule is that all the bottoms of a layer can be mapped, as
most layers have the same coordinate mapping for each bottom.
Crop layer is a notable exception. Only the first/cropped bottom is
mappable; the second/dimensions bottom is excluded from the walk.
"""
bottoms = top.fn.inputs
if top.fn.type_name == 'Crop':
bottoms = bottoms[:1]
return bottoms
# walk back from top_from, keeping the coord map as we go
from_maps = {top_from: (None, 1, 0)}
frontier = {top_from}
while frontier:
top = frontier.pop()
try:
bottoms = collect_bottoms(top)
for bottom in bottoms:
from_maps[bottom] = compose(from_maps[top], coord_map(top.fn))
frontier.add(bottom)
except UndefinedMapException:
pass
# now walk back from top_to until we hit a common blob
to_maps = {top_to: (None, 1, 0)}
frontier = {top_to}
while frontier:
top = frontier.pop()
if top in from_maps:
return compose(to_maps[top], inverse(from_maps[top]))
try:
bottoms = collect_bottoms(top)
for bottom in bottoms:
to_maps[bottom] = compose(to_maps[top], coord_map(top.fn))
frontier.add(bottom)
except UndefinedMapException:
continue
# if we got here, we did not find a blob in common
raise RuntimeError('Could not compute map between tops; are they '
'connected by spatial layers?') | [
"def",
"coord_map_from_to",
"(",
"top_from",
",",
"top_to",
")",
":",
"# We need to find a common ancestor of top_from and top_to.",
"# We'll assume that all ancestors are equivalent here (otherwise the graph",
"# is an inconsistent state (which we could improve this to check for)).",
"# For now use a brute-force algorithm.",
"def",
"collect_bottoms",
"(",
"top",
")",
":",
"\"\"\"\n Collect the bottoms to walk for the coordinate mapping.\n The general rule is that all the bottoms of a layer can be mapped, as\n most layers have the same coordinate mapping for each bottom.\n Crop layer is a notable exception. Only the first/cropped bottom is\n mappable; the second/dimensions bottom is excluded from the walk.\n \"\"\"",
"bottoms",
"=",
"top",
".",
"fn",
".",
"inputs",
"if",
"top",
".",
"fn",
".",
"type_name",
"==",
"'Crop'",
":",
"bottoms",
"=",
"bottoms",
"[",
":",
"1",
"]",
"return",
"bottoms",
"# walk back from top_from, keeping the coord map as we go",
"from_maps",
"=",
"{",
"top_from",
":",
"(",
"None",
",",
"1",
",",
"0",
")",
"}",
"frontier",
"=",
"{",
"top_from",
"}",
"while",
"frontier",
":",
"top",
"=",
"frontier",
".",
"pop",
"(",
")",
"try",
":",
"bottoms",
"=",
"collect_bottoms",
"(",
"top",
")",
"for",
"bottom",
"in",
"bottoms",
":",
"from_maps",
"[",
"bottom",
"]",
"=",
"compose",
"(",
"from_maps",
"[",
"top",
"]",
",",
"coord_map",
"(",
"top",
".",
"fn",
")",
")",
"frontier",
".",
"add",
"(",
"bottom",
")",
"except",
"UndefinedMapException",
":",
"pass",
"# now walk back from top_to until we hit a common blob",
"to_maps",
"=",
"{",
"top_to",
":",
"(",
"None",
",",
"1",
",",
"0",
")",
"}",
"frontier",
"=",
"{",
"top_to",
"}",
"while",
"frontier",
":",
"top",
"=",
"frontier",
".",
"pop",
"(",
")",
"if",
"top",
"in",
"from_maps",
":",
"return",
"compose",
"(",
"to_maps",
"[",
"top",
"]",
",",
"inverse",
"(",
"from_maps",
"[",
"top",
"]",
")",
")",
"try",
":",
"bottoms",
"=",
"collect_bottoms",
"(",
"top",
")",
"for",
"bottom",
"in",
"bottoms",
":",
"to_maps",
"[",
"bottom",
"]",
"=",
"compose",
"(",
"to_maps",
"[",
"top",
"]",
",",
"coord_map",
"(",
"top",
".",
"fn",
")",
")",
"frontier",
".",
"add",
"(",
"bottom",
")",
"except",
"UndefinedMapException",
":",
"continue",
"# if we got here, we did not find a blob in common",
"raise",
"RuntimeError",
"(",
"'Could not compute map between tops; are they '",
"'connected by spatial layers?'",
")"
] | https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/python/caffe/coord_map.py#L115-L169 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | EnumProperty.GetIndexForValue | (*args, **kwargs) | return _propgrid.EnumProperty_GetIndexForValue(*args, **kwargs) | GetIndexForValue(self, int value) -> int | GetIndexForValue(self, int value) -> int | [
"GetIndexForValue",
"(",
"self",
"int",
"value",
")",
"-",
">",
"int"
] | def GetIndexForValue(*args, **kwargs):
"""GetIndexForValue(self, int value) -> int"""
return _propgrid.EnumProperty_GetIndexForValue(*args, **kwargs) | [
"def",
"GetIndexForValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"EnumProperty_GetIndexForValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L3005-L3007 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/filters.py | python | do_float | (value: t.Any, default: float = 0.0) | Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter. | Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter. | [
"Convert",
"the",
"value",
"into",
"a",
"floating",
"point",
"number",
".",
"If",
"the",
"conversion",
"doesn",
"t",
"work",
"it",
"will",
"return",
"0",
".",
"0",
".",
"You",
"can",
"override",
"this",
"default",
"using",
"the",
"first",
"parameter",
"."
] | def do_float(value: t.Any, default: float = 0.0) -> float:
"""Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
"""
try:
return float(value)
except (TypeError, ValueError):
return default | [
"def",
"do_float",
"(",
"value",
":",
"t",
".",
"Any",
",",
"default",
":",
"float",
"=",
"0.0",
")",
"->",
"float",
":",
"try",
":",
"return",
"float",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L989-L997 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/Cookie.py | python | BaseCookie.__set | (self, key, real_value, coded_value) | Private method for setting a cookie's value | Private method for setting a cookie's value | [
"Private",
"method",
"for",
"setting",
"a",
"cookie",
"s",
"value"
] | def __set(self, key, real_value, coded_value):
"""Private method for setting a cookie's value"""
M = self.get(key, Morsel())
M.set(key, real_value, coded_value)
dict.__setitem__(self, key, M) | [
"def",
"__set",
"(",
"self",
",",
"key",
",",
"real_value",
",",
"coded_value",
")",
":",
"M",
"=",
"self",
".",
"get",
"(",
"key",
",",
"Morsel",
"(",
")",
")",
"M",
".",
"set",
"(",
"key",
",",
"real_value",
",",
"coded_value",
")",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"M",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/Cookie.py#L582-L586 | ||
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/__init__.py | python | Rule.__lshift__ | (self, nodes) | Add a node to build when the rule is built.
>>> rule = Rule('name')
>>> created = drake.touch('/tmp/.drake.rule.add')
>>> created.path().remove()
>>> rule << created
>>> rule.build()
Touch /tmp/.drake.rule.add | Add a node to build when the rule is built. | [
"Add",
"a",
"node",
"to",
"build",
"when",
"the",
"rule",
"is",
"built",
"."
] | def __lshift__(self, nodes):
'''Add a node to build when the rule is built.
>>> rule = Rule('name')
>>> created = drake.touch('/tmp/.drake.rule.add')
>>> created.path().remove()
>>> rule << created
>>> rule.build()
Touch /tmp/.drake.rule.add
'''
if isinstance(nodes, (list, types.GeneratorType)):
for node in nodes:
self << node
else:
self.dependency_add(nodes) | [
"def",
"__lshift__",
"(",
"self",
",",
"nodes",
")",
":",
"if",
"isinstance",
"(",
"nodes",
",",
"(",
"list",
",",
"types",
".",
"GeneratorType",
")",
")",
":",
"for",
"node",
"in",
"nodes",
":",
"self",
"<<",
"node",
"else",
":",
"self",
".",
"dependency_add",
"(",
"nodes",
")"
] | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L3453-L3467 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/profiler/profiler.py | python | _KinetoProfile.key_averages | (self, group_by_input_shape: bool = False, group_by_stack_n: int = 0) | return self.profiler.key_averages(group_by_input_shape, group_by_stack_n) | Averages events, grouping them by operator name and (optionally) input shapes and
stack.
.. note::
To use shape/stack functionality make sure to set record_shapes/with_stack
when creating profiler context manager. | Averages events, grouping them by operator name and (optionally) input shapes and
stack. | [
"Averages",
"events",
"grouping",
"them",
"by",
"operator",
"name",
"and",
"(",
"optionally",
")",
"input",
"shapes",
"and",
"stack",
"."
] | def key_averages(self, group_by_input_shape: bool = False, group_by_stack_n: int = 0):
"""Averages events, grouping them by operator name and (optionally) input shapes and
stack.
.. note::
To use shape/stack functionality make sure to set record_shapes/with_stack
when creating profiler context manager.
"""
assert self.profiler
return self.profiler.key_averages(group_by_input_shape, group_by_stack_n) | [
"def",
"key_averages",
"(",
"self",
",",
"group_by_input_shape",
":",
"bool",
"=",
"False",
",",
"group_by_stack_n",
":",
"int",
"=",
"0",
")",
":",
"assert",
"self",
".",
"profiler",
"return",
"self",
".",
"profiler",
".",
"key_averages",
"(",
"group_by_input_shape",
",",
"group_by_stack_n",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/profiler/profiler.py#L140-L149 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py | python | dot | (a, b, strict=False, out=None) | Return the dot product of two arrays.
This function is the equivalent of `numpy.dot` that takes masked values
into account. Note that `strict` and `out` are in different position
than in the method version. In order to maintain compatibility with the
corresponding method, it is recommended that the optional arguments be
treated as keyword only. At some point that may be mandatory.
.. note::
Works only with 2-D arrays at the moment.
Parameters
----------
a, b : masked_array_like
Inputs arrays.
strict : bool, optional
Whether masked data are propagated (True) or set to 0 (False) for
the computation. Default is False. Propagating the mask means that
if a masked value appears in a row or column, the whole row or
column is considered masked.
out : masked_array, optional
Output argument. This must have the exact kind that would be returned
if it was not used. In particular, it must have the right type, must be
C-contiguous, and its dtype must be the dtype that would be returned
for `dot(a,b)`. This is a performance feature. Therefore, if these
conditions are not met, an exception is raised, instead of attempting
to be flexible.
.. versionadded:: 1.10.2
See Also
--------
numpy.dot : Equivalent function for ndarrays.
Examples
--------
>>> a = np.ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
>>> b = np.ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]])
>>> np.ma.dot(a, b)
masked_array(
data=[[21, 26],
[45, 64]],
mask=[[False, False],
[False, False]],
fill_value=999999)
>>> np.ma.dot(a, b, strict=True)
masked_array(
data=[[--, --],
[--, 64]],
mask=[[ True, True],
[ True, False]],
fill_value=999999) | Return the dot product of two arrays. | [
"Return",
"the",
"dot",
"product",
"of",
"two",
"arrays",
"."
] | def dot(a, b, strict=False, out=None):
"""
Return the dot product of two arrays.
This function is the equivalent of `numpy.dot` that takes masked values
into account. Note that `strict` and `out` are in different position
than in the method version. In order to maintain compatibility with the
corresponding method, it is recommended that the optional arguments be
treated as keyword only. At some point that may be mandatory.
.. note::
Works only with 2-D arrays at the moment.
Parameters
----------
a, b : masked_array_like
Inputs arrays.
strict : bool, optional
Whether masked data are propagated (True) or set to 0 (False) for
the computation. Default is False. Propagating the mask means that
if a masked value appears in a row or column, the whole row or
column is considered masked.
out : masked_array, optional
Output argument. This must have the exact kind that would be returned
if it was not used. In particular, it must have the right type, must be
C-contiguous, and its dtype must be the dtype that would be returned
for `dot(a,b)`. This is a performance feature. Therefore, if these
conditions are not met, an exception is raised, instead of attempting
to be flexible.
.. versionadded:: 1.10.2
See Also
--------
numpy.dot : Equivalent function for ndarrays.
Examples
--------
>>> a = np.ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
>>> b = np.ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]])
>>> np.ma.dot(a, b)
masked_array(
data=[[21, 26],
[45, 64]],
mask=[[False, False],
[False, False]],
fill_value=999999)
>>> np.ma.dot(a, b, strict=True)
masked_array(
data=[[--, --],
[--, 64]],
mask=[[ True, True],
[ True, False]],
fill_value=999999)
"""
# !!!: Works only with 2D arrays. There should be a way to get it to run
# with higher dimension
if strict and (a.ndim == 2) and (b.ndim == 2):
a = mask_rowcols(a, 0)
b = mask_rowcols(b, 1)
am = ~getmaskarray(a)
bm = ~getmaskarray(b)
if out is None:
d = np.dot(filled(a, 0), filled(b, 0))
m = ~np.dot(am, bm)
if d.ndim == 0:
d = np.asarray(d)
r = d.view(get_masked_subclass(a, b))
r.__setmask__(m)
return r
else:
d = np.dot(filled(a, 0), filled(b, 0), out._data)
if out.mask.shape != d.shape:
out._mask = np.empty(d.shape, MaskType)
np.dot(am, bm, out._mask)
np.logical_not(out._mask, out._mask)
return out | [
"def",
"dot",
"(",
"a",
",",
"b",
",",
"strict",
"=",
"False",
",",
"out",
"=",
"None",
")",
":",
"# !!!: Works only with 2D arrays. There should be a way to get it to run",
"# with higher dimension",
"if",
"strict",
"and",
"(",
"a",
".",
"ndim",
"==",
"2",
")",
"and",
"(",
"b",
".",
"ndim",
"==",
"2",
")",
":",
"a",
"=",
"mask_rowcols",
"(",
"a",
",",
"0",
")",
"b",
"=",
"mask_rowcols",
"(",
"b",
",",
"1",
")",
"am",
"=",
"~",
"getmaskarray",
"(",
"a",
")",
"bm",
"=",
"~",
"getmaskarray",
"(",
"b",
")",
"if",
"out",
"is",
"None",
":",
"d",
"=",
"np",
".",
"dot",
"(",
"filled",
"(",
"a",
",",
"0",
")",
",",
"filled",
"(",
"b",
",",
"0",
")",
")",
"m",
"=",
"~",
"np",
".",
"dot",
"(",
"am",
",",
"bm",
")",
"if",
"d",
".",
"ndim",
"==",
"0",
":",
"d",
"=",
"np",
".",
"asarray",
"(",
"d",
")",
"r",
"=",
"d",
".",
"view",
"(",
"get_masked_subclass",
"(",
"a",
",",
"b",
")",
")",
"r",
".",
"__setmask__",
"(",
"m",
")",
"return",
"r",
"else",
":",
"d",
"=",
"np",
".",
"dot",
"(",
"filled",
"(",
"a",
",",
"0",
")",
",",
"filled",
"(",
"b",
",",
"0",
")",
",",
"out",
".",
"_data",
")",
"if",
"out",
".",
"mask",
".",
"shape",
"!=",
"d",
".",
"shape",
":",
"out",
".",
"_mask",
"=",
"np",
".",
"empty",
"(",
"d",
".",
"shape",
",",
"MaskType",
")",
"np",
".",
"dot",
"(",
"am",
",",
"bm",
",",
"out",
".",
"_mask",
")",
"np",
".",
"logical_not",
"(",
"out",
".",
"_mask",
",",
"out",
".",
"_mask",
")",
"return",
"out"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L7447-L7526 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/math_utils.py | python | Mean | (values) | return sum(values) / float(len(values)) | Returns the arithmetic mean, or NaN if the input is empty. | Returns the arithmetic mean, or NaN if the input is empty. | [
"Returns",
"the",
"arithmetic",
"mean",
"or",
"NaN",
"if",
"the",
"input",
"is",
"empty",
"."
] | def Mean(values):
"""Returns the arithmetic mean, or NaN if the input is empty."""
if not values:
return float('nan')
return sum(values) / float(len(values)) | [
"def",
"Mean",
"(",
"values",
")",
":",
"if",
"not",
"values",
":",
"return",
"float",
"(",
"'nan'",
")",
"return",
"sum",
"(",
"values",
")",
"/",
"float",
"(",
"len",
"(",
"values",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/math_utils.py#L10-L14 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/server/factory.py | python | RegisterClassFactories | (clsids, flags = None, clsctx = None) | return ret | Given a list of CLSID, create and register class factories.
Returns a list, which should be passed to RevokeClassFactories | Given a list of CLSID, create and register class factories.
Returns a list, which should be passed to RevokeClassFactories | [
"Given",
"a",
"list",
"of",
"CLSID",
"create",
"and",
"register",
"class",
"factories",
".",
"Returns",
"a",
"list",
"which",
"should",
"be",
"passed",
"to",
"RevokeClassFactories"
] | def RegisterClassFactories(clsids, flags = None, clsctx = None):
"""Given a list of CLSID, create and register class factories.
Returns a list, which should be passed to RevokeClassFactories
"""
if flags is None: flags = pythoncom.REGCLS_MULTIPLEUSE|pythoncom.REGCLS_SUSPENDED
if clsctx is None: clsctx = pythoncom.CLSCTX_LOCAL_SERVER
ret = []
for clsid in clsids:
# Some server append '-Embedding' etc
if clsid[0] not in ['-', '/']:
factory = pythoncom.MakePyFactory(clsid)
regId = pythoncom.CoRegisterClassObject(clsid, factory, clsctx, flags)
ret.append((factory, regId))
return ret | [
"def",
"RegisterClassFactories",
"(",
"clsids",
",",
"flags",
"=",
"None",
",",
"clsctx",
"=",
"None",
")",
":",
"if",
"flags",
"is",
"None",
":",
"flags",
"=",
"pythoncom",
".",
"REGCLS_MULTIPLEUSE",
"|",
"pythoncom",
".",
"REGCLS_SUSPENDED",
"if",
"clsctx",
"is",
"None",
":",
"clsctx",
"=",
"pythoncom",
".",
"CLSCTX_LOCAL_SERVER",
"ret",
"=",
"[",
"]",
"for",
"clsid",
"in",
"clsids",
":",
"# Some server append '-Embedding' etc",
"if",
"clsid",
"[",
"0",
"]",
"not",
"in",
"[",
"'-'",
",",
"'/'",
"]",
":",
"factory",
"=",
"pythoncom",
".",
"MakePyFactory",
"(",
"clsid",
")",
"regId",
"=",
"pythoncom",
".",
"CoRegisterClassObject",
"(",
"clsid",
",",
"factory",
",",
"clsctx",
",",
"flags",
")",
"ret",
".",
"append",
"(",
"(",
"factory",
",",
"regId",
")",
")",
"return",
"ret"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/server/factory.py#L4-L18 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py | python | TixWidget.subwidgets_all | (self) | return retlist | Return all subwidgets. | Return all subwidgets. | [
"Return",
"all",
"subwidgets",
"."
] | def subwidgets_all(self):
"""Return all subwidgets."""
names = self._subwidget_names()
if not names:
return []
retlist = []
for name in names:
name = name[len(self._w)+1:]
try:
retlist.append(self._nametowidget(name))
except:
# some of the widgets are unknown e.g. border in LabelFrame
pass
return retlist | [
"def",
"subwidgets_all",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"_subwidget_names",
"(",
")",
"if",
"not",
"names",
":",
"return",
"[",
"]",
"retlist",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"name",
"=",
"name",
"[",
"len",
"(",
"self",
".",
"_w",
")",
"+",
"1",
":",
"]",
"try",
":",
"retlist",
".",
"append",
"(",
"self",
".",
"_nametowidget",
"(",
"name",
")",
")",
"except",
":",
"# some of the widgets are unknown e.g. border in LabelFrame",
"pass",
"return",
"retlist"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py#L357-L370 | |
yuxng/DA-RNN | 77fbb50b4272514588a10a9f90b7d5f8d46974fb | lib/datasets/gmu_scene.py | python | gmu_scene._process_label_image | (self, label_image) | return label_index | change label image to label index | change label image to label index | [
"change",
"label",
"image",
"to",
"label",
"index"
] | def _process_label_image(self, label_image):
"""
change label image to label index
"""
class_colors = self._class_colors
width = label_image.shape[1]
height = label_image.shape[0]
label_index = np.zeros((height, width), dtype=np.float32)
# label image is in BRG order
index = label_image[:,:,2] + 256*label_image[:,:,1] + 256*256*label_image[:,:,0]
for i in xrange(len(class_colors)):
color = class_colors[i]
ind = 255 * (color[0] + 256*color[1] + 256*256*color[2])
I = np.where(index == ind)
label_index[I] = i
return label_index | [
"def",
"_process_label_image",
"(",
"self",
",",
"label_image",
")",
":",
"class_colors",
"=",
"self",
".",
"_class_colors",
"width",
"=",
"label_image",
".",
"shape",
"[",
"1",
"]",
"height",
"=",
"label_image",
".",
"shape",
"[",
"0",
"]",
"label_index",
"=",
"np",
".",
"zeros",
"(",
"(",
"height",
",",
"width",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# label image is in BRG order",
"index",
"=",
"label_image",
"[",
":",
",",
":",
",",
"2",
"]",
"+",
"256",
"*",
"label_image",
"[",
":",
",",
":",
",",
"1",
"]",
"+",
"256",
"*",
"256",
"*",
"label_image",
"[",
":",
",",
":",
",",
"0",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"class_colors",
")",
")",
":",
"color",
"=",
"class_colors",
"[",
"i",
"]",
"ind",
"=",
"255",
"*",
"(",
"color",
"[",
"0",
"]",
"+",
"256",
"*",
"color",
"[",
"1",
"]",
"+",
"256",
"*",
"256",
"*",
"color",
"[",
"2",
"]",
")",
"I",
"=",
"np",
".",
"where",
"(",
"index",
"==",
"ind",
")",
"label_index",
"[",
"I",
"]",
"=",
"i",
"return",
"label_index"
] | https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/gmu_scene.py#L178-L195 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiDockingHintWindow.MakeVenetianBlinds | (self) | Creates the "venetian blind" effect if :class:`AuiManager` has the ``AUI_MGR_VENETIAN_BLINDS_HINT``
flag set. | Creates the "venetian blind" effect if :class:`AuiManager` has the ``AUI_MGR_VENETIAN_BLINDS_HINT``
flag set. | [
"Creates",
"the",
"venetian",
"blind",
"effect",
"if",
":",
"class",
":",
"AuiManager",
"has",
"the",
"AUI_MGR_VENETIAN_BLINDS_HINT",
"flag",
"set",
"."
] | def MakeVenetianBlinds(self):
"""
Creates the "venetian blind" effect if :class:`AuiManager` has the ``AUI_MGR_VENETIAN_BLINDS_HINT``
flag set.
"""
amount = 128
size = self.GetClientSize()
region = wx.Region(0, 0, size.x, 1)
for y in xrange(size.y):
# Reverse the order of the bottom 4 bits
j = (y & 8 and [1] or [0])[0] | (y & 4 and [2] or [0])[0] | \
(y & 2 and [4] or [0])[0] | (y & 1 and [8] or [0])[0]
if 16*j+8 < amount:
region.Union(0, y, size.x, 1)
self.SetShape(region) | [
"def",
"MakeVenetianBlinds",
"(",
"self",
")",
":",
"amount",
"=",
"128",
"size",
"=",
"self",
".",
"GetClientSize",
"(",
")",
"region",
"=",
"wx",
".",
"Region",
"(",
"0",
",",
"0",
",",
"size",
".",
"x",
",",
"1",
")",
"for",
"y",
"in",
"xrange",
"(",
"size",
".",
"y",
")",
":",
"# Reverse the order of the bottom 4 bits",
"j",
"=",
"(",
"y",
"&",
"8",
"and",
"[",
"1",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"|",
"(",
"y",
"&",
"4",
"and",
"[",
"2",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"|",
"(",
"y",
"&",
"2",
"and",
"[",
"4",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"|",
"(",
"y",
"&",
"1",
"and",
"[",
"8",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"if",
"16",
"*",
"j",
"+",
"8",
"<",
"amount",
":",
"region",
".",
"Union",
"(",
"0",
",",
"y",
",",
"size",
".",
"x",
",",
"1",
")",
"self",
".",
"SetShape",
"(",
"region",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L2734-L2753 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py | python | prod | (x, axis=None, keepdims=False) | return math_ops.reduce_prod(x, axis, keepdims) | Multiplies the values in a tensor, alongside the specified axis.
Arguments:
x: A tensor or variable.
axis: An integer, the axis to compute the product.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
Returns:
A tensor with the product of elements of `x`. | Multiplies the values in a tensor, alongside the specified axis. | [
"Multiplies",
"the",
"values",
"in",
"a",
"tensor",
"alongside",
"the",
"specified",
"axis",
"."
] | def prod(x, axis=None, keepdims=False):
"""Multiplies the values in a tensor, alongside the specified axis.
Arguments:
x: A tensor or variable.
axis: An integer, the axis to compute the product.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1. If `keepdims` is `True`,
the reduced dimension is retained with length 1.
Returns:
A tensor with the product of elements of `x`.
"""
return math_ops.reduce_prod(x, axis, keepdims) | [
"def",
"prod",
"(",
"x",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"return",
"math_ops",
".",
"reduce_prod",
"(",
"x",
",",
"axis",
",",
"keepdims",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L1901-L1915 | |
Smorodov/Multitarget-tracker | bee300e8bfd660c86cbeb6892c65a5b7195c9381 | thirdparty/pybind11/tools/clang/cindex.py | python | CursorKind.get_all_kinds | () | return [_f for _f in CursorKind._kinds if _f] | Return all CursorKind enumeration instances. | Return all CursorKind enumeration instances. | [
"Return",
"all",
"CursorKind",
"enumeration",
"instances",
"."
] | def get_all_kinds():
"""Return all CursorKind enumeration instances."""
return [_f for _f in CursorKind._kinds if _f] | [
"def",
"get_all_kinds",
"(",
")",
":",
"return",
"[",
"_f",
"for",
"_f",
"in",
"CursorKind",
".",
"_kinds",
"if",
"_f",
"]"
] | https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L572-L574 | |
POV-Ray/povray | 76a804d18a30a1dbb0afbc0070b62526715571eb | tools/meta-make/bluenoise/BlueNoise.py | python | FindTightestCluster | (BinaryPattern,StandardDeviation) | return np.argmax(np.where(BinaryPattern,FilteredArray,-1.0)) | Like FindLargestVoid() but finds the tightest cluster which is a minority
pixel by definition.
\sa GetVoidAndClusterBlueNoise | Like FindLargestVoid() but finds the tightest cluster which is a minority
pixel by definition.
\sa GetVoidAndClusterBlueNoise | [
"Like",
"FindLargestVoid",
"()",
"but",
"finds",
"the",
"tightest",
"cluster",
"which",
"is",
"a",
"minority",
"pixel",
"by",
"definition",
".",
"\\",
"sa",
"GetVoidAndClusterBlueNoise"
] | def FindTightestCluster(BinaryPattern,StandardDeviation):
"""Like FindLargestVoid() but finds the tightest cluster which is a minority
pixel by definition.
\sa GetVoidAndClusterBlueNoise"""
if(np.count_nonzero(BinaryPattern)*2>=np.size(BinaryPattern)):
BinaryPattern=np.logical_not(BinaryPattern);
FilteredArray=np.fft.ifftn(ndimage.fourier.fourier_gaussian(np.fft.fftn(np.where(BinaryPattern,1.0,0.0)),StandardDeviation)).real;
return np.argmax(np.where(BinaryPattern,FilteredArray,-1.0)); | [
"def",
"FindTightestCluster",
"(",
"BinaryPattern",
",",
"StandardDeviation",
")",
":",
"if",
"(",
"np",
".",
"count_nonzero",
"(",
"BinaryPattern",
")",
"*",
"2",
">=",
"np",
".",
"size",
"(",
"BinaryPattern",
")",
")",
":",
"BinaryPattern",
"=",
"np",
".",
"logical_not",
"(",
"BinaryPattern",
")",
"FilteredArray",
"=",
"np",
".",
"fft",
".",
"ifftn",
"(",
"ndimage",
".",
"fourier",
".",
"fourier_gaussian",
"(",
"np",
".",
"fft",
".",
"fftn",
"(",
"np",
".",
"where",
"(",
"BinaryPattern",
",",
"1.0",
",",
"0.0",
")",
")",
",",
"StandardDeviation",
")",
")",
".",
"real",
"return",
"np",
".",
"argmax",
"(",
"np",
".",
"where",
"(",
"BinaryPattern",
",",
"FilteredArray",
",",
"-",
"1.0",
")",
")"
] | https://github.com/POV-Ray/povray/blob/76a804d18a30a1dbb0afbc0070b62526715571eb/tools/meta-make/bluenoise/BlueNoise.py#L56-L63 | |
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/tools/scan-build-py/libscanbuild/analyze.py | python | analyze_build_wrapper | (cplusplus) | return result | Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. | Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. | [
"Entry",
"point",
"for",
"analyze",
"-",
"cc",
"and",
"analyze",
"-",
"c",
"++",
"compiler",
"wrappers",
"."
] | def analyze_build_wrapper(cplusplus):
""" Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. """
# initialize wrapper logging
logging.basicConfig(format='analyze: %(levelname)s: %(message)s',
level=os.getenv('ANALYZE_BUILD_VERBOSE', 'INFO'))
# execute with real compiler
compiler = os.getenv('ANALYZE_BUILD_CXX', 'c++') if cplusplus \
else os.getenv('ANALYZE_BUILD_CC', 'cc')
compilation = [compiler] + sys.argv[1:]
logging.info('execute compiler: %s', compilation)
result = subprocess.call(compilation)
# exit when it fails, ...
if result or not os.getenv('ANALYZE_BUILD_CLANG'):
return result
# ... and run the analyzer if all went well.
try:
# check is it a compilation
compilation = split_command(sys.argv)
if compilation is None:
return result
# collect the needed parameters from environment, crash when missing
parameters = {
'clang': os.getenv('ANALYZE_BUILD_CLANG'),
'output_dir': os.getenv('ANALYZE_BUILD_REPORT_DIR'),
'output_format': os.getenv('ANALYZE_BUILD_REPORT_FORMAT'),
'output_failures': os.getenv('ANALYZE_BUILD_REPORT_FAILURES'),
'direct_args': os.getenv('ANALYZE_BUILD_PARAMETERS',
'').split(' '),
'force_debug': os.getenv('ANALYZE_BUILD_FORCE_DEBUG'),
'directory': os.getcwd(),
'command': [sys.argv[0], '-c'] + compilation.flags
}
# call static analyzer against the compilation
for source in compilation.files:
parameters.update({'file': source})
logging.debug('analyzer parameters %s', parameters)
current = run(parameters)
# display error message from the static analyzer
if current is not None:
for line in current['error_output']:
logging.info(line.rstrip())
except Exception:
logging.exception("run analyzer inside compiler wrapper failed.")
return result | [
"def",
"analyze_build_wrapper",
"(",
"cplusplus",
")",
":",
"# initialize wrapper logging",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'analyze: %(levelname)s: %(message)s'",
",",
"level",
"=",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_VERBOSE'",
",",
"'INFO'",
")",
")",
"# execute with real compiler",
"compiler",
"=",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_CXX'",
",",
"'c++'",
")",
"if",
"cplusplus",
"else",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_CC'",
",",
"'cc'",
")",
"compilation",
"=",
"[",
"compiler",
"]",
"+",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"logging",
".",
"info",
"(",
"'execute compiler: %s'",
",",
"compilation",
")",
"result",
"=",
"subprocess",
".",
"call",
"(",
"compilation",
")",
"# exit when it fails, ...",
"if",
"result",
"or",
"not",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_CLANG'",
")",
":",
"return",
"result",
"# ... and run the analyzer if all went well.",
"try",
":",
"# check is it a compilation",
"compilation",
"=",
"split_command",
"(",
"sys",
".",
"argv",
")",
"if",
"compilation",
"is",
"None",
":",
"return",
"result",
"# collect the needed parameters from environment, crash when missing",
"parameters",
"=",
"{",
"'clang'",
":",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_CLANG'",
")",
",",
"'output_dir'",
":",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_REPORT_DIR'",
")",
",",
"'output_format'",
":",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_REPORT_FORMAT'",
")",
",",
"'output_failures'",
":",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_REPORT_FAILURES'",
")",
",",
"'direct_args'",
":",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_PARAMETERS'",
",",
"''",
")",
".",
"split",
"(",
"' '",
")",
",",
"'force_debug'",
":",
"os",
".",
"getenv",
"(",
"'ANALYZE_BUILD_FORCE_DEBUG'",
")",
",",
"'directory'",
":",
"os",
".",
"getcwd",
"(",
")",
",",
"'command'",
":",
"[",
"sys",
".",
"argv",
"[",
"0",
"]",
",",
"'-c'",
"]",
"+",
"compilation",
".",
"flags",
"}",
"# call static analyzer against the compilation",
"for",
"source",
"in",
"compilation",
".",
"files",
":",
"parameters",
".",
"update",
"(",
"{",
"'file'",
":",
"source",
"}",
")",
"logging",
".",
"debug",
"(",
"'analyzer parameters %s'",
",",
"parameters",
")",
"current",
"=",
"run",
"(",
"parameters",
")",
"# display error message from the static analyzer",
"if",
"current",
"is",
"not",
"None",
":",
"for",
"line",
"in",
"current",
"[",
"'error_output'",
"]",
":",
"logging",
".",
"info",
"(",
"line",
".",
"rstrip",
"(",
")",
")",
"except",
"Exception",
":",
"logging",
".",
"exception",
"(",
"\"run analyzer inside compiler wrapper failed.\"",
")",
"return",
"result"
] | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/tools/scan-build-py/libscanbuild/analyze.py#L147-L191 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py | python | Keyword.setDefaultKeywordChars | ( chars ) | Overrides the default Keyword chars | Overrides the default Keyword chars | [
"Overrides",
"the",
"default",
"Keyword",
"chars"
] | def setDefaultKeywordChars( chars ):
"""Overrides the default Keyword chars
"""
Keyword.DEFAULT_KEYWORD_CHARS = chars | [
"def",
"setDefaultKeywordChars",
"(",
"chars",
")",
":",
"Keyword",
".",
"DEFAULT_KEYWORD_CHARS",
"=",
"chars"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py#L2697-L2700 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py | python | calc_chksums | (buf) | return unsigned_chksum, signed_chksum | Calculate the checksum for a member's header by summing up all
characters except for the chksum field which is treated as if
it was filled with spaces. According to the GNU tar sources,
some tars (Sun and NeXT) calculate chksum with signed char,
which will be different if there are chars in the buffer with
the high bit set. So we calculate two checksums, unsigned and
signed. | Calculate the checksum for a member's header by summing up all
characters except for the chksum field which is treated as if
it was filled with spaces. According to the GNU tar sources,
some tars (Sun and NeXT) calculate chksum with signed char,
which will be different if there are chars in the buffer with
the high bit set. So we calculate two checksums, unsigned and
signed. | [
"Calculate",
"the",
"checksum",
"for",
"a",
"member",
"s",
"header",
"by",
"summing",
"up",
"all",
"characters",
"except",
"for",
"the",
"chksum",
"field",
"which",
"is",
"treated",
"as",
"if",
"it",
"was",
"filled",
"with",
"spaces",
".",
"According",
"to",
"the",
"GNU",
"tar",
"sources",
"some",
"tars",
"(",
"Sun",
"and",
"NeXT",
")",
"calculate",
"chksum",
"with",
"signed",
"char",
"which",
"will",
"be",
"different",
"if",
"there",
"are",
"chars",
"in",
"the",
"buffer",
"with",
"the",
"high",
"bit",
"set",
".",
"So",
"we",
"calculate",
"two",
"checksums",
"unsigned",
"and",
"signed",
"."
] | def calc_chksums(buf):
"""Calculate the checksum for a member's header by summing up all
characters except for the chksum field which is treated as if
it was filled with spaces. According to the GNU tar sources,
some tars (Sun and NeXT) calculate chksum with signed char,
which will be different if there are chars in the buffer with
the high bit set. So we calculate two checksums, unsigned and
signed.
"""
unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512]))
signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512]))
return unsigned_chksum, signed_chksum | [
"def",
"calc_chksums",
"(",
"buf",
")",
":",
"unsigned_chksum",
"=",
"256",
"+",
"sum",
"(",
"struct",
".",
"unpack",
"(",
"\"148B\"",
",",
"buf",
"[",
":",
"148",
"]",
")",
"+",
"struct",
".",
"unpack",
"(",
"\"356B\"",
",",
"buf",
"[",
"156",
":",
"512",
"]",
")",
")",
"signed_chksum",
"=",
"256",
"+",
"sum",
"(",
"struct",
".",
"unpack",
"(",
"\"148b\"",
",",
"buf",
"[",
":",
"148",
"]",
")",
"+",
"struct",
".",
"unpack",
"(",
"\"356b\"",
",",
"buf",
"[",
"156",
":",
"512",
"]",
")",
")",
"return",
"unsigned_chksum",
",",
"signed_chksum"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L243-L254 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/handler.py | python | ErrorHandler.warning | (self, exception) | Handle a warning. | Handle a warning. | [
"Handle",
"a",
"warning",
"."
] | def warning(self, exception):
"Handle a warning."
print(exception) | [
"def",
"warning",
"(",
"self",
",",
"exception",
")",
":",
"print",
"(",
"exception",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/handler.py#L40-L42 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | register_loader_type | (loader_type, provider_factory) | Register `provider_factory` to make providers for `loader_type`
`loader_type` is the type or class of a PEP 302 ``module.__loader__``,
and `provider_factory` is a function that, passed a *module* object,
returns an ``IResourceProvider`` for that module. | Register `provider_factory` to make providers for `loader_type` | [
"Register",
"provider_factory",
"to",
"make",
"providers",
"for",
"loader_type"
] | def register_loader_type(loader_type, provider_factory):
"""Register `provider_factory` to make providers for `loader_type`
`loader_type` is the type or class of a PEP 302 ``module.__loader__``,
and `provider_factory` is a function that, passed a *module* object,
returns an ``IResourceProvider`` for that module.
"""
_provider_factories[loader_type] = provider_factory | [
"def",
"register_loader_type",
"(",
"loader_type",
",",
"provider_factory",
")",
":",
"_provider_factories",
"[",
"loader_type",
"]",
"=",
"provider_factory"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L401-L408 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | VListBox.SetSelection | (*args, **kwargs) | return _windows_.VListBox_SetSelection(*args, **kwargs) | SetSelection(self, int selection) | SetSelection(self, int selection) | [
"SetSelection",
"(",
"self",
"int",
"selection",
")"
] | def SetSelection(*args, **kwargs):
"""SetSelection(self, int selection)"""
return _windows_.VListBox_SetSelection(*args, **kwargs) | [
"def",
"SetSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"VListBox_SetSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L2656-L2658 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/saver.py | python | Saver._MetaGraphFilename | (self, checkpoint_filename, meta_graph_suffix="meta") | return meta_graph_filename | Returns the meta graph filename.
Args:
checkpoint_filename: Name of the checkpoint file.
meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
Returns:
MetaGraph file name. | Returns the meta graph filename. | [
"Returns",
"the",
"meta",
"graph",
"filename",
"."
] | def _MetaGraphFilename(self, checkpoint_filename, meta_graph_suffix="meta"):
"""Returns the meta graph filename.
Args:
checkpoint_filename: Name of the checkpoint file.
meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
Returns:
MetaGraph file name.
"""
# If the checkpoint_filename is sharded, the checkpoint_filename could
# be of format model.ckpt-step#-?????-of-shard#. For example,
# model.ckpt-123456-?????-of-00005, or model.ckpt-123456-00001-of-00002.
basename = re.sub(r"-[\d\?]+-of-\d+$", "", checkpoint_filename)
meta_graph_filename = ".".join([basename, meta_graph_suffix])
return meta_graph_filename | [
"def",
"_MetaGraphFilename",
"(",
"self",
",",
"checkpoint_filename",
",",
"meta_graph_suffix",
"=",
"\"meta\"",
")",
":",
"# If the checkpoint_filename is sharded, the checkpoint_filename could",
"# be of format model.ckpt-step#-?????-of-shard#. For example,",
"# model.ckpt-123456-?????-of-00005, or model.ckpt-123456-00001-of-00002.",
"basename",
"=",
"re",
".",
"sub",
"(",
"r\"-[\\d\\?]+-of-\\d+$\"",
",",
"\"\"",
",",
"checkpoint_filename",
")",
"meta_graph_filename",
"=",
"\".\"",
".",
"join",
"(",
"[",
"basename",
",",
"meta_graph_suffix",
"]",
")",
"return",
"meta_graph_filename"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/saver.py#L1313-L1328 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.MoveCaretInsideView | (*args, **kwargs) | return _stc.StyledTextCtrl_MoveCaretInsideView(*args, **kwargs) | MoveCaretInsideView(self)
Move the caret inside current view if it's not there already. | MoveCaretInsideView(self) | [
"MoveCaretInsideView",
"(",
"self",
")"
] | def MoveCaretInsideView(*args, **kwargs):
"""
MoveCaretInsideView(self)
Move the caret inside current view if it's not there already.
"""
return _stc.StyledTextCtrl_MoveCaretInsideView(*args, **kwargs) | [
"def",
"MoveCaretInsideView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_MoveCaretInsideView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4783-L4789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.