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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/manifest.py | python | Manifest._glob_to_re | (self, pattern) | return pattern_re | Translate a shell-like glob pattern to a regular expression.
Return a string containing the regex. Differs from
'fnmatch.translate()' in that '*' does not match "special characters"
(which are platform-specific). | Translate a shell-like glob pattern to a regular expression. | [
"Translate",
"a",
"shell",
"-",
"like",
"glob",
"pattern",
"to",
"a",
"regular",
"expression",
"."
] | def _glob_to_re(self, pattern):
"""Translate a shell-like glob pattern to a regular expression.
Return a string containing the regex. Differs from
'fnmatch.translate()' in that '*' does not match "special characters"
(which are platform-specific).
"""
pattern_re = fnmatch.translate(pattern)
# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
# and by extension they shouldn't match such "special characters" under
# any OS. So change all non-escaped dots in the RE to match any
# character except the special characters (currently: just os.sep).
sep = os.sep
if os.sep == '\\':
# we're using a regex to manipulate a regex, so we need
# to escape the backslash twice
sep = r'\\\\'
escaped = r'\1[^%s]' % sep
pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
return pattern_re | [
"def",
"_glob_to_re",
"(",
"self",
",",
"pattern",
")",
":",
"pattern_re",
"=",
"fnmatch",
".",
"translate",
"(",
"pattern",
")",
"# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which",
"# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,",
"# and by extension they shouldn't match such \"special characters\" under",
"# any OS. So change all non-escaped dots in the RE to match any",
"# character except the special characters (currently: just os.sep).",
"sep",
"=",
"os",
".",
"sep",
"if",
"os",
".",
"sep",
"==",
"'\\\\'",
":",
"# we're using a regex to manipulate a regex, so we need",
"# to escape the backslash twice",
"sep",
"=",
"r'\\\\\\\\'",
"escaped",
"=",
"r'\\1[^%s]'",
"%",
"sep",
"pattern_re",
"=",
"re",
".",
"sub",
"(",
"r'((?<!\\\\)(\\\\\\\\)*)\\.'",
",",
"escaped",
",",
"pattern_re",
")",
"return",
"pattern_re"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/manifest.py#L372-L393 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py | python | Circles.pick_handle | (self, coord, detectwidth=0.1) | return np.concatenate((ids.reshape((len(ids), 1)), np.zeros((len(ids), 1), np.int)), 1) | Retuns list [ id, ind_vert] when handle is near coord,
otherwise [] | Retuns list [ id, ind_vert] when handle is near coord,
otherwise [] | [
"Retuns",
"list",
"[",
"id",
"ind_vert",
"]",
"when",
"handle",
"is",
"near",
"coord",
"otherwise",
"[]"
] | def pick_handle(self, coord, detectwidth=0.1):
"""
Retuns list [ id, ind_vert] when handle is near coord,
otherwise []
"""
if len(self) == 0:
return np.zeros((0, 2), np.int)
# print 'pick_handle',self.get_ident(),len(self)
dw = detectwidth**2
centers = self.get_centers_array()
radii = self.get_radii_array()
dx = centers[:, 0]-coord[0]
dy = centers[:, 1]-coord[1]
r = dx*dx+dy*dy
ids = self._ids[(r > radii*radii-dw) & (r < radii*radii+dw)]
#handles = np.concatenate(( ids.reshape((len(ids),1)), np.zeros((len(ids),1),np.int)),1)
# print ' ids',ids
# print ' handles',handles
return np.concatenate((ids.reshape((len(ids), 1)), np.zeros((len(ids), 1), np.int)), 1) | [
"def",
"pick_handle",
"(",
"self",
",",
"coord",
",",
"detectwidth",
"=",
"0.1",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"2",
")",
",",
"np",
".",
"int",
")",
"# print 'pick_handle',self.get_ident(),len(self)",
"dw",
"=",
"detectwidth",
"**",
"2",
"centers",
"=",
"self",
".",
"get_centers_array",
"(",
")",
"radii",
"=",
"self",
".",
"get_radii_array",
"(",
")",
"dx",
"=",
"centers",
"[",
":",
",",
"0",
"]",
"-",
"coord",
"[",
"0",
"]",
"dy",
"=",
"centers",
"[",
":",
",",
"1",
"]",
"-",
"coord",
"[",
"1",
"]",
"r",
"=",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
"ids",
"=",
"self",
".",
"_ids",
"[",
"(",
"r",
">",
"radii",
"*",
"radii",
"-",
"dw",
")",
"&",
"(",
"r",
"<",
"radii",
"*",
"radii",
"+",
"dw",
")",
"]",
"#handles = np.concatenate(( ids.reshape((len(ids),1)), np.zeros((len(ids),1),np.int)),1)",
"# print ' ids',ids",
"# print ' handles',handles",
"return",
"np",
".",
"concatenate",
"(",
"(",
"ids",
".",
"reshape",
"(",
"(",
"len",
"(",
"ids",
")",
",",
"1",
")",
")",
",",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"ids",
")",
",",
"1",
")",
",",
"np",
".",
"int",
")",
")",
",",
"1",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py#L3723-L3744 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | DirDialog.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, String message=DirSelectorPromptStr,
String defaultPath=EmptyString, long style=DD_DEFAULT_STYLE,
Point pos=DefaultPosition, Size size=DefaultSize,
String name=DirDialogNameStr) -> DirDialog
Constructor. Use ShowModal method to show the dialog. | __init__(self, Window parent, String message=DirSelectorPromptStr,
String defaultPath=EmptyString, long style=DD_DEFAULT_STYLE,
Point pos=DefaultPosition, Size size=DefaultSize,
String name=DirDialogNameStr) -> DirDialog | [
"__init__",
"(",
"self",
"Window",
"parent",
"String",
"message",
"=",
"DirSelectorPromptStr",
"String",
"defaultPath",
"=",
"EmptyString",
"long",
"style",
"=",
"DD_DEFAULT_STYLE",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"String",
"name",
"=",
"DirDialogNameStr",
")",
"-",
">",
"DirDialog"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, String message=DirSelectorPromptStr,
String defaultPath=EmptyString, long style=DD_DEFAULT_STYLE,
Point pos=DefaultPosition, Size size=DefaultSize,
String name=DirDialogNameStr) -> DirDialog
Constructor. Use ShowModal method to show the dialog.
"""
_windows_.DirDialog_swiginit(self,_windows_.new_DirDialog(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_windows_",
".",
"DirDialog_swiginit",
"(",
"self",
",",
"_windows_",
".",
"new_DirDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L3058-L3068 | ||
CaoWGG/TensorRT-YOLOv4 | 4d7c2edce99e8794a4cb4ea3540d51ce91158a36 | onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py | python | Cursor.mangled_name | (self) | return self._mangled_name | Return the mangled name for the entity referenced by this cursor. | Return the mangled name for the entity referenced by this cursor. | [
"Return",
"the",
"mangled",
"name",
"for",
"the",
"entity",
"referenced",
"by",
"this",
"cursor",
"."
] | def mangled_name(self):
"""Return the mangled name for the entity referenced by this cursor."""
if not hasattr(self, '_mangled_name'):
self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
return self._mangled_name | [
"def",
"mangled_name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_mangled_name'",
")",
":",
"self",
".",
"_mangled_name",
"=",
"conf",
".",
"lib",
".",
"clang_Cursor_getMangling",
"(",
"self",
")",
"return",
"self",
".",
"_mangled_name"
] | https://github.com/CaoWGG/TensorRT-YOLOv4/blob/4d7c2edce99e8794a4cb4ea3540d51ce91158a36/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L1420-L1425 | |
LLNL/lbann | 26083e6c86050302ce33148aea70f62e61cacb92 | python/lbann/contrib/olcf/systems.py | python | cores_per_node | (system = system()) | return _system_params[system].cores_per_node | Number of CPU cores per node. | Number of CPU cores per node. | [
"Number",
"of",
"CPU",
"cores",
"per",
"node",
"."
] | def cores_per_node(system = system()):
"""Number of CPU cores per node."""
if not is_olcf_system(system):
raise RuntimeError('unknown system (' + system + ')')
return _system_params[system].cores_per_node | [
"def",
"cores_per_node",
"(",
"system",
"=",
"system",
"(",
")",
")",
":",
"if",
"not",
"is_olcf_system",
"(",
"system",
")",
":",
"raise",
"RuntimeError",
"(",
"'unknown system ('",
"+",
"system",
"+",
"')'",
")",
"return",
"_system_params",
"[",
"system",
"]",
".",
"cores_per_node"
] | https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/contrib/olcf/systems.py#L50-L54 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/setup.py | python | GenerateSrcPackageFiles | () | return data | Generate the list of files to include in a source package dist/install | Generate the list of files to include in a source package dist/install | [
"Generate",
"the",
"list",
"of",
"files",
"to",
"include",
"in",
"a",
"source",
"package",
"dist",
"/",
"install"
] | def GenerateSrcPackageFiles():
"""Generate the list of files to include in a source package dist/install"""
data = [ "src/*.py", "src/syntax/*.py", "src/autocomp/*.py",
"src/eclib/*.py", "docs/*.txt", "pixmaps/*.png", "pixmaps/*.ico",
"src/ebmlib/*.py",
"ekeys/*.ekeys",
"Editra",
"src/extern/*.py",
"src/extern/aui/*.py",
"src/extern/dexml/*.py",
"src/extern/pygments/*.py",
"src/extern/pygments/formatters/*.py",
"src/extern/pygments/filters/*.py",
"src/extern/pygments/lexers/*.py",
"src/extern/pygments/styles/*.py",
"pixmaps/*.icns",
"pixmaps/theme/Default/README",
"pixmaps/theme/Tango/AUTHOR",
"pixmaps/theme/Tango/COPYING",
"pixmaps/theme/Tango/toolbar/*.png",
"pixmaps/theme/Tango/menu/*.png",
"pixmaps/theme/Tango/mime/*.png",
"pixmaps/theme/Default/README",
"pixmaps/theme/Tango/other/*.png",
"styles/*.ess", "tests/syntax/*",
"AUTHORS", "CHANGELOG","COPYING", "FAQ", "INSTALL", "NEWS",
"README", "THANKS", "TODO", "setup.cfg" ]
# Get the local files
for loc_dir in os.listdir("locale"):
tmp = "locale/" + loc_dir
if os.path.isdir(tmp):
tmp = tmp + "/LC_MESSAGES/Editra.mo"
if os.path.exists(tmp):
data.append(tmp)
# NOTE: plugins selected to package in build step
return data | [
"def",
"GenerateSrcPackageFiles",
"(",
")",
":",
"data",
"=",
"[",
"\"src/*.py\"",
",",
"\"src/syntax/*.py\"",
",",
"\"src/autocomp/*.py\"",
",",
"\"src/eclib/*.py\"",
",",
"\"docs/*.txt\"",
",",
"\"pixmaps/*.png\"",
",",
"\"pixmaps/*.ico\"",
",",
"\"src/ebmlib/*.py\"",
",",
"\"ekeys/*.ekeys\"",
",",
"\"Editra\"",
",",
"\"src/extern/*.py\"",
",",
"\"src/extern/aui/*.py\"",
",",
"\"src/extern/dexml/*.py\"",
",",
"\"src/extern/pygments/*.py\"",
",",
"\"src/extern/pygments/formatters/*.py\"",
",",
"\"src/extern/pygments/filters/*.py\"",
",",
"\"src/extern/pygments/lexers/*.py\"",
",",
"\"src/extern/pygments/styles/*.py\"",
",",
"\"pixmaps/*.icns\"",
",",
"\"pixmaps/theme/Default/README\"",
",",
"\"pixmaps/theme/Tango/AUTHOR\"",
",",
"\"pixmaps/theme/Tango/COPYING\"",
",",
"\"pixmaps/theme/Tango/toolbar/*.png\"",
",",
"\"pixmaps/theme/Tango/menu/*.png\"",
",",
"\"pixmaps/theme/Tango/mime/*.png\"",
",",
"\"pixmaps/theme/Default/README\"",
",",
"\"pixmaps/theme/Tango/other/*.png\"",
",",
"\"styles/*.ess\"",
",",
"\"tests/syntax/*\"",
",",
"\"AUTHORS\"",
",",
"\"CHANGELOG\"",
",",
"\"COPYING\"",
",",
"\"FAQ\"",
",",
"\"INSTALL\"",
",",
"\"NEWS\"",
",",
"\"README\"",
",",
"\"THANKS\"",
",",
"\"TODO\"",
",",
"\"setup.cfg\"",
"]",
"# Get the local files",
"for",
"loc_dir",
"in",
"os",
".",
"listdir",
"(",
"\"locale\"",
")",
":",
"tmp",
"=",
"\"locale/\"",
"+",
"loc_dir",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"tmp",
")",
":",
"tmp",
"=",
"tmp",
"+",
"\"/LC_MESSAGES/Editra.mo\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"tmp",
")",
":",
"data",
".",
"append",
"(",
"tmp",
")",
"# NOTE: plugins selected to package in build step",
"return",
"data"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/setup.py#L161-L199 | |
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | python_packaging/src/gmxapi/operation.py | python | pop_context | () | return __current_context.pop() | Exit the current Context by popping it from the stack. | Exit the current Context by popping it from the stack. | [
"Exit",
"the",
"current",
"Context",
"by",
"popping",
"it",
"from",
"the",
"stack",
"."
] | def pop_context() -> Context:
"""Exit the current Context by popping it from the stack."""
return __current_context.pop() | [
"def",
"pop_context",
"(",
")",
"->",
"Context",
":",
"return",
"__current_context",
".",
"pop",
"(",
")"
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/operation.py#L2825-L2827 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/misc_util.py | python | Configuration.add_define_macros | (self, macros) | Add define macros to configuration
Add the given sequence of macro name and value duples to the beginning
of the define_macros list This list will be visible to all extension
modules of the current package. | Add define macros to configuration | [
"Add",
"define",
"macros",
"to",
"configuration"
] | def add_define_macros(self, macros):
"""Add define macros to configuration
Add the given sequence of macro name and value duples to the beginning
of the define_macros list This list will be visible to all extension
modules of the current package.
"""
dist = self.get_distribution()
if dist is not None:
if not hasattr(dist, 'define_macros'):
dist.define_macros = []
dist.define_macros.extend(macros)
else:
self.define_macros.extend(macros) | [
"def",
"add_define_macros",
"(",
"self",
",",
"macros",
")",
":",
"dist",
"=",
"self",
".",
"get_distribution",
"(",
")",
"if",
"dist",
"is",
"not",
"None",
":",
"if",
"not",
"hasattr",
"(",
"dist",
",",
"'define_macros'",
")",
":",
"dist",
".",
"define_macros",
"=",
"[",
"]",
"dist",
".",
"define_macros",
".",
"extend",
"(",
"macros",
")",
"else",
":",
"self",
".",
"define_macros",
".",
"extend",
"(",
"macros",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/misc_util.py#L1336-L1349 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py | python | _Semaphore.acquire | (self, blocking=1) | return rc | Acquire a semaphore, decrementing the internal counter by one.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called release() to
make it larger than zero. This is done with proper interlocking so that
if multiple acquire() calls are blocked, release() will wake exactly one
of them up. The implementation may pick one at random, so the order in
which blocked threads are awakened should not be relied on. There is no
return value in this case.
When invoked with blocking set to true, do the same thing as when called
without arguments, and return true.
When invoked with blocking set to false, do not block. If a call without
an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true. | Acquire a semaphore, decrementing the internal counter by one. | [
"Acquire",
"a",
"semaphore",
"decrementing",
"the",
"internal",
"counter",
"by",
"one",
"."
] | def acquire(self, blocking=1):
"""Acquire a semaphore, decrementing the internal counter by one.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called release() to
make it larger than zero. This is done with proper interlocking so that
if multiple acquire() calls are blocked, release() will wake exactly one
of them up. The implementation may pick one at random, so the order in
which blocked threads are awakened should not be relied on. There is no
return value in this case.
When invoked with blocking set to true, do the same thing as when called
without arguments, and return true.
When invoked with blocking set to false, do not block. If a call without
an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.
"""
rc = False
with self.__cond:
while self.__value == 0:
if not blocking:
break
if __debug__:
self._note("%s.acquire(%s): blocked waiting, value=%s",
self, blocking, self.__value)
self.__cond.wait()
else:
self.__value = self.__value - 1
if __debug__:
self._note("%s.acquire: success, value=%s",
self, self.__value)
rc = True
return rc | [
"def",
"acquire",
"(",
"self",
",",
"blocking",
"=",
"1",
")",
":",
"rc",
"=",
"False",
"with",
"self",
".",
"__cond",
":",
"while",
"self",
".",
"__value",
"==",
"0",
":",
"if",
"not",
"blocking",
":",
"break",
"if",
"__debug__",
":",
"self",
".",
"_note",
"(",
"\"%s.acquire(%s): blocked waiting, value=%s\"",
",",
"self",
",",
"blocking",
",",
"self",
".",
"__value",
")",
"self",
".",
"__cond",
".",
"wait",
"(",
")",
"else",
":",
"self",
".",
"__value",
"=",
"self",
".",
"__value",
"-",
"1",
"if",
"__debug__",
":",
"self",
".",
"_note",
"(",
"\"%s.acquire: success, value=%s\"",
",",
"self",
",",
"self",
".",
"__value",
")",
"rc",
"=",
"True",
"return",
"rc"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py#L439-L474 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/oracle/connector.py | python | OracleDBConnector.getTableRowEstimation | (self, table) | Find the estimated number of rows of a table. | Find the estimated number of rows of a table. | [
"Find",
"the",
"estimated",
"number",
"of",
"rows",
"of",
"a",
"table",
"."
] | def getTableRowEstimation(self, table):
""" Find the estimated number of rows of a table. """
schema, tablename = self.getSchemaTableName(table)
prefix = u"ALL" if schema else u"USER"
where = u"AND OWNER = {}".format(
self.quoteString(schema)) if schema else u""
sql = u"""
SELECT NUM_ROWS FROM {0}_ALL_TABLES
WHERE TABLE_NAME = {1}
{2}
""".format(prefix, self.quoteString(tablename), where)
c = self._execute(None, sql)
res = self._fetchone(c)
c.close()
if not res or res[0] == NULL:
return 0
else:
return int(res[0]) | [
"def",
"getTableRowEstimation",
"(",
"self",
",",
"table",
")",
":",
"schema",
",",
"tablename",
"=",
"self",
".",
"getSchemaTableName",
"(",
"table",
")",
"prefix",
"=",
"u\"ALL\"",
"if",
"schema",
"else",
"u\"USER\"",
"where",
"=",
"u\"AND OWNER = {}\"",
".",
"format",
"(",
"self",
".",
"quoteString",
"(",
"schema",
")",
")",
"if",
"schema",
"else",
"u\"\"",
"sql",
"=",
"u\"\"\"\n SELECT NUM_ROWS FROM {0}_ALL_TABLES\n WHERE TABLE_NAME = {1}\n {2}\n \"\"\"",
".",
"format",
"(",
"prefix",
",",
"self",
".",
"quoteString",
"(",
"tablename",
")",
",",
"where",
")",
"c",
"=",
"self",
".",
"_execute",
"(",
"None",
",",
"sql",
")",
"res",
"=",
"self",
".",
"_fetchone",
"(",
"c",
")",
"c",
".",
"close",
"(",
")",
"if",
"not",
"res",
"or",
"res",
"[",
"0",
"]",
"==",
"NULL",
":",
"return",
"0",
"else",
":",
"return",
"int",
"(",
"res",
"[",
"0",
"]",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/oracle/connector.py#L821-L841 | ||
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/tree.py | python | RewriteRuleElementStream.toTree | (self, el) | return el | Ensure stream emits trees; tokens must be converted to AST nodes.
AST nodes can be passed through unmolested. | Ensure stream emits trees; tokens must be converted to AST nodes.
AST nodes can be passed through unmolested. | [
"Ensure",
"stream",
"emits",
"trees",
";",
"tokens",
"must",
"be",
"converted",
"to",
"AST",
"nodes",
".",
"AST",
"nodes",
"can",
"be",
"passed",
"through",
"unmolested",
"."
] | def toTree(self, el):
"""
Ensure stream emits trees; tokens must be converted to AST nodes.
AST nodes can be passed through unmolested.
"""
return el | [
"def",
"toTree",
"(",
"self",
",",
"el",
")",
":",
"return",
"el"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/tree.py#L2315-L2321 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.CreateDocument | (*args, **kwargs) | return _stc.StyledTextCtrl_CreateDocument(*args, **kwargs) | CreateDocument(self) -> void
Create a new document object.
Starts with reference count of 1 and not selected into editor. | CreateDocument(self) -> void | [
"CreateDocument",
"(",
"self",
")",
"-",
">",
"void"
] | def CreateDocument(*args, **kwargs):
"""
CreateDocument(self) -> void
Create a new document object.
Starts with reference count of 1 and not selected into editor.
"""
return _stc.StyledTextCtrl_CreateDocument(*args, **kwargs) | [
"def",
"CreateDocument",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_CreateDocument",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4989-L4996 | |
alexgkendall/caffe-posenet | 62aafbd7c45df91acdba14f5d1406d8295c2bc6f | scripts/cpp_lint.py | python | GetLineWidth | (line) | Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters. | Determines the width of the line in column positions. | [
"Determines",
"the",
"width",
"of",
"the",
"line",
"in",
"column",
"positions",
"."
] | def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line) | [
"def",
"GetLineWidth",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"width",
"=",
"0",
"for",
"uc",
"in",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"line",
")",
":",
"if",
"unicodedata",
".",
"east_asian_width",
"(",
"uc",
")",
"in",
"(",
"'W'",
",",
"'F'",
")",
":",
"width",
"+=",
"2",
"elif",
"not",
"unicodedata",
".",
"combining",
"(",
"uc",
")",
":",
"width",
"+=",
"1",
"return",
"width",
"else",
":",
"return",
"len",
"(",
"line",
")"
] | https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/scripts/cpp_lint.py#L3437-L3456 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/scons/khEnvironment.py | python | DefineProtocolBufferBuilder | (env) | SCons entry point for this tool.
Args:
env: Environment to modify. | SCons entry point for this tool. | [
"SCons",
"entry",
"point",
"for",
"this",
"tool",
"."
] | def DefineProtocolBufferBuilder(env):
# Note: SCons requires the use of this name, which fails gpylint.
"""SCons entry point for this tool.
Args:
env: Environment to modify.
"""
# All protocol buffer generated files will be placed in the export directory
# under protobuf.
# To include them, the caller need only include "protobuf/xxx.pb.h"
out_dir = os.path.join(env.exportdirs['root'], 'protobuf')
out_dir = out_dir.strip('#')
out_dir = os.path.abspath(out_dir)
env.Replace(
# Root of output; files will be placed in subdirs of this mirroring the
# source tree.
PROTOBUF_OUT_ROOT=out_dir
)
# Set tool based on local platform
env['TOOLS_BIN'] = env.fs.Dir('../tools/bin/')
env['PROTOBUF_COMPILER'] = 'protoc'
# Add protocol buffer builder
bld = SCons.Script.Builder(generator=ProtocolBufferGenerator,
emitter=ProtocolBufferEmitter,
single_source=1,
suffix='.pb.cc')
env.Append(BUILDERS={'ProtocolBuffer': bld}) | [
"def",
"DefineProtocolBufferBuilder",
"(",
"env",
")",
":",
"# Note: SCons requires the use of this name, which fails gpylint.",
"# All protocol buffer generated files will be placed in the export directory",
"# under protobuf.",
"# To include them, the caller need only include \"protobuf/xxx.pb.h\"",
"out_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env",
".",
"exportdirs",
"[",
"'root'",
"]",
",",
"'protobuf'",
")",
"out_dir",
"=",
"out_dir",
".",
"strip",
"(",
"'#'",
")",
"out_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"out_dir",
")",
"env",
".",
"Replace",
"(",
"# Root of output; files will be placed in subdirs of this mirroring the",
"# source tree.",
"PROTOBUF_OUT_ROOT",
"=",
"out_dir",
")",
"# Set tool based on local platform",
"env",
"[",
"'TOOLS_BIN'",
"]",
"=",
"env",
".",
"fs",
".",
"Dir",
"(",
"'../tools/bin/'",
")",
"env",
"[",
"'PROTOBUF_COMPILER'",
"]",
"=",
"'protoc'",
"# Add protocol buffer builder",
"bld",
"=",
"SCons",
".",
"Script",
".",
"Builder",
"(",
"generator",
"=",
"ProtocolBufferGenerator",
",",
"emitter",
"=",
"ProtocolBufferEmitter",
",",
"single_source",
"=",
"1",
",",
"suffix",
"=",
"'.pb.cc'",
")",
"env",
".",
"Append",
"(",
"BUILDERS",
"=",
"{",
"'ProtocolBuffer'",
":",
"bld",
"}",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/scons/khEnvironment.py#L721-L751 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/simpleapi.py | python | EvaluateFunction | (*args, **kwargs) | return None | This function evaluates a function on a data set.
The data set is defined in a way similar to Fit algorithm.
Example:
EvaluateFunction(Function='name=LinearBackground,A0=0.3', InputWorkspace=dataWS',
StartX='0.05',EndX='1.0',Output="Z1") | This function evaluates a function on a data set.
The data set is defined in a way similar to Fit algorithm. | [
"This",
"function",
"evaluates",
"a",
"function",
"on",
"a",
"data",
"set",
".",
"The",
"data",
"set",
"is",
"defined",
"in",
"a",
"way",
"similar",
"to",
"Fit",
"algorithm",
"."
] | def EvaluateFunction(*args, **kwargs):
"""
This function evaluates a function on a data set.
The data set is defined in a way similar to Fit algorithm.
Example:
EvaluateFunction(Function='name=LinearBackground,A0=0.3', InputWorkspace=dataWS',
StartX='0.05',EndX='1.0',Output="Z1")
"""
return None | [
"def",
"EvaluateFunction",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"None"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/simpleapi.py#L365-L374 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/edit_site_config.py | python | EditSiteConfigHandler.get | (self) | Renders the UI with the form. | Renders the UI with the form. | [
"Renders",
"the",
"UI",
"with",
"the",
"form",
"."
] | def get(self):
"""Renders the UI with the form."""
key = self.request.get('key')
if not key:
self.RenderHtml('edit_site_config.html', {})
return
value = stored_object.Get(key)
external_value = namespaced_stored_object.GetExternal(key)
internal_value = namespaced_stored_object.Get(key)
self.RenderHtml('edit_site_config.html', {
'key': key,
'value': _FormatJson(value),
'external_value': _FormatJson(external_value),
'internal_value': _FormatJson(internal_value),
}) | [
"def",
"get",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"request",
".",
"get",
"(",
"'key'",
")",
"if",
"not",
"key",
":",
"self",
".",
"RenderHtml",
"(",
"'edit_site_config.html'",
",",
"{",
"}",
")",
"return",
"value",
"=",
"stored_object",
".",
"Get",
"(",
"key",
")",
"external_value",
"=",
"namespaced_stored_object",
".",
"GetExternal",
"(",
"key",
")",
"internal_value",
"=",
"namespaced_stored_object",
".",
"Get",
"(",
"key",
")",
"self",
".",
"RenderHtml",
"(",
"'edit_site_config.html'",
",",
"{",
"'key'",
":",
"key",
",",
"'value'",
":",
"_FormatJson",
"(",
"value",
")",
",",
"'external_value'",
":",
"_FormatJson",
"(",
"external_value",
")",
",",
"'internal_value'",
":",
"_FormatJson",
"(",
"internal_value",
")",
",",
"}",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/edit_site_config.py#L49-L64 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/platform.py | python | _platform | (*args) | return platform | Helper to format the platform string in a filename
compatible format e.g. "system-version-machine". | Helper to format the platform string in a filename
compatible format e.g. "system-version-machine". | [
"Helper",
"to",
"format",
"the",
"platform",
"string",
"in",
"a",
"filename",
"compatible",
"format",
"e",
".",
"g",
".",
"system",
"-",
"version",
"-",
"machine",
"."
] | def _platform(*args):
""" Helper to format the platform string in a filename
compatible format e.g. "system-version-machine".
"""
# Format the platform string
platform = string.join(
map(string.strip,
filter(len, args)),
'-')
# Cleanup some possible filename obstacles...
replace = string.replace
platform = replace(platform,' ','_')
platform = replace(platform,'/','-')
platform = replace(platform,'\\','-')
platform = replace(platform,':','-')
platform = replace(platform,';','-')
platform = replace(platform,'"','-')
platform = replace(platform,'(','-')
platform = replace(platform,')','-')
# No need to report 'unknown' information...
platform = replace(platform,'unknown','')
# Fold '--'s and remove trailing '-'
while 1:
cleaned = replace(platform,'--','-')
if cleaned == platform:
break
platform = cleaned
while platform[-1] == '-':
platform = platform[:-1]
return platform | [
"def",
"_platform",
"(",
"*",
"args",
")",
":",
"# Format the platform string",
"platform",
"=",
"string",
".",
"join",
"(",
"map",
"(",
"string",
".",
"strip",
",",
"filter",
"(",
"len",
",",
"args",
")",
")",
",",
"'-'",
")",
"# Cleanup some possible filename obstacles...",
"replace",
"=",
"string",
".",
"replace",
"platform",
"=",
"replace",
"(",
"platform",
",",
"' '",
",",
"'_'",
")",
"platform",
"=",
"replace",
"(",
"platform",
",",
"'/'",
",",
"'-'",
")",
"platform",
"=",
"replace",
"(",
"platform",
",",
"'\\\\'",
",",
"'-'",
")",
"platform",
"=",
"replace",
"(",
"platform",
",",
"':'",
",",
"'-'",
")",
"platform",
"=",
"replace",
"(",
"platform",
",",
"';'",
",",
"'-'",
")",
"platform",
"=",
"replace",
"(",
"platform",
",",
"'\"'",
",",
"'-'",
")",
"platform",
"=",
"replace",
"(",
"platform",
",",
"'('",
",",
"'-'",
")",
"platform",
"=",
"replace",
"(",
"platform",
",",
"')'",
",",
"'-'",
")",
"# No need to report 'unknown' information...",
"platform",
"=",
"replace",
"(",
"platform",
",",
"'unknown'",
",",
"''",
")",
"# Fold '--'s and remove trailing '-'",
"while",
"1",
":",
"cleaned",
"=",
"replace",
"(",
"platform",
",",
"'--'",
",",
"'-'",
")",
"if",
"cleaned",
"==",
"platform",
":",
"break",
"platform",
"=",
"cleaned",
"while",
"platform",
"[",
"-",
"1",
"]",
"==",
"'-'",
":",
"platform",
"=",
"platform",
"[",
":",
"-",
"1",
"]",
"return",
"platform"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/platform.py#L922-L956 | |
s9xie/DSN | 065e49898d239f5c96be558616b2556eabc50351 | scripts/cpp_lint.py | python | Error | (filename, linenum, category, confidence, message) | Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message. | Logs the fact we've found a lint error. | [
"Logs",
"the",
"fact",
"we",
"ve",
"found",
"a",
"lint",
"error",
"."
] | def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence)) | [
"def",
"Error",
"(",
"filename",
",",
"linenum",
",",
"category",
",",
"confidence",
",",
"message",
")",
":",
"if",
"_ShouldPrintError",
"(",
"category",
",",
"confidence",
",",
"linenum",
")",
":",
"_cpplint_state",
".",
"IncrementErrorCount",
"(",
"category",
")",
"if",
"_cpplint_state",
".",
"output_format",
"==",
"'vs7'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s(%s): %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")",
"elif",
"_cpplint_state",
".",
"output_format",
"==",
"'eclipse'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s:%s: warning: %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s:%s: %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")"
] | https://github.com/s9xie/DSN/blob/065e49898d239f5c96be558616b2556eabc50351/scripts/cpp_lint.py#L983-L1015 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/randomimpl.py | python | get_rnd_shuffle | (builder) | return fn | Get the internal function to shuffle the MT taste. | Get the internal function to shuffle the MT taste. | [
"Get",
"the",
"internal",
"function",
"to",
"shuffle",
"the",
"MT",
"taste",
"."
] | def get_rnd_shuffle(builder):
"""
Get the internal function to shuffle the MT taste.
"""
fnty = ir.FunctionType(ir.VoidType(), (rnd_state_ptr_t,))
fn = builder.function.module.get_or_insert_function(fnty, "numba_rnd_shuffle")
fn.args[0].add_attribute("nocapture")
return fn | [
"def",
"get_rnd_shuffle",
"(",
"builder",
")",
":",
"fnty",
"=",
"ir",
".",
"FunctionType",
"(",
"ir",
".",
"VoidType",
"(",
")",
",",
"(",
"rnd_state_ptr_t",
",",
")",
")",
"fn",
"=",
"builder",
".",
"function",
".",
"module",
".",
"get_or_insert_function",
"(",
"fnty",
",",
"\"numba_rnd_shuffle\"",
")",
"fn",
".",
"args",
"[",
"0",
"]",
".",
"add_attribute",
"(",
"\"nocapture\"",
")",
"return",
"fn"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/randomimpl.py#L96-L103 | |
danbev/learning-v8 | 2b3e17f59c5c79c61f1ae48de953626535312f32 | lldb_commands.py | python | jld | (debugger, param, *args) | Print a v8 LayoutDescriptor object | Print a v8 LayoutDescriptor object | [
"Print",
"a",
"v8",
"LayoutDescriptor",
"object"
] | def jld(debugger, param, *args):
"""Print a v8 LayoutDescriptor object"""
ptr_arg_cmd(debugger, 'jld', param,
"_v8_internal_Print_LayoutDescriptor({})") | [
"def",
"jld",
"(",
"debugger",
",",
"param",
",",
"*",
"args",
")",
":",
"ptr_arg_cmd",
"(",
"debugger",
",",
"'jld'",
",",
"param",
",",
"\"_v8_internal_Print_LayoutDescriptor({})\"",
")"
] | https://github.com/danbev/learning-v8/blob/2b3e17f59c5c79c61f1ae48de953626535312f32/lldb_commands.py#L66-L69 | ||
cocos2d/cocos2d-x | 90f6542cf7fb081335f04e474b880d7ce8c445a1 | download-deps.py | python | CocosZipInstaller.unpack_zipfile | (self, extract_dir) | Unpack zip `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
by ``zipfile.is_zipfile()``). | Unpack zip `filename` to `extract_dir` | [
"Unpack",
"zip",
"filename",
"to",
"extract_dir"
] | def unpack_zipfile(self, extract_dir):
"""Unpack zip `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
by ``zipfile.is_zipfile()``).
"""
if not zipfile.is_zipfile(self._filename):
raise UnrecognizedFormat("%s is not a zip file" % (self._filename))
print("==> Extracting files, please wait ...")
z = zipfile.ZipFile(self._filename)
try:
for info in z.infolist():
name = info.filename
# don't extract absolute paths or ones with .. in them
if name.startswith('/') or '..' in name:
continue
target = os.path.join(extract_dir, *name.split('/'))
if not target:
continue
if name.endswith('/'):
# directory
self.ensure_directory(target)
else:
# file
data = z.read(info.filename)
f = open(target, 'wb')
try:
f.write(data)
finally:
f.close()
del data
unix_attributes = info.external_attr >> 16
if unix_attributes:
os.chmod(target, unix_attributes)
finally:
z.close()
print("==> Extraction done!") | [
"def",
"unpack_zipfile",
"(",
"self",
",",
"extract_dir",
")",
":",
"if",
"not",
"zipfile",
".",
"is_zipfile",
"(",
"self",
".",
"_filename",
")",
":",
"raise",
"UnrecognizedFormat",
"(",
"\"%s is not a zip file\"",
"%",
"(",
"self",
".",
"_filename",
")",
")",
"print",
"(",
"\"==> Extracting files, please wait ...\"",
")",
"z",
"=",
"zipfile",
".",
"ZipFile",
"(",
"self",
".",
"_filename",
")",
"try",
":",
"for",
"info",
"in",
"z",
".",
"infolist",
"(",
")",
":",
"name",
"=",
"info",
".",
"filename",
"# don't extract absolute paths or ones with .. in them",
"if",
"name",
".",
"startswith",
"(",
"'/'",
")",
"or",
"'..'",
"in",
"name",
":",
"continue",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"extract_dir",
",",
"*",
"name",
".",
"split",
"(",
"'/'",
")",
")",
"if",
"not",
"target",
":",
"continue",
"if",
"name",
".",
"endswith",
"(",
"'/'",
")",
":",
"# directory",
"self",
".",
"ensure_directory",
"(",
"target",
")",
"else",
":",
"# file",
"data",
"=",
"z",
".",
"read",
"(",
"info",
".",
"filename",
")",
"f",
"=",
"open",
"(",
"target",
",",
"'wb'",
")",
"try",
":",
"f",
".",
"write",
"(",
"data",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"del",
"data",
"unix_attributes",
"=",
"info",
".",
"external_attr",
">>",
"16",
"if",
"unix_attributes",
":",
"os",
".",
"chmod",
"(",
"target",
",",
"unix_attributes",
")",
"finally",
":",
"z",
".",
"close",
"(",
")",
"print",
"(",
"\"==> Extraction done!\"",
")"
] | https://github.com/cocos2d/cocos2d-x/blob/90f6542cf7fb081335f04e474b880d7ce8c445a1/download-deps.py#L203-L243 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/norm_inf.py | python | norm_inf.is_atom_convex | (self) | return True | Is the atom convex? | Is the atom convex? | [
"Is",
"the",
"atom",
"convex?"
] | def is_atom_convex(self) -> bool:
"""Is the atom convex?
"""
return True | [
"def",
"is_atom_convex",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/norm_inf.py#L46-L49 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/glib2.py | python | process_settings | (self) | Process the schema files in *settings_schema_files* to create :py:class:`waflib.Tools.glib2.glib_mkenums` instances. The
same files are validated through :py:class:`waflib.Tools.glib2.glib_validate_schema` tasks. | Process the schema files in *settings_schema_files* to create :py:class:`waflib.Tools.glib2.glib_mkenums` instances. The
same files are validated through :py:class:`waflib.Tools.glib2.glib_validate_schema` tasks. | [
"Process",
"the",
"schema",
"files",
"in",
"*",
"settings_schema_files",
"*",
"to",
"create",
":",
"py",
":",
"class",
":",
"waflib",
".",
"Tools",
".",
"glib2",
".",
"glib_mkenums",
"instances",
".",
"The",
"same",
"files",
"are",
"validated",
"through",
":",
"py",
":",
"class",
":",
"waflib",
".",
"Tools",
".",
"glib2",
".",
"glib_validate_schema",
"tasks",
"."
] | def process_settings(self):
"""
Process the schema files in *settings_schema_files* to create :py:class:`waflib.Tools.glib2.glib_mkenums` instances. The
same files are validated through :py:class:`waflib.Tools.glib2.glib_validate_schema` tasks.
"""
enums_tgt_node = []
install_files = []
settings_schema_files = getattr(self, 'settings_schema_files', [])
if settings_schema_files and not self.env['GLIB_COMPILE_SCHEMAS']:
raise Errors.WafError ("Unable to process GSettings schemas - glib-compile-schemas was not found during configure")
# 1. process gsettings_enum_files (generate .enums.xml)
#
if hasattr(self, 'settings_enum_files'):
enums_task = self.create_task('glib_mkenums')
source_list = self.settings_enum_files
source_list = [self.path.find_resource(k) for k in source_list]
enums_task.set_inputs(source_list)
enums_task.env['GLIB_MKENUMS_SOURCE'] = [k.abspath() for k in source_list]
target = self.settings_enum_namespace + '.enums.xml'
tgt_node = self.path.find_or_declare(target)
enums_task.set_outputs(tgt_node)
enums_task.env['GLIB_MKENUMS_TARGET'] = tgt_node.abspath()
enums_tgt_node = [tgt_node]
install_files.append (tgt_node)
options = '--comments "<!-- @comment@ -->" --fhead "<schemalist>" --vhead " <@type@ id=\\"%s.@EnumName@\\">" --vprod " <value nick=\\"@valuenick@\\" value=\\"@valuenum@\\"/>" --vtail " </@type@>" --ftail "</schemalist>" ' % (self.settings_enum_namespace)
enums_task.env['GLIB_MKENUMS_OPTIONS'] = options
# 2. process gsettings_schema_files (validate .gschema.xml files)
#
for schema in settings_schema_files:
schema_task = self.create_task ('glib_validate_schema')
schema_node = self.path.find_resource(schema)
if not schema_node:
raise Errors.WafError("Cannot find the schema file '%s'" % schema)
install_files.append(schema_node)
source_list = enums_tgt_node + [schema_node]
schema_task.set_inputs (source_list)
schema_task.env['GLIB_COMPILE_SCHEMAS_OPTIONS'] = [("--schema-file=" + k.abspath()) for k in source_list]
target_node = r_change_ext (schema_node, '.xml.valid')
schema_task.set_outputs (target_node)
schema_task.env['GLIB_VALIDATE_SCHEMA_OUTPUT'] = target_node.abspath()
# 3. schemas install task
def compile_schemas_callback(bld):
if not bld.is_install: return
Logs.pprint ('YELLOW','Updating GSettings schema cache')
command = Utils.subst_vars("${GLIB_COMPILE_SCHEMAS} ${GSETTINGSSCHEMADIR}", bld.env)
ret = self.bld.exec_command(command)
if self.bld.is_install:
if not self.env['GSETTINGSSCHEMADIR']:
raise Errors.WafError ('GSETTINGSSCHEMADIR not defined (should have been set up automatically during configure)')
if install_files:
self.bld.install_files (self.env['GSETTINGSSCHEMADIR'], install_files)
if not hasattr(self.bld, '_compile_schemas_registered'):
self.bld.add_post_fun (compile_schemas_callback)
self.bld._compile_schemas_registered = True | [
"def",
"process_settings",
"(",
"self",
")",
":",
"enums_tgt_node",
"=",
"[",
"]",
"install_files",
"=",
"[",
"]",
"settings_schema_files",
"=",
"getattr",
"(",
"self",
",",
"'settings_schema_files'",
",",
"[",
"]",
")",
"if",
"settings_schema_files",
"and",
"not",
"self",
".",
"env",
"[",
"'GLIB_COMPILE_SCHEMAS'",
"]",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"\"Unable to process GSettings schemas - glib-compile-schemas was not found during configure\"",
")",
"# 1. process gsettings_enum_files (generate .enums.xml)",
"#",
"if",
"hasattr",
"(",
"self",
",",
"'settings_enum_files'",
")",
":",
"enums_task",
"=",
"self",
".",
"create_task",
"(",
"'glib_mkenums'",
")",
"source_list",
"=",
"self",
".",
"settings_enum_files",
"source_list",
"=",
"[",
"self",
".",
"path",
".",
"find_resource",
"(",
"k",
")",
"for",
"k",
"in",
"source_list",
"]",
"enums_task",
".",
"set_inputs",
"(",
"source_list",
")",
"enums_task",
".",
"env",
"[",
"'GLIB_MKENUMS_SOURCE'",
"]",
"=",
"[",
"k",
".",
"abspath",
"(",
")",
"for",
"k",
"in",
"source_list",
"]",
"target",
"=",
"self",
".",
"settings_enum_namespace",
"+",
"'.enums.xml'",
"tgt_node",
"=",
"self",
".",
"path",
".",
"find_or_declare",
"(",
"target",
")",
"enums_task",
".",
"set_outputs",
"(",
"tgt_node",
")",
"enums_task",
".",
"env",
"[",
"'GLIB_MKENUMS_TARGET'",
"]",
"=",
"tgt_node",
".",
"abspath",
"(",
")",
"enums_tgt_node",
"=",
"[",
"tgt_node",
"]",
"install_files",
".",
"append",
"(",
"tgt_node",
")",
"options",
"=",
"'--comments \"<!-- @comment@ -->\" --fhead \"<schemalist>\" --vhead \" <@type@ id=\\\\\"%s.@EnumName@\\\\\">\" --vprod \" <value nick=\\\\\"@valuenick@\\\\\" value=\\\\\"@valuenum@\\\\\"/>\" --vtail \" </@type@>\" --ftail \"</schemalist>\" '",
"%",
"(",
"self",
".",
"settings_enum_namespace",
")",
"enums_task",
".",
"env",
"[",
"'GLIB_MKENUMS_OPTIONS'",
"]",
"=",
"options",
"# 2. process gsettings_schema_files (validate .gschema.xml files)",
"#",
"for",
"schema",
"in",
"settings_schema_files",
":",
"schema_task",
"=",
"self",
".",
"create_task",
"(",
"'glib_validate_schema'",
")",
"schema_node",
"=",
"self",
".",
"path",
".",
"find_resource",
"(",
"schema",
")",
"if",
"not",
"schema_node",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"\"Cannot find the schema file '%s'\"",
"%",
"schema",
")",
"install_files",
".",
"append",
"(",
"schema_node",
")",
"source_list",
"=",
"enums_tgt_node",
"+",
"[",
"schema_node",
"]",
"schema_task",
".",
"set_inputs",
"(",
"source_list",
")",
"schema_task",
".",
"env",
"[",
"'GLIB_COMPILE_SCHEMAS_OPTIONS'",
"]",
"=",
"[",
"(",
"\"--schema-file=\"",
"+",
"k",
".",
"abspath",
"(",
")",
")",
"for",
"k",
"in",
"source_list",
"]",
"target_node",
"=",
"r_change_ext",
"(",
"schema_node",
",",
"'.xml.valid'",
")",
"schema_task",
".",
"set_outputs",
"(",
"target_node",
")",
"schema_task",
".",
"env",
"[",
"'GLIB_VALIDATE_SCHEMA_OUTPUT'",
"]",
"=",
"target_node",
".",
"abspath",
"(",
")",
"# 3. schemas install task",
"def",
"compile_schemas_callback",
"(",
"bld",
")",
":",
"if",
"not",
"bld",
".",
"is_install",
":",
"return",
"Logs",
".",
"pprint",
"(",
"'YELLOW'",
",",
"'Updating GSettings schema cache'",
")",
"command",
"=",
"Utils",
".",
"subst_vars",
"(",
"\"${GLIB_COMPILE_SCHEMAS} ${GSETTINGSSCHEMADIR}\"",
",",
"bld",
".",
"env",
")",
"ret",
"=",
"self",
".",
"bld",
".",
"exec_command",
"(",
"command",
")",
"if",
"self",
".",
"bld",
".",
"is_install",
":",
"if",
"not",
"self",
".",
"env",
"[",
"'GSETTINGSSCHEMADIR'",
"]",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"'GSETTINGSSCHEMADIR not defined (should have been set up automatically during configure)'",
")",
"if",
"install_files",
":",
"self",
".",
"bld",
".",
"install_files",
"(",
"self",
".",
"env",
"[",
"'GSETTINGSSCHEMADIR'",
"]",
",",
"install_files",
")",
"if",
"not",
"hasattr",
"(",
"self",
".",
"bld",
",",
"'_compile_schemas_registered'",
")",
":",
"self",
".",
"bld",
".",
"add_post_fun",
"(",
"compile_schemas_callback",
")",
"self",
".",
"bld",
".",
"_compile_schemas_registered",
"=",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/glib2.py#L265-L333 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/devices.py | python | require_context | (fn) | return _require_cuda_context | A decorator that ensures a CUDA context is available when *fn* is executed.
Note: The function *fn* cannot switch CUDA-context. | A decorator that ensures a CUDA context is available when *fn* is executed. | [
"A",
"decorator",
"that",
"ensures",
"a",
"CUDA",
"context",
"is",
"available",
"when",
"*",
"fn",
"*",
"is",
"executed",
"."
] | def require_context(fn):
"""
A decorator that ensures a CUDA context is available when *fn* is executed.
Note: The function *fn* cannot switch CUDA-context.
"""
@functools.wraps(fn)
def _require_cuda_context(*args, **kws):
with _runtime.ensure_context():
return fn(*args, **kws)
return _require_cuda_context | [
"def",
"require_context",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"_require_cuda_context",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"with",
"_runtime",
".",
"ensure_context",
"(",
")",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
"return",
"_require_cuda_context"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/devices.py#L216-L227 | |
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | scripts/cpp_lint.py | python | IsBlankLine | (line) | return not line or line.isspace() | Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank. | Returns true if the given line is blank. | [
"Returns",
"true",
"if",
"the",
"given",
"line",
"is",
"blank",
"."
] | def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | [
"def",
"IsBlankLine",
"(",
"line",
")",
":",
"return",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")"
] | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/scripts/cpp_lint.py#L2369-L2381 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/gluon/probability/distributions/binomial.py | python | Binomial.logit | (self) | return prob2logit(self.prob, True) | Get the log-odds of sampling `1`.
Returns
-------
Tensor
Parameter tensor. | Get the log-odds of sampling `1`. | [
"Get",
"the",
"log",
"-",
"odds",
"of",
"sampling",
"1",
"."
] | def logit(self):
"""Get the log-odds of sampling `1`.
Returns
-------
Tensor
Parameter tensor.
"""
# pylint: disable=method-hidden
return prob2logit(self.prob, True) | [
"def",
"logit",
"(",
"self",
")",
":",
"# pylint: disable=method-hidden",
"return",
"prob2logit",
"(",
"self",
".",
"prob",
",",
"True",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/binomial.py#L78-L87 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/CrystalField/fitting.py | python | CrystalField.getHeatCapacity | (self, workspace=None, ws_index=0) | return self._getPhysProp(PhysicalProperties('Cv'), workspace, ws_index) | Get the heat cacpacity calculated with the current crystal field parameters
Examples:
cf.getHeatCapacity() # Returns the heat capacity from 1 < T < 300 K in 1 K steps
cf.getHeatCapacity(ws) # Returns the heat capacity with temperatures given by ws.
cf.getHeatCapacity(ws, ws_index) # Use the spectrum indicated by ws_index for x-values
@param workspace: Either a Mantid workspace whose x-values will be used as the temperatures
to calculate the heat capacity; or a list of numpy ndarray of temperatures.
Temperatures are in Kelvin.
@param ws_index: The index of a spectrum in workspace to use (default=0). | Get the heat cacpacity calculated with the current crystal field parameters | [
"Get",
"the",
"heat",
"cacpacity",
"calculated",
"with",
"the",
"current",
"crystal",
"field",
"parameters"
] | def getHeatCapacity(self, workspace=None, ws_index=0):
"""
Get the heat cacpacity calculated with the current crystal field parameters
Examples:
cf.getHeatCapacity() # Returns the heat capacity from 1 < T < 300 K in 1 K steps
cf.getHeatCapacity(ws) # Returns the heat capacity with temperatures given by ws.
cf.getHeatCapacity(ws, ws_index) # Use the spectrum indicated by ws_index for x-values
@param workspace: Either a Mantid workspace whose x-values will be used as the temperatures
to calculate the heat capacity; or a list of numpy ndarray of temperatures.
Temperatures are in Kelvin.
@param ws_index: The index of a spectrum in workspace to use (default=0).
"""
return self._getPhysProp(PhysicalProperties('Cv'), workspace, ws_index) | [
"def",
"getHeatCapacity",
"(",
"self",
",",
"workspace",
"=",
"None",
",",
"ws_index",
"=",
"0",
")",
":",
"return",
"self",
".",
"_getPhysProp",
"(",
"PhysicalProperties",
"(",
"'Cv'",
")",
",",
"workspace",
",",
"ws_index",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/CrystalField/fitting.py#L769-L784 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/__init__.py | python | channel_ready_future | (channel) | return _utilities.channel_ready_future(channel) | Creates a Future that tracks when a Channel is ready.
Cancelling the Future does not affect the channel's state machine.
It merely decouples the Future from channel state machine.
Args:
channel: A Channel object.
Returns:
A Future object that matures when the channel connectivity is
ChannelConnectivity.READY. | Creates a Future that tracks when a Channel is ready. | [
"Creates",
"a",
"Future",
"that",
"tracks",
"when",
"a",
"Channel",
"is",
"ready",
"."
] | def channel_ready_future(channel):
"""Creates a Future that tracks when a Channel is ready.
Cancelling the Future does not affect the channel's state machine.
It merely decouples the Future from channel state machine.
Args:
channel: A Channel object.
Returns:
A Future object that matures when the channel connectivity is
ChannelConnectivity.READY.
"""
from grpc import _utilities # pylint: disable=cyclic-import
return _utilities.channel_ready_future(channel) | [
"def",
"channel_ready_future",
"(",
"channel",
")",
":",
"from",
"grpc",
"import",
"_utilities",
"# pylint: disable=cyclic-import",
"return",
"_utilities",
".",
"channel_ready_future",
"(",
"channel",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/__init__.py#L1945-L1959 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/linalg_ops.py | python | _BatchSelfAdjointEigShape | (op) | return [out_shape] | Shape function for batch self-adjoint eigensolver op. | Shape function for batch self-adjoint eigensolver op. | [
"Shape",
"function",
"for",
"batch",
"self",
"-",
"adjoint",
"eigensolver",
"op",
"."
] | def _BatchSelfAdjointEigShape(op):
"""Shape function for batch self-adjoint eigensolver op."""
input_shape = op.inputs[0].get_shape().with_rank_at_least(2)
# The matrices in the batch must be square.
input_shape[-1].assert_is_compatible_with(input_shape[-2])
dlist = input_shape.dims
dlist[-2] += 1
out_shape = tensor_shape.TensorShape(dlist)
return [out_shape] | [
"def",
"_BatchSelfAdjointEigShape",
"(",
"op",
")",
":",
"input_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank_at_least",
"(",
"2",
")",
"# The matrices in the batch must be square.",
"input_shape",
"[",
"-",
"1",
"]",
".",
"assert_is_compatible_with",
"(",
"input_shape",
"[",
"-",
"2",
"]",
")",
"dlist",
"=",
"input_shape",
".",
"dims",
"dlist",
"[",
"-",
"2",
"]",
"+=",
"1",
"out_shape",
"=",
"tensor_shape",
".",
"TensorShape",
"(",
"dlist",
")",
"return",
"[",
"out_shape",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/linalg_ops.py#L89-L97 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | StandardDialogLayoutAdapter.FitWithScrolling | (*args, **kwargs) | return _windows_.StandardDialogLayoutAdapter_FitWithScrolling(*args, **kwargs) | FitWithScrolling(self, Dialog dialog, ScrolledWindow scrolledWindow) -> bool | FitWithScrolling(self, Dialog dialog, ScrolledWindow scrolledWindow) -> bool | [
"FitWithScrolling",
"(",
"self",
"Dialog",
"dialog",
"ScrolledWindow",
"scrolledWindow",
")",
"-",
">",
"bool"
] | def FitWithScrolling(*args, **kwargs):
"""FitWithScrolling(self, Dialog dialog, ScrolledWindow scrolledWindow) -> bool"""
return _windows_.StandardDialogLayoutAdapter_FitWithScrolling(*args, **kwargs) | [
"def",
"FitWithScrolling",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"StandardDialogLayoutAdapter_FitWithScrolling",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1014-L1016 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/webkit.py | python | WebKitStateChangedEvent.SetState | (*args, **kwargs) | return _webkit.WebKitStateChangedEvent_SetState(*args, **kwargs) | SetState(self, int state) | SetState(self, int state) | [
"SetState",
"(",
"self",
"int",
"state",
")"
] | def SetState(*args, **kwargs):
"""SetState(self, int state)"""
return _webkit.WebKitStateChangedEvent_SetState(*args, **kwargs) | [
"def",
"SetState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_webkit",
".",
"WebKitStateChangedEvent_SetState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/webkit.py#L242-L244 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/record_wpr.py | python | _GetSubclasses | (base_dir, cls) | return discover.DiscoverClasses(base_dir, base_dir, cls,
index_by_class_name=True) | Returns all subclasses of |cls| in |base_dir|.
Args:
cls: a class
Returns:
dict of {underscored_class_name: benchmark class} | Returns all subclasses of |cls| in |base_dir|. | [
"Returns",
"all",
"subclasses",
"of",
"|cls|",
"in",
"|base_dir|",
"."
] | def _GetSubclasses(base_dir, cls):
"""Returns all subclasses of |cls| in |base_dir|.
Args:
cls: a class
Returns:
dict of {underscored_class_name: benchmark class}
"""
return discover.DiscoverClasses(base_dir, base_dir, cls,
index_by_class_name=True) | [
"def",
"_GetSubclasses",
"(",
"base_dir",
",",
"cls",
")",
":",
"return",
"discover",
".",
"DiscoverClasses",
"(",
"base_dir",
",",
"base_dir",
",",
"cls",
",",
"index_by_class_name",
"=",
"True",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/record_wpr.py#L68-L78 | |
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert/run_classifier.py | python | ColaProcessor.get_labels | (self) | return ["0", "1"] | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_labels(self):
"""See base class."""
return ["0", "1"] | [
"def",
"get_labels",
"(",
"self",
")",
":",
"return",
"[",
"\"0\"",
",",
"\"1\"",
"]"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert/run_classifier.py#L354-L356 | |
Illumina/strelka | d7377443b62319f7c7bd70c241c4b2df3459e29a | src/python/scoringModelTraining/somatic/lib/evs/features/VcfFeatureSet.py | python | VcfFeatureSet.collectCore | (self, vcfname, headerKey = None) | return pandas.DataFrame(records, columns=cols) | Return a data frame with features collected from the given VCF
If headerKey is provided, then use this header value to extract labels
for the INFO EVSF feature tag | Return a data frame with features collected from the given VCF | [
"Return",
"a",
"data",
"frame",
"with",
"features",
"collected",
"from",
"the",
"given",
"VCF"
] | def collectCore(self, vcfname, headerKey = None):
"""
Return a data frame with features collected from the given VCF
If headerKey is provided, then use this header value to extract labels
for the INFO EVSF feature tag
"""
def isNucleotide(nucString):
"""
Return True if nucString is a single nucleotide, False otherwise.
"""
return (nucString in ["A", "C", "G", "T", "N"])
def variantType(ref, alt):
"""
Return 'snv' if ref and all alt alleles are single nucleotides,
otherwise return 'indel'
"""
if isNucleotide(ref) and all(isNucleotide(allele) for allele in alt.split(',')) :
return "snv"
return "indel"
def processVariant(line, keyType, header_feature_labels):
"""
Return a record with collected features for this variant
or None if the variant type does not match the key type.
"""
isHeaderKey = (header_feature_labels is not None)
word = line.strip().split('\t')
qrec = {
"CHROM": word[VCFID.CHROM],
"POS": int(word[VCFID.POS]),
"REF": word[VCFID.REF],
"ALT": word[VCFID.ALT],
}
if isHeaderKey :
if variantType(word[VCFID.REF], word[VCFID.ALT]) != keyType :
return None
for ikv in word[VCFID.INFO].split(';') :
iword = ikv.split("=",1)
if iword[0] == "EVSF" :
assert(len(iword) == 2)
features = [float(f) for f in iword[1].split(',')]
for i in range(len(features)) :
qrec[header_feature_labels[i]] = features[i]
return qrec
feature_labels = ["CHROM", "POS", "REF", "ALT"]
header_feature_labels = None
records = []
isHeader = True
isHeaderKey = (headerKey is not None)
if isHeaderKey :
if headerKey == "snv_scoring_features" :
keyType = "snv"
elif headerKey == "indel_scoring_features" :
keyType = "indel"
else :
raise Exception("Unknown header key: '%s'" % headerKey)
else :
keyType = None
for line in openMaybeGzip(vcfname):
if isHeader :
if line[0] == "#" :
if isHeaderKey and line.startswith("##") :
word = line[2:].strip().split("=")
if word[0] == headerKey :
assert(header_feature_labels is None)
header_feature_labels = word[1].split(",")
assert(len(header_feature_labels) > 0)
continue
else :
if isHeaderKey :
assert(header_feature_labels is not None)
isHeader = False
qrec = processVariant(line, keyType, header_feature_labels)
if qrec is not None:
records.append(qrec)
cols = feature_labels
if isHeaderKey :
cols += header_feature_labels
return pandas.DataFrame(records, columns=cols) | [
"def",
"collectCore",
"(",
"self",
",",
"vcfname",
",",
"headerKey",
"=",
"None",
")",
":",
"def",
"isNucleotide",
"(",
"nucString",
")",
":",
"\"\"\"\n Return True if nucString is a single nucleotide, False otherwise.\n \"\"\"",
"return",
"(",
"nucString",
"in",
"[",
"\"A\"",
",",
"\"C\"",
",",
"\"G\"",
",",
"\"T\"",
",",
"\"N\"",
"]",
")",
"def",
"variantType",
"(",
"ref",
",",
"alt",
")",
":",
"\"\"\"\n Return 'snv' if ref and all alt alleles are single nucleotides,\n otherwise return 'indel'\n \"\"\"",
"if",
"isNucleotide",
"(",
"ref",
")",
"and",
"all",
"(",
"isNucleotide",
"(",
"allele",
")",
"for",
"allele",
"in",
"alt",
".",
"split",
"(",
"','",
")",
")",
":",
"return",
"\"snv\"",
"return",
"\"indel\"",
"def",
"processVariant",
"(",
"line",
",",
"keyType",
",",
"header_feature_labels",
")",
":",
"\"\"\"\n Return a record with collected features for this variant\n or None if the variant type does not match the key type.\n \"\"\"",
"isHeaderKey",
"=",
"(",
"header_feature_labels",
"is",
"not",
"None",
")",
"word",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"qrec",
"=",
"{",
"\"CHROM\"",
":",
"word",
"[",
"VCFID",
".",
"CHROM",
"]",
",",
"\"POS\"",
":",
"int",
"(",
"word",
"[",
"VCFID",
".",
"POS",
"]",
")",
",",
"\"REF\"",
":",
"word",
"[",
"VCFID",
".",
"REF",
"]",
",",
"\"ALT\"",
":",
"word",
"[",
"VCFID",
".",
"ALT",
"]",
",",
"}",
"if",
"isHeaderKey",
":",
"if",
"variantType",
"(",
"word",
"[",
"VCFID",
".",
"REF",
"]",
",",
"word",
"[",
"VCFID",
".",
"ALT",
"]",
")",
"!=",
"keyType",
":",
"return",
"None",
"for",
"ikv",
"in",
"word",
"[",
"VCFID",
".",
"INFO",
"]",
".",
"split",
"(",
"';'",
")",
":",
"iword",
"=",
"ikv",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"if",
"iword",
"[",
"0",
"]",
"==",
"\"EVSF\"",
":",
"assert",
"(",
"len",
"(",
"iword",
")",
"==",
"2",
")",
"features",
"=",
"[",
"float",
"(",
"f",
")",
"for",
"f",
"in",
"iword",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"features",
")",
")",
":",
"qrec",
"[",
"header_feature_labels",
"[",
"i",
"]",
"]",
"=",
"features",
"[",
"i",
"]",
"return",
"qrec",
"feature_labels",
"=",
"[",
"\"CHROM\"",
",",
"\"POS\"",
",",
"\"REF\"",
",",
"\"ALT\"",
"]",
"header_feature_labels",
"=",
"None",
"records",
"=",
"[",
"]",
"isHeader",
"=",
"True",
"isHeaderKey",
"=",
"(",
"headerKey",
"is",
"not",
"None",
")",
"if",
"isHeaderKey",
":",
"if",
"headerKey",
"==",
"\"snv_scoring_features\"",
":",
"keyType",
"=",
"\"snv\"",
"elif",
"headerKey",
"==",
"\"indel_scoring_features\"",
":",
"keyType",
"=",
"\"indel\"",
"else",
":",
"raise",
"Exception",
"(",
"\"Unknown header key: '%s'\"",
"%",
"headerKey",
")",
"else",
":",
"keyType",
"=",
"None",
"for",
"line",
"in",
"openMaybeGzip",
"(",
"vcfname",
")",
":",
"if",
"isHeader",
":",
"if",
"line",
"[",
"0",
"]",
"==",
"\"#\"",
":",
"if",
"isHeaderKey",
"and",
"line",
".",
"startswith",
"(",
"\"##\"",
")",
":",
"word",
"=",
"line",
"[",
"2",
":",
"]",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"=\"",
")",
"if",
"word",
"[",
"0",
"]",
"==",
"headerKey",
":",
"assert",
"(",
"header_feature_labels",
"is",
"None",
")",
"header_feature_labels",
"=",
"word",
"[",
"1",
"]",
".",
"split",
"(",
"\",\"",
")",
"assert",
"(",
"len",
"(",
"header_feature_labels",
")",
">",
"0",
")",
"continue",
"else",
":",
"if",
"isHeaderKey",
":",
"assert",
"(",
"header_feature_labels",
"is",
"not",
"None",
")",
"isHeader",
"=",
"False",
"qrec",
"=",
"processVariant",
"(",
"line",
",",
"keyType",
",",
"header_feature_labels",
")",
"if",
"qrec",
"is",
"not",
"None",
":",
"records",
".",
"append",
"(",
"qrec",
")",
"cols",
"=",
"feature_labels",
"if",
"isHeaderKey",
":",
"cols",
"+=",
"header_feature_labels",
"return",
"pandas",
".",
"DataFrame",
"(",
"records",
",",
"columns",
"=",
"cols",
")"
] | https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/scoringModelTraining/somatic/lib/evs/features/VcfFeatureSet.py#L28-L125 | |
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | dev/archery/archery/bot.py | python | actions | (ctx) | Ursabot | Ursabot | [
"Ursabot"
] | def actions(ctx):
"""Ursabot"""
ctx.ensure_object(dict) | [
"def",
"actions",
"(",
"ctx",
")",
":",
"ctx",
".",
"ensure_object",
"(",
"dict",
")"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/bot.py#L174-L176 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/all_reduce/python/all_reduce.py | python | _strip_padding | (tensors, pad_len) | return stripped | Strip the suffix padding added by _padded_split.
Args:
tensors: list of T @{tf.Tensor} of identical length 1D tensors.
pad_len: number of elements to be stripped from the end of each tensor.
Returns:
list of T @{tf.Tensor} which are the stripped inputs.
Raises:
ValueError: tensors must be a non-empty list of 1D tensors, and
each must be longer than pad_len. | Strip the suffix padding added by _padded_split. | [
"Strip",
"the",
"suffix",
"padding",
"added",
"by",
"_padded_split",
"."
] | def _strip_padding(tensors, pad_len):
"""Strip the suffix padding added by _padded_split.
Args:
tensors: list of T @{tf.Tensor} of identical length 1D tensors.
pad_len: number of elements to be stripped from the end of each tensor.
Returns:
list of T @{tf.Tensor} which are the stripped inputs.
Raises:
ValueError: tensors must be a non-empty list of 1D tensors, and
each must be longer than pad_len.
"""
if not tensors:
raise ValueError("tensors cannot be empty")
shape = tensors[0].shape
if len(shape) > 1:
raise ValueError("tensors must be 1D")
prefix_len = int(shape[0] - pad_len)
if prefix_len < 0:
raise ValueError("pad_len longer than tensor")
stripped = []
for t in tensors:
with ops.colocate_with(t):
stripped.append(array_ops.slice(t, [0], [prefix_len]))
return stripped | [
"def",
"_strip_padding",
"(",
"tensors",
",",
"pad_len",
")",
":",
"if",
"not",
"tensors",
":",
"raise",
"ValueError",
"(",
"\"tensors cannot be empty\"",
")",
"shape",
"=",
"tensors",
"[",
"0",
"]",
".",
"shape",
"if",
"len",
"(",
"shape",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"tensors must be 1D\"",
")",
"prefix_len",
"=",
"int",
"(",
"shape",
"[",
"0",
"]",
"-",
"pad_len",
")",
"if",
"prefix_len",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"pad_len longer than tensor\"",
")",
"stripped",
"=",
"[",
"]",
"for",
"t",
"in",
"tensors",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"t",
")",
":",
"stripped",
".",
"append",
"(",
"array_ops",
".",
"slice",
"(",
"t",
",",
"[",
"0",
"]",
",",
"[",
"prefix_len",
"]",
")",
")",
"return",
"stripped"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/all_reduce/python/all_reduce.py#L131-L157 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | Pythonwin/pywin/framework/scriptutils.py | python | GetActiveEditorDocument | () | return (None, None) | Returns the active editor document and view, or (None,None) if no
active document or its not an editor document. | Returns the active editor document and view, or (None,None) if no
active document or its not an editor document. | [
"Returns",
"the",
"active",
"editor",
"document",
"and",
"view",
"or",
"(",
"None",
"None",
")",
"if",
"no",
"active",
"document",
"or",
"its",
"not",
"an",
"editor",
"document",
"."
] | def GetActiveEditorDocument():
"""Returns the active editor document and view, or (None,None) if no
active document or its not an editor document.
"""
view = GetActiveView()
if view is None or isinstance(view, TreeView):
return (None, None)
doc = view.GetDocument()
if hasattr(doc, "MarkerAdd"): # Is it an Editor document?
return doc, view
return (None, None) | [
"def",
"GetActiveEditorDocument",
"(",
")",
":",
"view",
"=",
"GetActiveView",
"(",
")",
"if",
"view",
"is",
"None",
"or",
"isinstance",
"(",
"view",
",",
"TreeView",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"doc",
"=",
"view",
".",
"GetDocument",
"(",
")",
"if",
"hasattr",
"(",
"doc",
",",
"\"MarkerAdd\"",
")",
":",
"# Is it an Editor document?",
"return",
"doc",
",",
"view",
"return",
"(",
"None",
",",
"None",
")"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/Pythonwin/pywin/framework/scriptutils.py#L158-L168 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | TreeCtrl.SetItemImage | (*args, **kwargs) | return _controls_.TreeCtrl_SetItemImage(*args, **kwargs) | SetItemImage(self, TreeItemId item, int image, int which=TreeItemIcon_Normal) | SetItemImage(self, TreeItemId item, int image, int which=TreeItemIcon_Normal) | [
"SetItemImage",
"(",
"self",
"TreeItemId",
"item",
"int",
"image",
"int",
"which",
"=",
"TreeItemIcon_Normal",
")"
] | def SetItemImage(*args, **kwargs):
"""SetItemImage(self, TreeItemId item, int image, int which=TreeItemIcon_Normal)"""
return _controls_.TreeCtrl_SetItemImage(*args, **kwargs) | [
"def",
"SetItemImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_SetItemImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5290-L5292 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/util.py | python | get_file_scheme | (paths) | return 'drill' | For the given row groups, figure out if the partitioning scheme
Parameters
----------
paths: list of str
normally from row_group.columns[0].file_path
Returns
-------
'empty': no rgs at all
'simple': all rgs in a single file
'flat': multiple files in one directory
'hive': directories are all `key=value`; all files are at the same
directory depth
'drill': assume directory names are labels, and field names are of the
form dir0, dir1; all files are at the same directory depth
'other': none of the above, assume no partitioning | For the given row groups, figure out if the partitioning scheme | [
"For",
"the",
"given",
"row",
"groups",
"figure",
"out",
"if",
"the",
"partitioning",
"scheme"
] | def get_file_scheme(paths):
"""For the given row groups, figure out if the partitioning scheme
Parameters
----------
paths: list of str
normally from row_group.columns[0].file_path
Returns
-------
'empty': no rgs at all
'simple': all rgs in a single file
'flat': multiple files in one directory
'hive': directories are all `key=value`; all files are at the same
directory depth
'drill': assume directory names are labels, and field names are of the
form dir0, dir1; all files are at the same directory depth
'other': none of the above, assume no partitioning
"""
if not paths:
return 'empty'
if set(paths) == {None}:
return 'simple'
if None in paths:
return 'other'
parts = [p.split('/') for p in paths]
lens = [len(p) for p in parts]
if len(set(lens)) > 1:
return 'other'
if set(lens) == {1}:
return 'flat'
s = ex_from_sep('/')
dirs = [p.rsplit('/', 1)[0] for p in paths]
matches = [s.findall(d) for d in dirs]
if all(len(m) == (l - 1) for (m, l) in
zip(matches, lens)):
keys = (tuple(m[0] for m in parts) for parts in matches)
if len(set(keys)) == 1:
return 'hive'
return 'drill' | [
"def",
"get_file_scheme",
"(",
"paths",
")",
":",
"if",
"not",
"paths",
":",
"return",
"'empty'",
"if",
"set",
"(",
"paths",
")",
"==",
"{",
"None",
"}",
":",
"return",
"'simple'",
"if",
"None",
"in",
"paths",
":",
"return",
"'other'",
"parts",
"=",
"[",
"p",
".",
"split",
"(",
"'/'",
")",
"for",
"p",
"in",
"paths",
"]",
"lens",
"=",
"[",
"len",
"(",
"p",
")",
"for",
"p",
"in",
"parts",
"]",
"if",
"len",
"(",
"set",
"(",
"lens",
")",
")",
">",
"1",
":",
"return",
"'other'",
"if",
"set",
"(",
"lens",
")",
"==",
"{",
"1",
"}",
":",
"return",
"'flat'",
"s",
"=",
"ex_from_sep",
"(",
"'/'",
")",
"dirs",
"=",
"[",
"p",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"0",
"]",
"for",
"p",
"in",
"paths",
"]",
"matches",
"=",
"[",
"s",
".",
"findall",
"(",
"d",
")",
"for",
"d",
"in",
"dirs",
"]",
"if",
"all",
"(",
"len",
"(",
"m",
")",
"==",
"(",
"l",
"-",
"1",
")",
"for",
"(",
"m",
",",
"l",
")",
"in",
"zip",
"(",
"matches",
",",
"lens",
")",
")",
":",
"keys",
"=",
"(",
"tuple",
"(",
"m",
"[",
"0",
"]",
"for",
"m",
"in",
"parts",
")",
"for",
"parts",
"in",
"matches",
")",
"if",
"len",
"(",
"set",
"(",
"keys",
")",
")",
"==",
"1",
":",
"return",
"'hive'",
"return",
"'drill'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/util.py#L273-L312 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/gzip.py | python | GzipFile._check_closed | (self) | Raises a ValueError if the underlying file object has been closed. | Raises a ValueError if the underlying file object has been closed. | [
"Raises",
"a",
"ValueError",
"if",
"the",
"underlying",
"file",
"object",
"has",
"been",
"closed",
"."
] | def _check_closed(self):
"""Raises a ValueError if the underlying file object has been closed.
"""
if self.closed:
raise ValueError('I/O operation on closed file.') | [
"def",
"_check_closed",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"'I/O operation on closed file.'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/gzip.py#L150-L155 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | PyTextDataObject.__init__ | (self, *args, **kwargs) | __init__(self, String text=EmptyString) -> PyTextDataObject
wx.PyTextDataObject is a version of `wx.TextDataObject` that is
Python-aware and knows how to reflect calls to its C++ virtual methods
to methods in the Python derived class. You should derive from this
class and overload `GetTextLength`, `GetText`, and `SetText` when you
want to be able to provide text on demand instead of preloading it
into the data object. | __init__(self, String text=EmptyString) -> PyTextDataObject | [
"__init__",
"(",
"self",
"String",
"text",
"=",
"EmptyString",
")",
"-",
">",
"PyTextDataObject"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, String text=EmptyString) -> PyTextDataObject
wx.PyTextDataObject is a version of `wx.TextDataObject` that is
Python-aware and knows how to reflect calls to its C++ virtual methods
to methods in the Python derived class. You should derive from this
class and overload `GetTextLength`, `GetText`, and `SetText` when you
want to be able to provide text on demand instead of preloading it
into the data object.
"""
_misc_.PyTextDataObject_swiginit(self,_misc_.new_PyTextDataObject(*args, **kwargs))
PyTextDataObject._setCallbackInfo(self, self, PyTextDataObject) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"PyTextDataObject_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_PyTextDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"PyTextDataObject",
".",
"_setCallbackInfo",
"(",
"self",
",",
"self",
",",
"PyTextDataObject",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L5236-L5248 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/monitors.py | python | EveryN.step_end | (self, step, output) | return False | Overrides `BaseMonitor.step_end`.
When overriding this method, you must call the super implementation.
Args:
step: `int`, the current value of the global step.
output: `dict` mapping `string` values representing tensor names to
the value resulted from running these tensors. Values may be either
scalars, for scalar tensors, or Numpy `array`, for non-scalar tensors.
Returns:
`bool`, the result of every_n_step_end, if that was called this step,
or `False` otherwise. | Overrides `BaseMonitor.step_end`. | [
"Overrides",
"BaseMonitor",
".",
"step_end",
"."
] | def step_end(self, step, output):
"""Overrides `BaseMonitor.step_end`.
When overriding this method, you must call the super implementation.
Args:
step: `int`, the current value of the global step.
output: `dict` mapping `string` values representing tensor names to
the value resulted from running these tensors. Values may be either
scalars, for scalar tensors, or Numpy `array`, for non-scalar tensors.
Returns:
`bool`, the result of every_n_step_end, if that was called this step,
or `False` otherwise.
"""
super(EveryN, self).step_end(step, output)
if self._every_n_step_begin_called:
return self.every_n_step_end(step, output)
return False | [
"def",
"step_end",
"(",
"self",
",",
"step",
",",
"output",
")",
":",
"super",
"(",
"EveryN",
",",
"self",
")",
".",
"step_end",
"(",
"step",
",",
"output",
")",
"if",
"self",
".",
"_every_n_step_begin_called",
":",
"return",
"self",
".",
"every_n_step_end",
"(",
"step",
",",
"output",
")",
"return",
"False"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/monitors.py#L342-L359 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/classifier/svm_classifier.py | python | SVMClassifier._get | (self, field) | return super(_Classifier, self)._get(field) | Return the value of a given field. The list of all queryable fields is
detailed below, and can be obtained programmatically with the
:func:`~turicreate.svm.SVMClassifier._list_fields` method.
+------------------------+-------------------------------------------------------------+
| Field | Description |
+========================+=============================================================+
| coefficients | Classifier coefficients |
+------------------------+-------------------------------------------------------------+
| convergence_threshold | Desired solver accuracy |
+------------------------+-------------------------------------------------------------+
| feature_rescaling | Bool indicating l2-rescaling of features |
+------------------------+---------+---------------------------------------------------+
| features | Feature column names |
+------------------------+-------------------------------------------------------------+
| lbfgs_memory_level | Number of updates to store (lbfgs only) |
+------------------------+-------------------------------------------------------------+
| max_iterations | Maximum number of solver iterations |
+------------------------+-------------------------------------------------------------+
| num_coefficients | Number of coefficients in the model |
+------------------------+-------------------------------------------------------------+
| num_examples | Number of examples used for training |
+------------------------+-------------------------------------------------------------+
| num_features | Number of dataset columns used for training |
+------------------------+-------------------------------------------------------------+
| num_unpacked_features | Number of features (including expanded list/dict features) |
+------------------------+-------------------------------------------------------------+
| penalty | Misclassification penalty term |
+------------------------+-------------------------------------------------------------+
| solver | Type of solver |
+------------------------+-------------------------------------------------------------+
| target | Target column name |
+------------------------+-------------------------------------------------------------+
| training_iterations | Number of solver iterations |
+------------------------+-------------------------------------------------------------+
| training_loss | Maximized Log-likelihood |
+------------------------+-------------------------------------------------------------+
| training_solver_status | Solver status after training |
+------------------------+-------------------------------------------------------------+
| training_time | Training time (excludes preprocessing) |
+------------------------+-------------------------------------------------------------+
| unpacked_features | Feature names (including expanded list/dict features) |
+------------------------+-------------------------------------------------------------+
Parameters
----------
field : string
Name of the field to be retrieved.
Returns
-------
out
Value of the requested fields. | Return the value of a given field. The list of all queryable fields is
detailed below, and can be obtained programmatically with the
:func:`~turicreate.svm.SVMClassifier._list_fields` method. | [
"Return",
"the",
"value",
"of",
"a",
"given",
"field",
".",
"The",
"list",
"of",
"all",
"queryable",
"fields",
"is",
"detailed",
"below",
"and",
"can",
"be",
"obtained",
"programmatically",
"with",
"the",
":",
"func",
":",
"~turicreate",
".",
"svm",
".",
"SVMClassifier",
".",
"_list_fields",
"method",
"."
] | def _get(self, field):
"""
Return the value of a given field. The list of all queryable fields is
detailed below, and can be obtained programmatically with the
:func:`~turicreate.svm.SVMClassifier._list_fields` method.
+------------------------+-------------------------------------------------------------+
| Field | Description |
+========================+=============================================================+
| coefficients | Classifier coefficients |
+------------------------+-------------------------------------------------------------+
| convergence_threshold | Desired solver accuracy |
+------------------------+-------------------------------------------------------------+
| feature_rescaling | Bool indicating l2-rescaling of features |
+------------------------+---------+---------------------------------------------------+
| features | Feature column names |
+------------------------+-------------------------------------------------------------+
| lbfgs_memory_level | Number of updates to store (lbfgs only) |
+------------------------+-------------------------------------------------------------+
| max_iterations | Maximum number of solver iterations |
+------------------------+-------------------------------------------------------------+
| num_coefficients | Number of coefficients in the model |
+------------------------+-------------------------------------------------------------+
| num_examples | Number of examples used for training |
+------------------------+-------------------------------------------------------------+
| num_features | Number of dataset columns used for training |
+------------------------+-------------------------------------------------------------+
| num_unpacked_features | Number of features (including expanded list/dict features) |
+------------------------+-------------------------------------------------------------+
| penalty | Misclassification penalty term |
+------------------------+-------------------------------------------------------------+
| solver | Type of solver |
+------------------------+-------------------------------------------------------------+
| target | Target column name |
+------------------------+-------------------------------------------------------------+
| training_iterations | Number of solver iterations |
+------------------------+-------------------------------------------------------------+
| training_loss | Maximized Log-likelihood |
+------------------------+-------------------------------------------------------------+
| training_solver_status | Solver status after training |
+------------------------+-------------------------------------------------------------+
| training_time | Training time (excludes preprocessing) |
+------------------------+-------------------------------------------------------------+
| unpacked_features | Feature names (including expanded list/dict features) |
+------------------------+-------------------------------------------------------------+
Parameters
----------
field : string
Name of the field to be retrieved.
Returns
-------
out
Value of the requested fields.
"""
return super(_Classifier, self)._get(field) | [
"def",
"_get",
"(",
"self",
",",
"field",
")",
":",
"return",
"super",
"(",
"_Classifier",
",",
"self",
")",
".",
"_get",
"(",
"field",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/classifier/svm_classifier.py#L412-L469 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/escape.py | python | recursive_unicode | (obj: Any) | Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries. | Walks a simple data structure, converting byte strings to unicode. | [
"Walks",
"a",
"simple",
"data",
"structure",
"converting",
"byte",
"strings",
"to",
"unicode",
"."
] | def recursive_unicode(obj: Any) -> Any:
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict(
(recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()
)
elif isinstance(obj, list):
return list(recursive_unicode(i) for i in obj)
elif isinstance(obj, tuple):
return tuple(recursive_unicode(i) for i in obj)
elif isinstance(obj, bytes):
return to_unicode(obj)
else:
return obj | [
"def",
"recursive_unicode",
"(",
"obj",
":",
"Any",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"recursive_unicode",
"(",
"k",
")",
",",
"recursive_unicode",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"obj",
".",
"items",
"(",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"list",
"(",
"recursive_unicode",
"(",
"i",
")",
"for",
"i",
"in",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"return",
"tuple",
"(",
"recursive_unicode",
"(",
"i",
")",
"for",
"i",
"in",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
":",
"return",
"to_unicode",
"(",
"obj",
")",
"else",
":",
"return",
"obj"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/escape.py#L242-L258 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/plotting/markers.py | python | VerticalMarker.set_position | (self, x) | Set the x position of the marker.
:param x: An x axis coordinate. | Set the x position of the marker.
:param x: An x axis coordinate. | [
"Set",
"the",
"x",
"position",
"of",
"the",
"marker",
".",
":",
"param",
"x",
":",
"An",
"x",
"axis",
"coordinate",
"."
] | def set_position(self, x):
"""
Set the x position of the marker.
:param x: An x axis coordinate.
"""
self.x = x
self.x_moved.emit(x) | [
"def",
"set_position",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"x",
"=",
"x",
"self",
".",
"x_moved",
".",
"emit",
"(",
"x",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/plotting/markers.py#L300-L306 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | _PartialFile.__init__ | (self, f, start=None, stop=None) | Initialize a _PartialFile. | Initialize a _PartialFile. | [
"Initialize",
"a",
"_PartialFile",
"."
] | def __init__(self, f, start=None, stop=None):
"""Initialize a _PartialFile."""
_ProxyFile.__init__(self, f, start)
self._start = start
self._stop = stop | [
"def",
"__init__",
"(",
"self",
",",
"f",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"_ProxyFile",
".",
"__init__",
"(",
"self",
",",
"f",
",",
"start",
")",
"self",
".",
"_start",
"=",
"start",
"self",
".",
"_stop",
"=",
"stop"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L2027-L2031 | ||
ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | LeetCode/python3/695.py | python | Solution.maxAreaOfIsland | (self, grid) | return maxArea | :type grid: List[List[int]]
:rtype: int | :type grid: List[List[int]]
:rtype: int | [
":",
"type",
"grid",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"int"
] | def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
dir_x = [0, 0, 1, -1]
dir_y = [-1, 1, 0, 0]
def helper(i, j):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[i]) or (i, j) in visited or grid[i][j] == 0:
return 0
visited.add((i, j))
area = 1
for k in range(4):
x, y = i + dir_x[k], j + dir_y[k]
area += helper(x, y)
return area
visited = set()
maxArea = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1 and (i,j) not in visited:
maxArea = max(maxArea, helper(i, j))
return maxArea | [
"def",
"maxAreaOfIsland",
"(",
"self",
",",
"grid",
")",
":",
"dir_x",
"=",
"[",
"0",
",",
"0",
",",
"1",
",",
"-",
"1",
"]",
"dir_y",
"=",
"[",
"-",
"1",
",",
"1",
",",
"0",
",",
"0",
"]",
"def",
"helper",
"(",
"i",
",",
"j",
")",
":",
"if",
"i",
"<",
"0",
"or",
"i",
">=",
"len",
"(",
"grid",
")",
"or",
"j",
"<",
"0",
"or",
"j",
">=",
"len",
"(",
"grid",
"[",
"i",
"]",
")",
"or",
"(",
"i",
",",
"j",
")",
"in",
"visited",
"or",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"0",
":",
"return",
"0",
"visited",
".",
"add",
"(",
"(",
"i",
",",
"j",
")",
")",
"area",
"=",
"1",
"for",
"k",
"in",
"range",
"(",
"4",
")",
":",
"x",
",",
"y",
"=",
"i",
"+",
"dir_x",
"[",
"k",
"]",
",",
"j",
"+",
"dir_y",
"[",
"k",
"]",
"area",
"+=",
"helper",
"(",
"x",
",",
"y",
")",
"return",
"area",
"visited",
"=",
"set",
"(",
")",
"maxArea",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"grid",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"grid",
"[",
"i",
"]",
")",
")",
":",
"if",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"1",
"and",
"(",
"i",
",",
"j",
")",
"not",
"in",
"visited",
":",
"maxArea",
"=",
"max",
"(",
"maxArea",
",",
"helper",
"(",
"i",
",",
"j",
")",
")",
"return",
"maxArea"
] | https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python3/695.py#L2-L26 | |
liulei01/DRBox | b5c76e033c555c9009590ab384e1f7bd3c66c237 | scripts/cpp_lint.py | python | _IsTestFilename | (filename) | Determines if the given filename has a suffix that identifies it as a test.
Args:
filename: The input filename.
Returns:
True if 'filename' looks like a test, False otherwise. | Determines if the given filename has a suffix that identifies it as a test. | [
"Determines",
"if",
"the",
"given",
"filename",
"has",
"a",
"suffix",
"that",
"identifies",
"it",
"as",
"a",
"test",
"."
] | def _IsTestFilename(filename):
"""Determines if the given filename has a suffix that identifies it as a test.
Args:
filename: The input filename.
Returns:
True if 'filename' looks like a test, False otherwise.
"""
if (filename.endswith('_test.cc') or
filename.endswith('_unittest.cc') or
filename.endswith('_regtest.cc')):
return True
else:
return False | [
"def",
"_IsTestFilename",
"(",
"filename",
")",
":",
"if",
"(",
"filename",
".",
"endswith",
"(",
"'_test.cc'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'_unittest.cc'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'_regtest.cc'",
")",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/scripts/cpp_lint.py#L3607-L3621 | ||
cksystemsgroup/scalloc | 049857919b5fa1d539c9e4206e353daca2e87394 | tools/cpplint.py | python | _NestingState.CheckCompletedBlocks | (self, filename, error) | Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found. | Checks that all classes and namespaces have been completely parsed. | [
"Checks",
"that",
"all",
"classes",
"and",
"namespaces",
"have",
"been",
"completely",
"parsed",
"."
] | def CheckCompletedBlocks(self, filename, error):
"""Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
elif isinstance(obj, _NamespaceInfo):
error(filename, obj.starting_linenum, 'build/namespaces', 5,
'Failed to find complete declaration of namespace %s' %
obj.name) | [
"def",
"CheckCompletedBlocks",
"(",
"self",
",",
"filename",
",",
"error",
")",
":",
"# Note: This test can result in false positives if #ifdef constructs",
"# get in the way of brace matching. See the testBuildClass test in",
"# cpplint_unittest.py for an example of this.",
"for",
"obj",
"in",
"self",
".",
"stack",
":",
"if",
"isinstance",
"(",
"obj",
",",
"_ClassInfo",
")",
":",
"error",
"(",
"filename",
",",
"obj",
".",
"starting_linenum",
",",
"'build/class'",
",",
"5",
",",
"'Failed to find complete declaration of class %s'",
"%",
"obj",
".",
"name",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"_NamespaceInfo",
")",
":",
"error",
"(",
"filename",
",",
"obj",
".",
"starting_linenum",
",",
"'build/namespaces'",
",",
"5",
",",
"'Failed to find complete declaration of namespace %s'",
"%",
"obj",
".",
"name",
")"
] | https://github.com/cksystemsgroup/scalloc/blob/049857919b5fa1d539c9e4206e353daca2e87394/tools/cpplint.py#L2060-L2079 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/layers/python/layers/layers.py | python | convolution3d_transpose | (
inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=DATA_FORMAT_NDHWC,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None) | Adds a convolution3d_transpose with an optional batch normalization layer.
The function creates a variable called `weights`, representing the
kernel, that is convolved with the input. If `batch_norm_params` is `None`, a
second variable called 'biases' is added to the result of the operation.
Args:
inputs: A 5-D `Tensor` of type `float` and shape
`[batch, depth, height, width, in_channels]` for `NDHWC` data format or
`[batch, in_channels, depth, height, width]` for `NCDHW` data format.
num_outputs: Integer, the number of output filters.
kernel_size: A list of length 3 holding the [kernel_depth, kernel_height,
kernel_width] of the filters. Can be an int if both values are the same.
stride: A list of length 3: [stride_depth, stride_height, stride_width].
Can be an int if both strides are the same. Note that presently
both strides must have the same value.
padding: One of 'VALID' or 'SAME'.
data_format: A string. `NDHWC` (default) and `NCDHW` are supported.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collection per variable.
outputs_collections: Collection to add the outputs.
trainable: Whether or not the variables should be trainable or not.
scope: Optional scope for variable_scope.
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If 'kernel_size' is not a list of length 3.
ValueError: If `data_format` is neither `NDHWC` nor `NCDHW`.
ValueError: If `C` dimension of `inputs` is None. | Adds a convolution3d_transpose with an optional batch normalization layer. | [
"Adds",
"a",
"convolution3d_transpose",
"with",
"an",
"optional",
"batch",
"normalization",
"layer",
"."
] | def convolution3d_transpose(
inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=DATA_FORMAT_NDHWC,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
"""Adds a convolution3d_transpose with an optional batch normalization layer.
The function creates a variable called `weights`, representing the
kernel, that is convolved with the input. If `batch_norm_params` is `None`, a
second variable called 'biases' is added to the result of the operation.
Args:
inputs: A 5-D `Tensor` of type `float` and shape
`[batch, depth, height, width, in_channels]` for `NDHWC` data format or
`[batch, in_channels, depth, height, width]` for `NCDHW` data format.
num_outputs: Integer, the number of output filters.
kernel_size: A list of length 3 holding the [kernel_depth, kernel_height,
kernel_width] of the filters. Can be an int if both values are the same.
stride: A list of length 3: [stride_depth, stride_height, stride_width].
Can be an int if both strides are the same. Note that presently
both strides must have the same value.
padding: One of 'VALID' or 'SAME'.
data_format: A string. `NDHWC` (default) and `NCDHW` are supported.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collection per variable.
outputs_collections: Collection to add the outputs.
trainable: Whether or not the variables should be trainable or not.
scope: Optional scope for variable_scope.
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If 'kernel_size' is not a list of length 3.
ValueError: If `data_format` is neither `NDHWC` nor `NCDHW`.
ValueError: If `C` dimension of `inputs` is None.
"""
layer_variable_getter = _build_variable_getter(
{'bias': 'biases', 'kernel': 'weights'})
with variable_scope.variable_scope(
scope, 'Conv3d_transpose', [inputs], reuse=reuse,
custom_getter=layer_variable_getter) as sc:
if data_format not in (DATA_FORMAT_NCDHW, DATA_FORMAT_NDHWC):
raise ValueError('data_format has to be either NCDHW or NDHWC.')
inputs = ops.convert_to_tensor(inputs)
df = ('channels_first' if data_format and data_format.startswith('NC')
else 'channels_last')
layer = convolutional_layers.Convolution3DTranspose(
filters=num_outputs,
kernel_size=kernel_size,
strides=stride,
padding=padding,
data_format=df,
activation=None,
use_bias=not normalizer_fn and biases_initializer,
kernel_initializer=weights_initializer,
bias_initializer=biases_initializer,
kernel_regularizer=weights_regularizer,
bias_regularizer=biases_regularizer,
activity_regularizer=None,
trainable=trainable,
name=sc.name,
dtype=inputs.dtype.base_dtype,
_scope=sc,
_reuse=reuse)
outputs = layer.apply(inputs)
# Add variables to collections.
_add_variable_to_collections(layer.kernel, variables_collections, 'weights')
if layer.bias:
_add_variable_to_collections(layer.bias, variables_collections, 'biases')
if normalizer_fn is not None:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections, sc.name, outputs) | [
"def",
"convolution3d_transpose",
"(",
"inputs",
",",
"num_outputs",
",",
"kernel_size",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
",",
"data_format",
"=",
"DATA_FORMAT_NDHWC",
",",
"activation_fn",
"=",
"nn",
".",
"relu",
",",
"normalizer_fn",
"=",
"None",
",",
"normalizer_params",
"=",
"None",
",",
"weights_initializer",
"=",
"initializers",
".",
"xavier_initializer",
"(",
")",
",",
"weights_regularizer",
"=",
"None",
",",
"biases_initializer",
"=",
"init_ops",
".",
"zeros_initializer",
"(",
")",
",",
"biases_regularizer",
"=",
"None",
",",
"reuse",
"=",
"None",
",",
"variables_collections",
"=",
"None",
",",
"outputs_collections",
"=",
"None",
",",
"trainable",
"=",
"True",
",",
"scope",
"=",
"None",
")",
":",
"layer_variable_getter",
"=",
"_build_variable_getter",
"(",
"{",
"'bias'",
":",
"'biases'",
",",
"'kernel'",
":",
"'weights'",
"}",
")",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"scope",
",",
"'Conv3d_transpose'",
",",
"[",
"inputs",
"]",
",",
"reuse",
"=",
"reuse",
",",
"custom_getter",
"=",
"layer_variable_getter",
")",
"as",
"sc",
":",
"if",
"data_format",
"not",
"in",
"(",
"DATA_FORMAT_NCDHW",
",",
"DATA_FORMAT_NDHWC",
")",
":",
"raise",
"ValueError",
"(",
"'data_format has to be either NCDHW or NDHWC.'",
")",
"inputs",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"inputs",
")",
"df",
"=",
"(",
"'channels_first'",
"if",
"data_format",
"and",
"data_format",
".",
"startswith",
"(",
"'NC'",
")",
"else",
"'channels_last'",
")",
"layer",
"=",
"convolutional_layers",
".",
"Convolution3DTranspose",
"(",
"filters",
"=",
"num_outputs",
",",
"kernel_size",
"=",
"kernel_size",
",",
"strides",
"=",
"stride",
",",
"padding",
"=",
"padding",
",",
"data_format",
"=",
"df",
",",
"activation",
"=",
"None",
",",
"use_bias",
"=",
"not",
"normalizer_fn",
"and",
"biases_initializer",
",",
"kernel_initializer",
"=",
"weights_initializer",
",",
"bias_initializer",
"=",
"biases_initializer",
",",
"kernel_regularizer",
"=",
"weights_regularizer",
",",
"bias_regularizer",
"=",
"biases_regularizer",
",",
"activity_regularizer",
"=",
"None",
",",
"trainable",
"=",
"trainable",
",",
"name",
"=",
"sc",
".",
"name",
",",
"dtype",
"=",
"inputs",
".",
"dtype",
".",
"base_dtype",
",",
"_scope",
"=",
"sc",
",",
"_reuse",
"=",
"reuse",
")",
"outputs",
"=",
"layer",
".",
"apply",
"(",
"inputs",
")",
"# Add variables to collections.",
"_add_variable_to_collections",
"(",
"layer",
".",
"kernel",
",",
"variables_collections",
",",
"'weights'",
")",
"if",
"layer",
".",
"bias",
":",
"_add_variable_to_collections",
"(",
"layer",
".",
"bias",
",",
"variables_collections",
",",
"'biases'",
")",
"if",
"normalizer_fn",
"is",
"not",
"None",
":",
"normalizer_params",
"=",
"normalizer_params",
"or",
"{",
"}",
"outputs",
"=",
"normalizer_fn",
"(",
"outputs",
",",
"*",
"*",
"normalizer_params",
")",
"if",
"activation_fn",
"is",
"not",
"None",
":",
"outputs",
"=",
"activation_fn",
"(",
"outputs",
")",
"return",
"utils",
".",
"collect_named_outputs",
"(",
"outputs_collections",
",",
"sc",
".",
"name",
",",
"outputs",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/layers.py#L1283-L1388 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py | python | MIMEPart.iter_attachments | (self) | Return an iterator over the non-main parts of a multipart.
Skip the first of each occurrence of text/plain, text/html,
multipart/related, or multipart/alternative in the multipart (unless
they have a 'Content-Disposition: attachment' header) and include all
remaining subparts in the returned iterator. When applied to a
multipart/related, return all parts except the root part. Return an
empty iterator when applied to a multipart/alternative or a
non-multipart. | Return an iterator over the non-main parts of a multipart. | [
"Return",
"an",
"iterator",
"over",
"the",
"non",
"-",
"main",
"parts",
"of",
"a",
"multipart",
"."
] | def iter_attachments(self):
"""Return an iterator over the non-main parts of a multipart.
Skip the first of each occurrence of text/plain, text/html,
multipart/related, or multipart/alternative in the multipart (unless
they have a 'Content-Disposition: attachment' header) and include all
remaining subparts in the returned iterator. When applied to a
multipart/related, return all parts except the root part. Return an
empty iterator when applied to a multipart/alternative or a
non-multipart.
"""
maintype, subtype = self.get_content_type().split('/')
if maintype != 'multipart' or subtype == 'alternative':
return
payload = self.get_payload()
# Certain malformed messages can have content type set to `multipart/*`
# but still have single part body, in which case payload.copy() can
# fail with AttributeError.
try:
parts = payload.copy()
except AttributeError:
# payload is not a list, it is most probably a string.
return
if maintype == 'multipart' and subtype == 'related':
# For related, we treat everything but the root as an attachment.
# The root may be indicated by 'start'; if there's no start or we
# can't find the named start, treat the first subpart as the root.
start = self.get_param('start')
if start:
found = False
attachments = []
for part in parts:
if part.get('content-id') == start:
found = True
else:
attachments.append(part)
if found:
yield from attachments
return
parts.pop(0)
yield from parts
return
# Otherwise we more or less invert the remaining logic in get_body.
# This only really works in edge cases (ex: non-text related or
# alternatives) if the sending agent sets content-disposition.
seen = [] # Only skip the first example of each candidate type.
for part in parts:
maintype, subtype = part.get_content_type().split('/')
if ((maintype, subtype) in self._body_types and
not part.is_attachment() and subtype not in seen):
seen.append(subtype)
continue
yield part | [
"def",
"iter_attachments",
"(",
"self",
")",
":",
"maintype",
",",
"subtype",
"=",
"self",
".",
"get_content_type",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"maintype",
"!=",
"'multipart'",
"or",
"subtype",
"==",
"'alternative'",
":",
"return",
"payload",
"=",
"self",
".",
"get_payload",
"(",
")",
"# Certain malformed messages can have content type set to `multipart/*`",
"# but still have single part body, in which case payload.copy() can",
"# fail with AttributeError.",
"try",
":",
"parts",
"=",
"payload",
".",
"copy",
"(",
")",
"except",
"AttributeError",
":",
"# payload is not a list, it is most probably a string.",
"return",
"if",
"maintype",
"==",
"'multipart'",
"and",
"subtype",
"==",
"'related'",
":",
"# For related, we treat everything but the root as an attachment.",
"# The root may be indicated by 'start'; if there's no start or we",
"# can't find the named start, treat the first subpart as the root.",
"start",
"=",
"self",
".",
"get_param",
"(",
"'start'",
")",
"if",
"start",
":",
"found",
"=",
"False",
"attachments",
"=",
"[",
"]",
"for",
"part",
"in",
"parts",
":",
"if",
"part",
".",
"get",
"(",
"'content-id'",
")",
"==",
"start",
":",
"found",
"=",
"True",
"else",
":",
"attachments",
".",
"append",
"(",
"part",
")",
"if",
"found",
":",
"yield",
"from",
"attachments",
"return",
"parts",
".",
"pop",
"(",
"0",
")",
"yield",
"from",
"parts",
"return",
"# Otherwise we more or less invert the remaining logic in get_body.",
"# This only really works in edge cases (ex: non-text related or",
"# alternatives) if the sending agent sets content-disposition.",
"seen",
"=",
"[",
"]",
"# Only skip the first example of each candidate type.",
"for",
"part",
"in",
"parts",
":",
"maintype",
",",
"subtype",
"=",
"part",
".",
"get_content_type",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"(",
"(",
"maintype",
",",
"subtype",
")",
"in",
"self",
".",
"_body_types",
"and",
"not",
"part",
".",
"is_attachment",
"(",
")",
"and",
"subtype",
"not",
"in",
"seen",
")",
":",
"seen",
".",
"append",
"(",
"subtype",
")",
"continue",
"yield",
"part"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py#L1030-L1083 | ||
casadi/casadi | 8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff | misc/cpplint.py | python | ParseArguments | (args) | return filenames | Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | Parses the command line arguments. | [
"Parses",
"the",
"command",
"line",
"arguments",
"."
] | def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma seperated list.')
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames | [
"def",
"ParseArguments",
"(",
"args",
")",
":",
"try",
":",
"(",
"opts",
",",
"filenames",
")",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"''",
",",
"[",
"'help'",
",",
"'output='",
",",
"'verbose='",
",",
"'counting='",
",",
"'filter='",
",",
"'root='",
",",
"'linelength='",
",",
"'extensions='",
"]",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"PrintUsage",
"(",
"'Invalid arguments.'",
")",
"verbosity",
"=",
"_VerboseLevel",
"(",
")",
"output_format",
"=",
"_OutputFormat",
"(",
")",
"filters",
"=",
"''",
"counting_style",
"=",
"''",
"for",
"(",
"opt",
",",
"val",
")",
"in",
"opts",
":",
"if",
"opt",
"==",
"'--help'",
":",
"PrintUsage",
"(",
"None",
")",
"elif",
"opt",
"==",
"'--output'",
":",
"if",
"val",
"not",
"in",
"(",
"'emacs'",
",",
"'vs7'",
",",
"'eclipse'",
")",
":",
"PrintUsage",
"(",
"'The only allowed output formats are emacs, vs7 and eclipse.'",
")",
"output_format",
"=",
"val",
"elif",
"opt",
"==",
"'--verbose'",
":",
"verbosity",
"=",
"int",
"(",
"val",
")",
"elif",
"opt",
"==",
"'--filter'",
":",
"filters",
"=",
"val",
"if",
"not",
"filters",
":",
"PrintCategories",
"(",
")",
"elif",
"opt",
"==",
"'--counting'",
":",
"if",
"val",
"not",
"in",
"(",
"'total'",
",",
"'toplevel'",
",",
"'detailed'",
")",
":",
"PrintUsage",
"(",
"'Valid counting options are total, toplevel, and detailed'",
")",
"counting_style",
"=",
"val",
"elif",
"opt",
"==",
"'--root'",
":",
"global",
"_root",
"_root",
"=",
"val",
"elif",
"opt",
"==",
"'--linelength'",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Line length must be digits.'",
")",
"elif",
"opt",
"==",
"'--extensions'",
":",
"global",
"_valid_extensions",
"try",
":",
"_valid_extensions",
"=",
"set",
"(",
"val",
".",
"split",
"(",
"','",
")",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Extensions must be comma seperated list.'",
")",
"if",
"not",
"filenames",
":",
"PrintUsage",
"(",
"'No files were specified.'",
")",
"_SetOutputFormat",
"(",
"output_format",
")",
"_SetVerboseLevel",
"(",
"verbosity",
")",
"_SetFilters",
"(",
"filters",
")",
"_SetCountingStyle",
"(",
"counting_style",
")",
"return",
"filenames"
] | https://github.com/casadi/casadi/blob/8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff/misc/cpplint.py#L4661-L4728 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_vendor/packaging/tags.py | python | interpreter_name | () | return INTERPRETER_SHORT_NAMES.get(name) or name | Returns the name of the running interpreter. | Returns the name of the running interpreter. | [
"Returns",
"the",
"name",
"of",
"the",
"running",
"interpreter",
"."
] | def interpreter_name() -> str:
"""
Returns the name of the running interpreter.
"""
name = sys.implementation.name
return INTERPRETER_SHORT_NAMES.get(name) or name | [
"def",
"interpreter_name",
"(",
")",
"->",
"str",
":",
"name",
"=",
"sys",
".",
"implementation",
".",
"name",
"return",
"INTERPRETER_SHORT_NAMES",
".",
"get",
"(",
"name",
")",
"or",
"name"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/packaging/tags.py#L446-L451 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/asyncio/selector_events.py | python | BaseSelectorEventLoop.remove_reader | (self, fd) | return self._remove_reader(fd) | Remove a reader callback. | Remove a reader callback. | [
"Remove",
"a",
"reader",
"callback",
"."
] | def remove_reader(self, fd):
"""Remove a reader callback."""
self._ensure_fd_no_transport(fd)
return self._remove_reader(fd) | [
"def",
"remove_reader",
"(",
"self",
",",
"fd",
")",
":",
"self",
".",
"_ensure_fd_no_transport",
"(",
"fd",
")",
"return",
"self",
".",
"_remove_reader",
"(",
"fd",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/selector_events.py#L331-L334 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html2.py | python | WebView.CanPaste | (*args, **kwargs) | return _html2.WebView_CanPaste(*args, **kwargs) | CanPaste(self) -> bool | CanPaste(self) -> bool | [
"CanPaste",
"(",
"self",
")",
"-",
">",
"bool"
] | def CanPaste(*args, **kwargs):
"""CanPaste(self) -> bool"""
return _html2.WebView_CanPaste(*args, **kwargs) | [
"def",
"CanPaste",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html2",
".",
"WebView_CanPaste",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html2.py#L222-L224 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/npyio.py | python | mafromtxt | (fname, **kwargs) | return genfromtxt(fname, **kwargs) | Load ASCII data stored in a text file and return a masked array.
.. deprecated:: 1.17
np.mafromtxt is a deprecated alias of `genfromtxt` which
overwrites the ``usemask`` argument with `True` even when
explicitly called as ``mafromtxt(..., usemask=False)``.
Use `genfromtxt` instead.
Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.
See Also
--------
numpy.genfromtxt : generic function to load ASCII data. | Load ASCII data stored in a text file and return a masked array. | [
"Load",
"ASCII",
"data",
"stored",
"in",
"a",
"text",
"file",
"and",
"return",
"a",
"masked",
"array",
"."
] | def mafromtxt(fname, **kwargs):
"""
Load ASCII data stored in a text file and return a masked array.
.. deprecated:: 1.17
np.mafromtxt is a deprecated alias of `genfromtxt` which
overwrites the ``usemask`` argument with `True` even when
explicitly called as ``mafromtxt(..., usemask=False)``.
Use `genfromtxt` instead.
Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.
See Also
--------
numpy.genfromtxt : generic function to load ASCII data.
"""
kwargs['usemask'] = True
# Numpy 1.17
warnings.warn(
"np.mafromtxt is a deprecated alias of np.genfromtxt, "
"prefer the latter.",
DeprecationWarning, stacklevel=2)
return genfromtxt(fname, **kwargs) | [
"def",
"mafromtxt",
"(",
"fname",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'usemask'",
"]",
"=",
"True",
"# Numpy 1.17",
"warnings",
".",
"warn",
"(",
"\"np.mafromtxt is a deprecated alias of np.genfromtxt, \"",
"\"prefer the latter.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"genfromtxt",
"(",
"fname",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/npyio.py#L2285-L2310 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | tools/coverage/cuda_clean.py | python | get_files | (pull_id) | Args:
pull_id (int): Pull id.
Returns:
iterable: The generator will yield every filename. | Args:
pull_id (int): Pull id. | [
"Args",
":",
"pull_id",
"(",
"int",
")",
":",
"Pull",
"id",
"."
] | def get_files(pull_id):
"""
Args:
pull_id (int): Pull id.
Returns:
iterable: The generator will yield every filename.
"""
pull = get_pull(pull_id)
for file in pull.get_files():
yield file.filename | [
"def",
"get_files",
"(",
"pull_id",
")",
":",
"pull",
"=",
"get_pull",
"(",
"pull_id",
")",
"for",
"file",
"in",
"pull",
".",
"get_files",
"(",
")",
":",
"yield",
"file",
".",
"filename"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/coverage/cuda_clean.py#L41-L53 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewRenderer.CancelEditing | (*args, **kwargs) | return _dataview.DataViewRenderer_CancelEditing(*args, **kwargs) | CancelEditing(self) | CancelEditing(self) | [
"CancelEditing",
"(",
"self",
")"
] | def CancelEditing(*args, **kwargs):
"""CancelEditing(self)"""
return _dataview.DataViewRenderer_CancelEditing(*args, **kwargs) | [
"def",
"CancelEditing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewRenderer_CancelEditing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1212-L1214 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py | python | Environment.best_match | (
self, req, working_set, installer=None, replace_conflicting=False) | return self.obtain(req, installer) | Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned. | Find distribution best matching `req` and usable on `working_set` | [
"Find",
"distribution",
"best",
"matching",
"req",
"and",
"usable",
"on",
"working_set"
] | def best_match(
self, req, working_set, installer=None, replace_conflicting=False):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned.
"""
try:
dist = working_set.find(req)
except VersionConflict:
if not replace_conflicting:
raise
dist = None
if dist is not None:
return dist
for dist in self[req.key]:
if dist in req:
return dist
# try to download/install
return self.obtain(req, installer) | [
"def",
"best_match",
"(",
"self",
",",
"req",
",",
"working_set",
",",
"installer",
"=",
"None",
",",
"replace_conflicting",
"=",
"False",
")",
":",
"try",
":",
"dist",
"=",
"working_set",
".",
"find",
"(",
"req",
")",
"except",
"VersionConflict",
":",
"if",
"not",
"replace_conflicting",
":",
"raise",
"dist",
"=",
"None",
"if",
"dist",
"is",
"not",
"None",
":",
"return",
"dist",
"for",
"dist",
"in",
"self",
"[",
"req",
".",
"key",
"]",
":",
"if",
"dist",
"in",
"req",
":",
"return",
"dist",
"# try to download/install",
"return",
"self",
".",
"obtain",
"(",
"req",
",",
"installer",
")"
] | 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/__init__.py#L1040-L1066 | |
ROCmSoftwarePlatform/hipCaffe | 4ec5d482515cce532348553b6db6d00d015675d5 | scripts/cpp_lint.py | python | _NestingState.InNamespaceBody | (self) | return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise. | Check if we are currently one level inside a namespace body. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"a",
"namespace",
"body",
"."
] | def InNamespaceBody(self):
"""Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | [
"def",
"InNamespaceBody",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_NamespaceInfo",
")"
] | https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/scripts/cpp_lint.py#L1940-L1946 | |
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | shell/impala_shell.py | python | ImpalaShell._replace_history_delimiters | (self, src_delim, tgt_delim) | Replaces source_delim with target_delim for all items in history.
Read all the items from history into a local list. Clear the history and copy them
back after doing the transformation. | Replaces source_delim with target_delim for all items in history. | [
"Replaces",
"source_delim",
"with",
"target_delim",
"for",
"all",
"items",
"in",
"history",
"."
] | def _replace_history_delimiters(self, src_delim, tgt_delim):
"""Replaces source_delim with target_delim for all items in history.
Read all the items from history into a local list. Clear the history and copy them
back after doing the transformation.
"""
history_len = self.readline.get_current_history_length()
# load the history and replace the shell's delimiter with EOL
history_items = map(self.readline.get_history_item, xrange(1, history_len + 1))
if sys.version_info.major == 2:
src_delim = src_delim.encode('utf-8')
tgt_delim = tgt_delim.encode('utf-8')
history_items = [item.replace(src_delim, tgt_delim) for item in history_items]
# Clear the original history and replace it with the mutated history.
self.readline.clear_history()
for history_item in history_items:
self.readline.add_history(history_item) | [
"def",
"_replace_history_delimiters",
"(",
"self",
",",
"src_delim",
",",
"tgt_delim",
")",
":",
"history_len",
"=",
"self",
".",
"readline",
".",
"get_current_history_length",
"(",
")",
"# load the history and replace the shell's delimiter with EOL",
"history_items",
"=",
"map",
"(",
"self",
".",
"readline",
".",
"get_history_item",
",",
"xrange",
"(",
"1",
",",
"history_len",
"+",
"1",
")",
")",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"2",
":",
"src_delim",
"=",
"src_delim",
".",
"encode",
"(",
"'utf-8'",
")",
"tgt_delim",
"=",
"tgt_delim",
".",
"encode",
"(",
"'utf-8'",
")",
"history_items",
"=",
"[",
"item",
".",
"replace",
"(",
"src_delim",
",",
"tgt_delim",
")",
"for",
"item",
"in",
"history_items",
"]",
"# Clear the original history and replace it with the mutated history.",
"self",
".",
"readline",
".",
"clear_history",
"(",
")",
"for",
"history_item",
"in",
"history_items",
":",
"self",
".",
"readline",
".",
"add_history",
"(",
"history_item",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/impala_shell.py#L1666-L1682 | ||
deepmodeling/deepmd-kit | 159e45d248b0429844fb6a8cb3b3a201987c8d79 | deepmd/fit/polar.py | python | PolarFittingSeA.get_sel_type | (self) | return self.sel_type | Get selected atom types | Get selected atom types | [
"Get",
"selected",
"atom",
"types"
] | def get_sel_type(self) -> List[int]:
"""
Get selected atom types
"""
return self.sel_type | [
"def",
"get_sel_type",
"(",
"self",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"self",
".",
"sel_type"
] | https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/fit/polar.py#L196-L200 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/detector2dview.py | python | Detector2DView.plot_roi | (self) | return | Plot region of interest (as rectangular) to the canvas from the region set from
:return: | Plot region of interest (as rectangular) to the canvas from the region set from
:return: | [
"Plot",
"region",
"of",
"interest",
"(",
"as",
"rectangular",
")",
"to",
"the",
"canvas",
"from",
"the",
"region",
"set",
"from",
":",
"return",
":"
] | def plot_roi(self):
""" Plot region of interest (as rectangular) to the canvas from the region set from
:return:
"""
# check
assert self._roiStart is not None, 'Starting point of region-of-interest cannot be None'
assert self._roiEnd is not None, 'Ending point of region-of-interest cannot be None'
# create a vertex list of a rectangular
vertex_array = np.ndarray(shape=(4, 2))
# upper left corner
vertex_array[0][0] = self._roiStart[0]
vertex_array[0][1] = self._roiStart[1]
# lower right corner
vertex_array[2][0] = self._roiEnd[0]
vertex_array[2][1] = self._roiEnd[1]
# upper right corner
vertex_array[1][0] = self._roiEnd[0]
vertex_array[1][1] = self._roiStart[1]
# lower left corner
vertex_array[3][0] = self._roiStart[0]
vertex_array[3][1] = self._roiEnd[1]
# register
if self._myPolygon is not None:
self._myPolygon.remove()
self._myPolygon = None
self._myPolygon = self._myCanvas.plot_polygon(vertex_array, fill=False, color='w')
return | [
"def",
"plot_roi",
"(",
"self",
")",
":",
"# check",
"assert",
"self",
".",
"_roiStart",
"is",
"not",
"None",
",",
"'Starting point of region-of-interest cannot be None'",
"assert",
"self",
".",
"_roiEnd",
"is",
"not",
"None",
",",
"'Ending point of region-of-interest cannot be None'",
"# create a vertex list of a rectangular",
"vertex_array",
"=",
"np",
".",
"ndarray",
"(",
"shape",
"=",
"(",
"4",
",",
"2",
")",
")",
"# upper left corner",
"vertex_array",
"[",
"0",
"]",
"[",
"0",
"]",
"=",
"self",
".",
"_roiStart",
"[",
"0",
"]",
"vertex_array",
"[",
"0",
"]",
"[",
"1",
"]",
"=",
"self",
".",
"_roiStart",
"[",
"1",
"]",
"# lower right corner",
"vertex_array",
"[",
"2",
"]",
"[",
"0",
"]",
"=",
"self",
".",
"_roiEnd",
"[",
"0",
"]",
"vertex_array",
"[",
"2",
"]",
"[",
"1",
"]",
"=",
"self",
".",
"_roiEnd",
"[",
"1",
"]",
"# upper right corner",
"vertex_array",
"[",
"1",
"]",
"[",
"0",
"]",
"=",
"self",
".",
"_roiEnd",
"[",
"0",
"]",
"vertex_array",
"[",
"1",
"]",
"[",
"1",
"]",
"=",
"self",
".",
"_roiStart",
"[",
"1",
"]",
"# lower left corner",
"vertex_array",
"[",
"3",
"]",
"[",
"0",
"]",
"=",
"self",
".",
"_roiStart",
"[",
"0",
"]",
"vertex_array",
"[",
"3",
"]",
"[",
"1",
"]",
"=",
"self",
".",
"_roiEnd",
"[",
"1",
"]",
"# register",
"if",
"self",
".",
"_myPolygon",
"is",
"not",
"None",
":",
"self",
".",
"_myPolygon",
".",
"remove",
"(",
")",
"self",
".",
"_myPolygon",
"=",
"None",
"self",
".",
"_myPolygon",
"=",
"self",
".",
"_myCanvas",
".",
"plot_polygon",
"(",
"vertex_array",
",",
"fill",
"=",
"False",
",",
"color",
"=",
"'w'",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/detector2dview.py#L218-L250 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/loading_trace.py | python | LoadingTrace.RecordUrlNavigation | (
cls, url, connection, chrome_metadata, categories,
timeout_seconds=devtools_monitor.DEFAULT_TIMEOUT_SECONDS,
stop_delay_multiplier=0) | return trace | Create a loading trace by using controller to fetch url.
Args:
url: (str) url to fetch.
connection: An opened devtools connection.
chrome_metadata: Dictionary of chrome metadata.
categories: as in tracing.TracingTrack
timeout_seconds: monitoring connection timeout in seconds.
stop_delay_multiplier: How long to wait after page load completed before
tearing down, relative to the time it took to reach the page load to
complete.
Returns:
LoadingTrace instance. | Create a loading trace by using controller to fetch url. | [
"Create",
"a",
"loading",
"trace",
"by",
"using",
"controller",
"to",
"fetch",
"url",
"."
] | def RecordUrlNavigation(
cls, url, connection, chrome_metadata, categories,
timeout_seconds=devtools_monitor.DEFAULT_TIMEOUT_SECONDS,
stop_delay_multiplier=0):
"""Create a loading trace by using controller to fetch url.
Args:
url: (str) url to fetch.
connection: An opened devtools connection.
chrome_metadata: Dictionary of chrome metadata.
categories: as in tracing.TracingTrack
timeout_seconds: monitoring connection timeout in seconds.
stop_delay_multiplier: How long to wait after page load completed before
tearing down, relative to the time it took to reach the page load to
complete.
Returns:
LoadingTrace instance.
"""
page = page_track.PageTrack(connection)
request = request_track.RequestTrack(connection)
trace = tracing.TracingTrack(connection, categories)
start_date_str = datetime.datetime.utcnow().isoformat()
seconds_since_epoch=time.time()
connection.MonitorUrl(url,
timeout_seconds=timeout_seconds,
stop_delay_multiplier=stop_delay_multiplier)
trace = cls(url, chrome_metadata, page, request, trace)
trace.metadata.update(date=start_date_str,
seconds_since_epoch=seconds_since_epoch)
return trace | [
"def",
"RecordUrlNavigation",
"(",
"cls",
",",
"url",
",",
"connection",
",",
"chrome_metadata",
",",
"categories",
",",
"timeout_seconds",
"=",
"devtools_monitor",
".",
"DEFAULT_TIMEOUT_SECONDS",
",",
"stop_delay_multiplier",
"=",
"0",
")",
":",
"page",
"=",
"page_track",
".",
"PageTrack",
"(",
"connection",
")",
"request",
"=",
"request_track",
".",
"RequestTrack",
"(",
"connection",
")",
"trace",
"=",
"tracing",
".",
"TracingTrack",
"(",
"connection",
",",
"categories",
")",
"start_date_str",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"seconds_since_epoch",
"=",
"time",
".",
"time",
"(",
")",
"connection",
".",
"MonitorUrl",
"(",
"url",
",",
"timeout_seconds",
"=",
"timeout_seconds",
",",
"stop_delay_multiplier",
"=",
"stop_delay_multiplier",
")",
"trace",
"=",
"cls",
"(",
"url",
",",
"chrome_metadata",
",",
"page",
",",
"request",
",",
"trace",
")",
"trace",
".",
"metadata",
".",
"update",
"(",
"date",
"=",
"start_date_str",
",",
"seconds_since_epoch",
"=",
"seconds_since_epoch",
")",
"return",
"trace"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/loading_trace.py#L81-L111 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextCtrl.IsSelectionUnderlined | (*args, **kwargs) | return _richtext.RichTextCtrl_IsSelectionUnderlined(*args, **kwargs) | IsSelectionUnderlined(self) -> bool
Is all of the selection underlined? | IsSelectionUnderlined(self) -> bool | [
"IsSelectionUnderlined",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsSelectionUnderlined(*args, **kwargs):
"""
IsSelectionUnderlined(self) -> bool
Is all of the selection underlined?
"""
return _richtext.RichTextCtrl_IsSelectionUnderlined(*args, **kwargs) | [
"def",
"IsSelectionUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_IsSelectionUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3931-L3937 | |
argman/EAST | dca414de39a3a4915a019c9a02c1832a31cdd0ca | nets/resnet_utils.py | python | stack_blocks_dense | (net, blocks, output_stride=None,
outputs_collections=None) | return net | Stacks ResNet `Blocks` and controls output feature density.
First, this function creates scopes for the ResNet in the form of
'block_name/unit_1', 'block_name/unit_2', etc.
Second, this function allows the user to explicitly control the ResNet
output_stride, which is the ratio of the input to output spatial resolution.
This is useful for dense prediction tasks such as semantic segmentation or
object detection.
Most ResNets consist of 4 ResNet blocks and subsample the activations by a
factor of 2 when transitioning between consecutive ResNet blocks. This results
to a nominal ResNet output_stride equal to 8. If we set the output_stride to
half the nominal network stride (e.g., output_stride=4), then we compute
responses twice.
Control of the output feature density is implemented by atrous convolution.
Args:
net: A `Tensor` of size [batch, height, width, channels].
blocks: A list of length equal to the number of ResNet `Blocks`. Each
element is a ResNet `Block` object describing the units in the `Block`.
output_stride: If `None`, then the output will be computed at the nominal
network stride. If output_stride is not `None`, it specifies the requested
ratio of input to output spatial resolution, which needs to be equal to
the product of unit strides from the start up to some level of the ResNet.
For example, if the ResNet employs units with strides 1, 2, 1, 3, 4, 1,
then valid values for the output_stride are 1, 2, 6, 24 or None (which
is equivalent to output_stride=24).
outputs_collections: Collection to add the ResNet block outputs.
Returns:
net: Output tensor with stride equal to the specified output_stride.
Raises:
ValueError: If the target output_stride is not valid. | Stacks ResNet `Blocks` and controls output feature density. | [
"Stacks",
"ResNet",
"Blocks",
"and",
"controls",
"output",
"feature",
"density",
"."
] | def stack_blocks_dense(net, blocks, output_stride=None,
outputs_collections=None):
"""Stacks ResNet `Blocks` and controls output feature density.
First, this function creates scopes for the ResNet in the form of
'block_name/unit_1', 'block_name/unit_2', etc.
Second, this function allows the user to explicitly control the ResNet
output_stride, which is the ratio of the input to output spatial resolution.
This is useful for dense prediction tasks such as semantic segmentation or
object detection.
Most ResNets consist of 4 ResNet blocks and subsample the activations by a
factor of 2 when transitioning between consecutive ResNet blocks. This results
to a nominal ResNet output_stride equal to 8. If we set the output_stride to
half the nominal network stride (e.g., output_stride=4), then we compute
responses twice.
Control of the output feature density is implemented by atrous convolution.
Args:
net: A `Tensor` of size [batch, height, width, channels].
blocks: A list of length equal to the number of ResNet `Blocks`. Each
element is a ResNet `Block` object describing the units in the `Block`.
output_stride: If `None`, then the output will be computed at the nominal
network stride. If output_stride is not `None`, it specifies the requested
ratio of input to output spatial resolution, which needs to be equal to
the product of unit strides from the start up to some level of the ResNet.
For example, if the ResNet employs units with strides 1, 2, 1, 3, 4, 1,
then valid values for the output_stride are 1, 2, 6, 24 or None (which
is equivalent to output_stride=24).
outputs_collections: Collection to add the ResNet block outputs.
Returns:
net: Output tensor with stride equal to the specified output_stride.
Raises:
ValueError: If the target output_stride is not valid.
"""
# The current_stride variable keeps track of the effective stride of the
# activations. This allows us to invoke atrous convolution whenever applying
# the next residual unit would result in the activations having stride larger
# than the target output_stride.
current_stride = 1
# The atrous convolution rate parameter.
rate = 1
for block in blocks:
with tf.variable_scope(block.scope, 'block', [net]) as sc:
for i, unit in enumerate(block.args):
if output_stride is not None and current_stride > output_stride:
raise ValueError('The target output_stride cannot be reached.')
with tf.variable_scope('unit_%d' % (i + 1), values=[net]):
unit_depth, unit_depth_bottleneck, unit_stride = unit
# If we have reached the target output_stride, then we need to employ
# atrous convolution with stride=1 and multiply the atrous rate by the
# current unit's stride for use in subsequent layers.
if output_stride is not None and current_stride == output_stride:
net = block.unit_fn(net,
depth=unit_depth,
depth_bottleneck=unit_depth_bottleneck,
stride=1,
rate=rate)
rate *= unit_stride
else:
net = block.unit_fn(net,
depth=unit_depth,
depth_bottleneck=unit_depth_bottleneck,
stride=unit_stride,
rate=1)
current_stride *= unit_stride
print(sc.name, net.shape)
net = slim.utils.collect_named_outputs(outputs_collections, sc.name, net)
if output_stride is not None and current_stride != output_stride:
raise ValueError('The target output_stride cannot be reached.')
return net | [
"def",
"stack_blocks_dense",
"(",
"net",
",",
"blocks",
",",
"output_stride",
"=",
"None",
",",
"outputs_collections",
"=",
"None",
")",
":",
"# The current_stride variable keeps track of the effective stride of the",
"# activations. This allows us to invoke atrous convolution whenever applying",
"# the next residual unit would result in the activations having stride larger",
"# than the target output_stride.",
"current_stride",
"=",
"1",
"# The atrous convolution rate parameter.",
"rate",
"=",
"1",
"for",
"block",
"in",
"blocks",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"block",
".",
"scope",
",",
"'block'",
",",
"[",
"net",
"]",
")",
"as",
"sc",
":",
"for",
"i",
",",
"unit",
"in",
"enumerate",
"(",
"block",
".",
"args",
")",
":",
"if",
"output_stride",
"is",
"not",
"None",
"and",
"current_stride",
">",
"output_stride",
":",
"raise",
"ValueError",
"(",
"'The target output_stride cannot be reached.'",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"'unit_%d'",
"%",
"(",
"i",
"+",
"1",
")",
",",
"values",
"=",
"[",
"net",
"]",
")",
":",
"unit_depth",
",",
"unit_depth_bottleneck",
",",
"unit_stride",
"=",
"unit",
"# If we have reached the target output_stride, then we need to employ",
"# atrous convolution with stride=1 and multiply the atrous rate by the",
"# current unit's stride for use in subsequent layers.",
"if",
"output_stride",
"is",
"not",
"None",
"and",
"current_stride",
"==",
"output_stride",
":",
"net",
"=",
"block",
".",
"unit_fn",
"(",
"net",
",",
"depth",
"=",
"unit_depth",
",",
"depth_bottleneck",
"=",
"unit_depth_bottleneck",
",",
"stride",
"=",
"1",
",",
"rate",
"=",
"rate",
")",
"rate",
"*=",
"unit_stride",
"else",
":",
"net",
"=",
"block",
".",
"unit_fn",
"(",
"net",
",",
"depth",
"=",
"unit_depth",
",",
"depth_bottleneck",
"=",
"unit_depth_bottleneck",
",",
"stride",
"=",
"unit_stride",
",",
"rate",
"=",
"1",
")",
"current_stride",
"*=",
"unit_stride",
"print",
"(",
"sc",
".",
"name",
",",
"net",
".",
"shape",
")",
"net",
"=",
"slim",
".",
"utils",
".",
"collect_named_outputs",
"(",
"outputs_collections",
",",
"sc",
".",
"name",
",",
"net",
")",
"if",
"output_stride",
"is",
"not",
"None",
"and",
"current_stride",
"!=",
"output_stride",
":",
"raise",
"ValueError",
"(",
"'The target output_stride cannot be reached.'",
")",
"return",
"net"
] | https://github.com/argman/EAST/blob/dca414de39a3a4915a019c9a02c1832a31cdd0ca/nets/resnet_utils.py#L126-L206 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/webapp2/webapp2_extras/auth.py | python | Auth.get_session_data | (self, pop=False) | return None | Returns the session data as a dictionary.
:param pop:
If True, removes the session.
:returns:
A deserialized session, or None. | Returns the session data as a dictionary. | [
"Returns",
"the",
"session",
"data",
"as",
"a",
"dictionary",
"."
] | def get_session_data(self, pop=False):
"""Returns the session data as a dictionary.
:param pop:
If True, removes the session.
:returns:
A deserialized session, or None.
"""
func = self.session.pop if pop else self.session.get
rv = func('_user', None)
if rv is not None:
data = self.store.deserialize_session(rv)
if data:
return data
elif not pop:
self.session.pop('_user', None)
return None | [
"def",
"get_session_data",
"(",
"self",
",",
"pop",
"=",
"False",
")",
":",
"func",
"=",
"self",
".",
"session",
".",
"pop",
"if",
"pop",
"else",
"self",
".",
"session",
".",
"get",
"rv",
"=",
"func",
"(",
"'_user'",
",",
"None",
")",
"if",
"rv",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"store",
".",
"deserialize_session",
"(",
"rv",
")",
"if",
"data",
":",
"return",
"data",
"elif",
"not",
"pop",
":",
"self",
".",
"session",
".",
"pop",
"(",
"'_user'",
",",
"None",
")",
"return",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2_extras/auth.py#L523-L540 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_tensor_shape.py | python | RaggedTensorDynamicShape.__init__ | (self, partitioned_dim_sizes, inner_dim_sizes,
dim_size_dtype=None) | Creates a RaggedTensorDynamicShape.
Args:
partitioned_dim_sizes: A `list` of 0-D or 1-D integer `Tensor`, one for
each partitioned dimension. If dimension `d` is uniform, then
`partitioned_dim_sizes[d]` must be an integer scalar, specifying the
size of all slices across dimension `d`. If dimension `d` is ragged,
then `partitioned_dim_sizes[d]` must be an integer vector, specifying
the size of each slice across dimension `d`.
inner_dim_sizes: A 1-D integer `Tensor`, whose length is equal to the
number of inner dimensions. `inner_dim_sizes[n]` is the size of all
slices across the `n`th inner dimension (which is the
`(len(partitioned_dim_sizes)+n)`th dimension in the overall tensor.
dim_size_dtype: dtype for dimension sizes. If not specified, then it
is chosen based on the dtypes of `partitioned_dim_sizes` and
`inner_dim_sizes`. | Creates a RaggedTensorDynamicShape. | [
"Creates",
"a",
"RaggedTensorDynamicShape",
"."
] | def __init__(self, partitioned_dim_sizes, inner_dim_sizes,
dim_size_dtype=None):
"""Creates a RaggedTensorDynamicShape.
Args:
partitioned_dim_sizes: A `list` of 0-D or 1-D integer `Tensor`, one for
each partitioned dimension. If dimension `d` is uniform, then
`partitioned_dim_sizes[d]` must be an integer scalar, specifying the
size of all slices across dimension `d`. If dimension `d` is ragged,
then `partitioned_dim_sizes[d]` must be an integer vector, specifying
the size of each slice across dimension `d`.
inner_dim_sizes: A 1-D integer `Tensor`, whose length is equal to the
number of inner dimensions. `inner_dim_sizes[n]` is the size of all
slices across the `n`th inner dimension (which is the
`(len(partitioned_dim_sizes)+n)`th dimension in the overall tensor.
dim_size_dtype: dtype for dimension sizes. If not specified, then it
is chosen based on the dtypes of `partitioned_dim_sizes` and
`inner_dim_sizes`.
"""
assert isinstance(partitioned_dim_sizes, (list, tuple))
with ops.name_scope(None, 'RaggedTensorDynamicShape',
(partitioned_dim_sizes, inner_dim_sizes)):
partitioned_dim_sizes = tuple(
ops.convert_to_tensor(size, name='partitioned_dimension_size_%d' % i)
for (i, size) in enumerate(partitioned_dim_sizes))
inner_dim_sizes = ops.convert_to_tensor(
inner_dim_sizes, name='inner_dim_sizes')
# Validate shapes.
if partitioned_dim_sizes:
for axis, dimension_size in enumerate(partitioned_dim_sizes):
if dimension_size.shape.ndims is None:
raise ValueError(
'rank of partitioned_dim_sizes[%d] is unknown' % axis)
dimension_size.shape.with_rank_at_most(1)
if partitioned_dim_sizes[0].shape.ndims == 1:
raise ValueError('outermost partitioned dimension must be uniform')
if partitioned_dim_sizes[-1].shape.ndims == 0:
raise ValueError('innermost partitioned dimension must be ragged')
inner_dim_sizes.shape.assert_has_rank(1)
# Convert dimension size tensors to a single dtype.
if dim_size_dtype is None:
dim_size_dtypes = set(
p.dtype for p in partitioned_dim_sizes if p.shape.ndims == 1)
if not dim_size_dtypes:
dim_size_dtype = dtypes.int64
elif len(dim_size_dtypes) == 1:
dim_size_dtype = dim_size_dtypes.pop()
else:
if not ragged_config.auto_cast_partition_dtype():
raise ValueError('partitioned_dim_sizes must have matching dtypes')
dim_size_dtype = dtypes.int64
partitioned_dim_sizes = tuple(math_ops.cast(p, dim_size_dtype)
for p in partitioned_dim_sizes)
inner_dim_sizes = math_ops.cast(inner_dim_sizes, dim_size_dtype)
self._partitioned_dim_sizes = partitioned_dim_sizes
self._inner_dim_sizes = inner_dim_sizes | [
"def",
"__init__",
"(",
"self",
",",
"partitioned_dim_sizes",
",",
"inner_dim_sizes",
",",
"dim_size_dtype",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"partitioned_dim_sizes",
",",
"(",
"list",
",",
"tuple",
")",
")",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"'RaggedTensorDynamicShape'",
",",
"(",
"partitioned_dim_sizes",
",",
"inner_dim_sizes",
")",
")",
":",
"partitioned_dim_sizes",
"=",
"tuple",
"(",
"ops",
".",
"convert_to_tensor",
"(",
"size",
",",
"name",
"=",
"'partitioned_dimension_size_%d'",
"%",
"i",
")",
"for",
"(",
"i",
",",
"size",
")",
"in",
"enumerate",
"(",
"partitioned_dim_sizes",
")",
")",
"inner_dim_sizes",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"inner_dim_sizes",
",",
"name",
"=",
"'inner_dim_sizes'",
")",
"# Validate shapes.",
"if",
"partitioned_dim_sizes",
":",
"for",
"axis",
",",
"dimension_size",
"in",
"enumerate",
"(",
"partitioned_dim_sizes",
")",
":",
"if",
"dimension_size",
".",
"shape",
".",
"ndims",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'rank of partitioned_dim_sizes[%d] is unknown'",
"%",
"axis",
")",
"dimension_size",
".",
"shape",
".",
"with_rank_at_most",
"(",
"1",
")",
"if",
"partitioned_dim_sizes",
"[",
"0",
"]",
".",
"shape",
".",
"ndims",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"'outermost partitioned dimension must be uniform'",
")",
"if",
"partitioned_dim_sizes",
"[",
"-",
"1",
"]",
".",
"shape",
".",
"ndims",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'innermost partitioned dimension must be ragged'",
")",
"inner_dim_sizes",
".",
"shape",
".",
"assert_has_rank",
"(",
"1",
")",
"# Convert dimension size tensors to a single dtype.",
"if",
"dim_size_dtype",
"is",
"None",
":",
"dim_size_dtypes",
"=",
"set",
"(",
"p",
".",
"dtype",
"for",
"p",
"in",
"partitioned_dim_sizes",
"if",
"p",
".",
"shape",
".",
"ndims",
"==",
"1",
")",
"if",
"not",
"dim_size_dtypes",
":",
"dim_size_dtype",
"=",
"dtypes",
".",
"int64",
"elif",
"len",
"(",
"dim_size_dtypes",
")",
"==",
"1",
":",
"dim_size_dtype",
"=",
"dim_size_dtypes",
".",
"pop",
"(",
")",
"else",
":",
"if",
"not",
"ragged_config",
".",
"auto_cast_partition_dtype",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'partitioned_dim_sizes must have matching dtypes'",
")",
"dim_size_dtype",
"=",
"dtypes",
".",
"int64",
"partitioned_dim_sizes",
"=",
"tuple",
"(",
"math_ops",
".",
"cast",
"(",
"p",
",",
"dim_size_dtype",
")",
"for",
"p",
"in",
"partitioned_dim_sizes",
")",
"inner_dim_sizes",
"=",
"math_ops",
".",
"cast",
"(",
"inner_dim_sizes",
",",
"dim_size_dtype",
")",
"self",
".",
"_partitioned_dim_sizes",
"=",
"partitioned_dim_sizes",
"self",
".",
"_inner_dim_sizes",
"=",
"inner_dim_sizes"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_tensor_shape.py#L81-L140 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py | python | ZipFile.extractall | (self, path=None, members=None, pwd=None) | Extract all members from the archive to the current working
directory. `path' specifies a different directory to extract to.
`members' is optional and must be a subset of the list returned
by namelist(). | Extract all members from the archive to the current working
directory. `path' specifies a different directory to extract to.
`members' is optional and must be a subset of the list returned
by namelist(). | [
"Extract",
"all",
"members",
"from",
"the",
"archive",
"to",
"the",
"current",
"working",
"directory",
".",
"path",
"specifies",
"a",
"different",
"directory",
"to",
"extract",
"to",
".",
"members",
"is",
"optional",
"and",
"must",
"be",
"a",
"subset",
"of",
"the",
"list",
"returned",
"by",
"namelist",
"()",
"."
] | def extractall(self, path=None, members=None, pwd=None):
"""Extract all members from the archive to the current working
directory. `path' specifies a different directory to extract to.
`members' is optional and must be a subset of the list returned
by namelist().
"""
if members is None:
members = self.namelist()
for zipinfo in members:
self.extract(zipinfo, path, pwd) | [
"def",
"extractall",
"(",
"self",
",",
"path",
"=",
"None",
",",
"members",
"=",
"None",
",",
"pwd",
"=",
"None",
")",
":",
"if",
"members",
"is",
"None",
":",
"members",
"=",
"self",
".",
"namelist",
"(",
")",
"for",
"zipinfo",
"in",
"members",
":",
"self",
".",
"extract",
"(",
"zipinfo",
",",
"path",
",",
"pwd",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py#L1026-L1036 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Listbox.insert | (self, index, *elements) | Insert ELEMENTS at INDEX. | Insert ELEMENTS at INDEX. | [
"Insert",
"ELEMENTS",
"at",
"INDEX",
"."
] | def insert(self, index, *elements):
"""Insert ELEMENTS at INDEX."""
self.tk.call((self._w, 'insert', index) + elements) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"*",
"elements",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'insert'",
",",
"index",
")",
"+",
"elements",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2578-L2580 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/metrics/metric.py | python | acc | (correct, total, scope=None, util=None) | return float(global_correct_num[0]) / float(global_total_num[0]) | distributed accuracy in fleet
Args:
correct(numpy.array|Variable|string): correct Variable
total(numpy.array|Variable): total Variable
scope(Scope): specific scope
Returns:
acc(float): accuracy value
Example:
.. code-block:: python
# in model.py
correct = fluid.layers.create_global_var(dtype='float32', shape=[1], value=0)
total = fluid.layers.create_global_var(dtype='float32', shape=[1], value=0)
acc = fluid.layers.acc(predict, label, k=1, correct=correct, total=total)
global_correct = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
tmp1 = fluid.layers.elementwise_min(correct, global_correct)
fluid.layers.assign(tmp1, global_correct)
global_total = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
tmp2 = fluid.layers.elementwise_min(total, global_total)
fluid.layers.assign(tmp2, global_total)
# in train.py, after train or infer
correct_num = np.array(scope.find_var(correct.name).get_tensor())
total_num = np.array(scope.find_var(total.name).get_tensor())
print("accuracy: ", paddle.distributed.fleet.acc(correct_num, total_num)) | distributed accuracy in fleet | [
"distributed",
"accuracy",
"in",
"fleet"
] | def acc(correct, total, scope=None, util=None):
"""
distributed accuracy in fleet
Args:
correct(numpy.array|Variable|string): correct Variable
total(numpy.array|Variable): total Variable
scope(Scope): specific scope
Returns:
acc(float): accuracy value
Example:
.. code-block:: python
# in model.py
correct = fluid.layers.create_global_var(dtype='float32', shape=[1], value=0)
total = fluid.layers.create_global_var(dtype='float32', shape=[1], value=0)
acc = fluid.layers.acc(predict, label, k=1, correct=correct, total=total)
global_correct = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
tmp1 = fluid.layers.elementwise_min(correct, global_correct)
fluid.layers.assign(tmp1, global_correct)
global_total = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
tmp2 = fluid.layers.elementwise_min(total, global_total)
fluid.layers.assign(tmp2, global_total)
# in train.py, after train or infer
correct_num = np.array(scope.find_var(correct.name).get_tensor())
total_num = np.array(scope.find_var(total.name).get_tensor())
print("accuracy: ", paddle.distributed.fleet.acc(correct_num, total_num))
"""
if scope is None:
scope = paddle.static.global_scope()
if util is None:
util = paddle.distributed.fleet.util
if isinstance(correct, Variable):
correct = np.array(scope.find_var(correct.name).get_tensor())
elif isinstance(correct, str):
correct = np.array(scope.find_var(correct).get_tensor())
if isinstance(total, Variable):
total = np.array(scope.find_var(total.name).get_tensor())
elif isinstance(total, str):
total = np.array(scope.find_var(total).get_tensor())
global_correct_num = np.copy(correct) * 0
global_total_num = np.copy(total) * 0
global_correct_num = util.all_reduce(correct, "sum")
global_total_num = util.all_reduce(total, "sum")
return float(global_correct_num[0]) / float(global_total_num[0]) | [
"def",
"acc",
"(",
"correct",
",",
"total",
",",
"scope",
"=",
"None",
",",
"util",
"=",
"None",
")",
":",
"if",
"scope",
"is",
"None",
":",
"scope",
"=",
"paddle",
".",
"static",
".",
"global_scope",
"(",
")",
"if",
"util",
"is",
"None",
":",
"util",
"=",
"paddle",
".",
"distributed",
".",
"fleet",
".",
"util",
"if",
"isinstance",
"(",
"correct",
",",
"Variable",
")",
":",
"correct",
"=",
"np",
".",
"array",
"(",
"scope",
".",
"find_var",
"(",
"correct",
".",
"name",
")",
".",
"get_tensor",
"(",
")",
")",
"elif",
"isinstance",
"(",
"correct",
",",
"str",
")",
":",
"correct",
"=",
"np",
".",
"array",
"(",
"scope",
".",
"find_var",
"(",
"correct",
")",
".",
"get_tensor",
"(",
")",
")",
"if",
"isinstance",
"(",
"total",
",",
"Variable",
")",
":",
"total",
"=",
"np",
".",
"array",
"(",
"scope",
".",
"find_var",
"(",
"total",
".",
"name",
")",
".",
"get_tensor",
"(",
")",
")",
"elif",
"isinstance",
"(",
"total",
",",
"str",
")",
":",
"total",
"=",
"np",
".",
"array",
"(",
"scope",
".",
"find_var",
"(",
"total",
")",
".",
"get_tensor",
"(",
")",
")",
"global_correct_num",
"=",
"np",
".",
"copy",
"(",
"correct",
")",
"*",
"0",
"global_total_num",
"=",
"np",
".",
"copy",
"(",
"total",
")",
"*",
"0",
"global_correct_num",
"=",
"util",
".",
"all_reduce",
"(",
"correct",
",",
"\"sum\"",
")",
"global_total_num",
"=",
"util",
".",
"all_reduce",
"(",
"total",
",",
"\"sum\"",
")",
"return",
"float",
"(",
"global_correct_num",
"[",
"0",
"]",
")",
"/",
"float",
"(",
"global_total_num",
"[",
"0",
"]",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/metrics/metric.py#L373-L426 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | RecoEgamma/ElectronIdentification/python/Identification/cutBasedElectronID_tools.py | python | configureVIDCutBasedEleID_V3 | ( wpEB, wpEE, isoInputs ) | return parameterSet | This function configures the full cms.PSet for a VID ID and returns it.
The inputs: two objects of the type WorkingPoint_V3, one
containing the cuts for the Barrel (EB) and the other one for the Endcap (EE).
The third argument is an object that contains information necessary
for isolation calculations.
In this version, the impact parameter cuts dxy and dz are not present | This function configures the full cms.PSet for a VID ID and returns it.
The inputs: two objects of the type WorkingPoint_V3, one
containing the cuts for the Barrel (EB) and the other one for the Endcap (EE).
The third argument is an object that contains information necessary
for isolation calculations.
In this version, the impact parameter cuts dxy and dz are not present | [
"This",
"function",
"configures",
"the",
"full",
"cms",
".",
"PSet",
"for",
"a",
"VID",
"ID",
"and",
"returns",
"it",
".",
"The",
"inputs",
":",
"two",
"objects",
"of",
"the",
"type",
"WorkingPoint_V3",
"one",
"containing",
"the",
"cuts",
"for",
"the",
"Barrel",
"(",
"EB",
")",
"and",
"the",
"other",
"one",
"for",
"the",
"Endcap",
"(",
"EE",
")",
".",
"The",
"third",
"argument",
"is",
"an",
"object",
"that",
"contains",
"information",
"necessary",
"for",
"isolation",
"calculations",
".",
"In",
"this",
"version",
"the",
"impact",
"parameter",
"cuts",
"dxy",
"and",
"dz",
"are",
"not",
"present"
] | def configureVIDCutBasedEleID_V3( wpEB, wpEE, isoInputs ):
"""
This function configures the full cms.PSet for a VID ID and returns it.
The inputs: two objects of the type WorkingPoint_V3, one
containing the cuts for the Barrel (EB) and the other one for the Endcap (EE).
The third argument is an object that contains information necessary
for isolation calculations.
In this version, the impact parameter cuts dxy and dz are not present
"""
# print "VID: Configuring cut set %s" % wpEB.idName
parameterSet = cms.PSet(
#
idName = cms.string( wpEB.idName ), # same name stored in the _EB and _EE objects
cutFlow = cms.VPSet(
psetMinPtCut(),
psetPhoSCEtaMultiRangeCut(), # eta cut
psetDEtaInSeedCut(wpEB, wpEE), # dEtaIn seed cut
psetDPhiInCut(wpEB, wpEE), # dPhiIn cut
psetFull5x5SigmaIEtaIEtaCut(wpEB, wpEE), # full 5x5 sigmaIEtaIEta cut
psetHadronicOverEMCut(wpEB, wpEE), # H/E cut
psetEInerseMinusPInverseCut(wpEB, wpEE), # |1/e-1/p| cut
psetEffAreaPFIsoCut(wpEB, wpEE, isoInputs), # rel. comb. PF isolation cut
psetConversionVetoCut(),
psetMissingHitsCut(wpEB, wpEE)
)
)
#
return parameterSet | [
"def",
"configureVIDCutBasedEleID_V3",
"(",
"wpEB",
",",
"wpEE",
",",
"isoInputs",
")",
":",
"# print \"VID: Configuring cut set %s\" % wpEB.idName",
"parameterSet",
"=",
"cms",
".",
"PSet",
"(",
"#",
"idName",
"=",
"cms",
".",
"string",
"(",
"wpEB",
".",
"idName",
")",
",",
"# same name stored in the _EB and _EE objects",
"cutFlow",
"=",
"cms",
".",
"VPSet",
"(",
"psetMinPtCut",
"(",
")",
",",
"psetPhoSCEtaMultiRangeCut",
"(",
")",
",",
"# eta cut",
"psetDEtaInSeedCut",
"(",
"wpEB",
",",
"wpEE",
")",
",",
"# dEtaIn seed cut",
"psetDPhiInCut",
"(",
"wpEB",
",",
"wpEE",
")",
",",
"# dPhiIn cut",
"psetFull5x5SigmaIEtaIEtaCut",
"(",
"wpEB",
",",
"wpEE",
")",
",",
"# full 5x5 sigmaIEtaIEta cut",
"psetHadronicOverEMCut",
"(",
"wpEB",
",",
"wpEE",
")",
",",
"# H/E cut",
"psetEInerseMinusPInverseCut",
"(",
"wpEB",
",",
"wpEE",
")",
",",
"# |1/e-1/p| cut",
"psetEffAreaPFIsoCut",
"(",
"wpEB",
",",
"wpEE",
",",
"isoInputs",
")",
",",
"# rel. comb. PF isolation cut",
"psetConversionVetoCut",
"(",
")",
",",
"psetMissingHitsCut",
"(",
"wpEB",
",",
"wpEE",
")",
")",
")",
"#",
"return",
"parameterSet"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/RecoEgamma/ElectronIdentification/python/Identification/cutBasedElectronID_tools.py#L480-L507 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/commands/setmeta.py | python | SetMetaCommand._ParseMetadataHeaders | (self, headers) | return (metadata_minus, metadata_plus) | Validates and parses metadata changes from the headers argument.
Args:
headers: Header dict to validate and parse.
Returns:
(metadata_plus, metadata_minus): Tuple of header sets to add and remove. | Validates and parses metadata changes from the headers argument. | [
"Validates",
"and",
"parses",
"metadata",
"changes",
"from",
"the",
"headers",
"argument",
"."
] | def _ParseMetadataHeaders(self, headers):
"""Validates and parses metadata changes from the headers argument.
Args:
headers: Header dict to validate and parse.
Returns:
(metadata_plus, metadata_minus): Tuple of header sets to add and remove.
"""
metadata_minus = set()
cust_metadata_minus = set()
metadata_plus = {}
cust_metadata_plus = {}
# Build a count of the keys encountered from each plus and minus arg so we
# can check for dupe field specs.
num_metadata_plus_elems = 0
num_cust_metadata_plus_elems = 0
num_metadata_minus_elems = 0
num_cust_metadata_minus_elems = 0
for md_arg in headers:
parts = md_arg.split(':')
if len(parts) not in (1, 2):
raise CommandException(
'Invalid argument: must be either header or header:value (%s)' %
md_arg)
if len(parts) == 2:
(header, value) = parts
else:
(header, value) = (parts[0], None)
_InsistAsciiHeader(header)
# Translate headers to lowercase to match the casing assumed by our
# sanity-checking operations.
header = header.lower()
if value:
if _IsCustomMeta(header):
# Allow non-ASCII data for custom metadata fields.
cust_metadata_plus[header] = value
num_cust_metadata_plus_elems += 1
else:
# Don't unicode encode other fields because that would perturb their
# content (e.g., adding %2F's into the middle of a Cache-Control
# value).
_InsistAsciiHeaderValue(header, value)
value = str(value)
metadata_plus[header] = value
num_metadata_plus_elems += 1
else:
if _IsCustomMeta(header):
cust_metadata_minus.add(header)
num_cust_metadata_minus_elems += 1
else:
metadata_minus.add(header)
num_metadata_minus_elems += 1
if (num_metadata_plus_elems != len(metadata_plus)
or num_cust_metadata_plus_elems != len(cust_metadata_plus)
or num_metadata_minus_elems != len(metadata_minus)
or num_cust_metadata_minus_elems != len(cust_metadata_minus)
or metadata_minus.intersection(set(metadata_plus.keys()))):
raise CommandException('Each header must appear at most once.')
other_than_base_fields = (set(metadata_plus.keys())
.difference(SETTABLE_FIELDS))
other_than_base_fields.update(
metadata_minus.difference(SETTABLE_FIELDS))
for f in other_than_base_fields:
# This check is overly simple; it would be stronger to check, for each
# URL argument, whether f.startswith the
# provider metadata_prefix, but here we just parse the spec
# once, before processing any of the URLs. This means we will not
# detect if the user tries to set an x-goog-meta- field on an another
# provider's object, for example.
if not _IsCustomMeta(f):
raise CommandException(
'Invalid or disallowed header (%s).\nOnly these fields (plus '
'x-goog-meta-* fields) can be set or unset:\n%s' % (
f, sorted(list(SETTABLE_FIELDS))))
metadata_plus.update(cust_metadata_plus)
metadata_minus.update(cust_metadata_minus)
return (metadata_minus, metadata_plus) | [
"def",
"_ParseMetadataHeaders",
"(",
"self",
",",
"headers",
")",
":",
"metadata_minus",
"=",
"set",
"(",
")",
"cust_metadata_minus",
"=",
"set",
"(",
")",
"metadata_plus",
"=",
"{",
"}",
"cust_metadata_plus",
"=",
"{",
"}",
"# Build a count of the keys encountered from each plus and minus arg so we",
"# can check for dupe field specs.",
"num_metadata_plus_elems",
"=",
"0",
"num_cust_metadata_plus_elems",
"=",
"0",
"num_metadata_minus_elems",
"=",
"0",
"num_cust_metadata_minus_elems",
"=",
"0",
"for",
"md_arg",
"in",
"headers",
":",
"parts",
"=",
"md_arg",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"parts",
")",
"not",
"in",
"(",
"1",
",",
"2",
")",
":",
"raise",
"CommandException",
"(",
"'Invalid argument: must be either header or header:value (%s)'",
"%",
"md_arg",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"(",
"header",
",",
"value",
")",
"=",
"parts",
"else",
":",
"(",
"header",
",",
"value",
")",
"=",
"(",
"parts",
"[",
"0",
"]",
",",
"None",
")",
"_InsistAsciiHeader",
"(",
"header",
")",
"# Translate headers to lowercase to match the casing assumed by our",
"# sanity-checking operations.",
"header",
"=",
"header",
".",
"lower",
"(",
")",
"if",
"value",
":",
"if",
"_IsCustomMeta",
"(",
"header",
")",
":",
"# Allow non-ASCII data for custom metadata fields.",
"cust_metadata_plus",
"[",
"header",
"]",
"=",
"value",
"num_cust_metadata_plus_elems",
"+=",
"1",
"else",
":",
"# Don't unicode encode other fields because that would perturb their",
"# content (e.g., adding %2F's into the middle of a Cache-Control",
"# value).",
"_InsistAsciiHeaderValue",
"(",
"header",
",",
"value",
")",
"value",
"=",
"str",
"(",
"value",
")",
"metadata_plus",
"[",
"header",
"]",
"=",
"value",
"num_metadata_plus_elems",
"+=",
"1",
"else",
":",
"if",
"_IsCustomMeta",
"(",
"header",
")",
":",
"cust_metadata_minus",
".",
"add",
"(",
"header",
")",
"num_cust_metadata_minus_elems",
"+=",
"1",
"else",
":",
"metadata_minus",
".",
"add",
"(",
"header",
")",
"num_metadata_minus_elems",
"+=",
"1",
"if",
"(",
"num_metadata_plus_elems",
"!=",
"len",
"(",
"metadata_plus",
")",
"or",
"num_cust_metadata_plus_elems",
"!=",
"len",
"(",
"cust_metadata_plus",
")",
"or",
"num_metadata_minus_elems",
"!=",
"len",
"(",
"metadata_minus",
")",
"or",
"num_cust_metadata_minus_elems",
"!=",
"len",
"(",
"cust_metadata_minus",
")",
"or",
"metadata_minus",
".",
"intersection",
"(",
"set",
"(",
"metadata_plus",
".",
"keys",
"(",
")",
")",
")",
")",
":",
"raise",
"CommandException",
"(",
"'Each header must appear at most once.'",
")",
"other_than_base_fields",
"=",
"(",
"set",
"(",
"metadata_plus",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"SETTABLE_FIELDS",
")",
")",
"other_than_base_fields",
".",
"update",
"(",
"metadata_minus",
".",
"difference",
"(",
"SETTABLE_FIELDS",
")",
")",
"for",
"f",
"in",
"other_than_base_fields",
":",
"# This check is overly simple; it would be stronger to check, for each",
"# URL argument, whether f.startswith the",
"# provider metadata_prefix, but here we just parse the spec",
"# once, before processing any of the URLs. This means we will not",
"# detect if the user tries to set an x-goog-meta- field on an another",
"# provider's object, for example.",
"if",
"not",
"_IsCustomMeta",
"(",
"f",
")",
":",
"raise",
"CommandException",
"(",
"'Invalid or disallowed header (%s).\\nOnly these fields (plus '",
"'x-goog-meta-* fields) can be set or unset:\\n%s'",
"%",
"(",
"f",
",",
"sorted",
"(",
"list",
"(",
"SETTABLE_FIELDS",
")",
")",
")",
")",
"metadata_plus",
".",
"update",
"(",
"cust_metadata_plus",
")",
"metadata_minus",
".",
"update",
"(",
"cust_metadata_minus",
")",
"return",
"(",
"metadata_minus",
",",
"metadata_plus",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/commands/setmeta.py#L250-L329 | |
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert/run_classifier.py | python | DataProcessor.get_labels | (self) | Gets the list of labels for this data set. | Gets the list of labels for this data set. | [
"Gets",
"the",
"list",
"of",
"labels",
"for",
"this",
"data",
"set",
"."
] | def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError() | [
"def",
"get_labels",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert/run_classifier.py#L192-L194 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/twodim_base.py | python | vander | (x, N=None, increasing=False) | return v | Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. The
order of the powers is determined by the `increasing` boolean argument.
Specifically, when `increasing` is False, the `i`-th output column is
the input vector raised element-wise to the power of ``N - i - 1``. Such
a matrix with a geometric progression in each row is named for Alexandre-
Theophile Vandermonde.
Parameters
----------
x : array_like
1-D input array.
N : int, optional
Number of columns in the output. If `N` is not specified, a square
array is returned (``N = len(x)``).
increasing : bool, optional
Order of the powers of the columns. If True, the powers increase
from left to right, if False (the default) they are reversed.
.. versionadded:: 1.9.0
Returns
-------
out : ndarray
Vandermonde matrix. If `increasing` is False, the first column is
``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
True, the columns are ``x^0, x^1, ..., x^(N-1)``.
See Also
--------
polynomial.polynomial.polyvander
Examples
--------
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[ 1, 1, 1, 1],
[ 8, 4, 2, 1],
[ 27, 9, 3, 1],
[125, 25, 5, 1]])
>>> np.vander(x, increasing=True)
array([[ 1, 1, 1, 1],
[ 1, 2, 4, 8],
[ 1, 3, 9, 27],
[ 1, 5, 25, 125]])
The determinant of a square Vandermonde matrix is the product
of the differences between the values of the input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043 # may vary
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48 | Generate a Vandermonde matrix. | [
"Generate",
"a",
"Vandermonde",
"matrix",
"."
] | def vander(x, N=None, increasing=False):
"""
Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. The
order of the powers is determined by the `increasing` boolean argument.
Specifically, when `increasing` is False, the `i`-th output column is
the input vector raised element-wise to the power of ``N - i - 1``. Such
a matrix with a geometric progression in each row is named for Alexandre-
Theophile Vandermonde.
Parameters
----------
x : array_like
1-D input array.
N : int, optional
Number of columns in the output. If `N` is not specified, a square
array is returned (``N = len(x)``).
increasing : bool, optional
Order of the powers of the columns. If True, the powers increase
from left to right, if False (the default) they are reversed.
.. versionadded:: 1.9.0
Returns
-------
out : ndarray
Vandermonde matrix. If `increasing` is False, the first column is
``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
True, the columns are ``x^0, x^1, ..., x^(N-1)``.
See Also
--------
polynomial.polynomial.polyvander
Examples
--------
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[ 1, 1, 1, 1],
[ 8, 4, 2, 1],
[ 27, 9, 3, 1],
[125, 25, 5, 1]])
>>> np.vander(x, increasing=True)
array([[ 1, 1, 1, 1],
[ 1, 2, 4, 8],
[ 1, 3, 9, 27],
[ 1, 5, 25, 125]])
The determinant of a square Vandermonde matrix is the product
of the differences between the values of the input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043 # may vary
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
"""
x = asarray(x)
if x.ndim != 1:
raise ValueError("x must be a one-dimensional array or sequence.")
if N is None:
N = len(x)
v = empty((len(x), N), dtype=promote_types(x.dtype, int))
tmp = v[:, ::-1] if not increasing else v
if N > 0:
tmp[:, 0] = 1
if N > 1:
tmp[:, 1:] = x[:, None]
multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1)
return v | [
"def",
"vander",
"(",
"x",
",",
"N",
"=",
"None",
",",
"increasing",
"=",
"False",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"if",
"x",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"x must be a one-dimensional array or sequence.\"",
")",
"if",
"N",
"is",
"None",
":",
"N",
"=",
"len",
"(",
"x",
")",
"v",
"=",
"empty",
"(",
"(",
"len",
"(",
"x",
")",
",",
"N",
")",
",",
"dtype",
"=",
"promote_types",
"(",
"x",
".",
"dtype",
",",
"int",
")",
")",
"tmp",
"=",
"v",
"[",
":",
",",
":",
":",
"-",
"1",
"]",
"if",
"not",
"increasing",
"else",
"v",
"if",
"N",
">",
"0",
":",
"tmp",
"[",
":",
",",
"0",
"]",
"=",
"1",
"if",
"N",
">",
"1",
":",
"tmp",
"[",
":",
",",
"1",
":",
"]",
"=",
"x",
"[",
":",
",",
"None",
"]",
"multiply",
".",
"accumulate",
"(",
"tmp",
"[",
":",
",",
"1",
":",
"]",
",",
"out",
"=",
"tmp",
"[",
":",
",",
"1",
":",
"]",
",",
"axis",
"=",
"1",
")",
"return",
"v"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/twodim_base.py#L510-L597 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | cmake/developer_package/cpplint/cpplint.py | python | IsOutOfLineMethodDefinition | (clean_lines, linenum) | return False | Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition. | Check if current line contains an out-of-line method definition. | [
"Check",
"if",
"current",
"line",
"contains",
"an",
"out",
"-",
"of",
"-",
"line",
"method",
"definition",
"."
] | def IsOutOfLineMethodDefinition(clean_lines, linenum):
"""Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition.
"""
# Scan back a few lines for start of current function
for i in xrange(linenum, max(-1, linenum - 10), -1):
if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
return False | [
"def",
"IsOutOfLineMethodDefinition",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"# Scan back a few lines for start of current function",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"max",
"(",
"-",
"1",
",",
"linenum",
"-",
"10",
")",
",",
"-",
"1",
")",
":",
"if",
"Match",
"(",
"r'^([^()]*\\w+)\\('",
",",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
")",
":",
"return",
"Match",
"(",
"r'^[^()]*\\w+::\\w+\\('",
",",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
")",
"is",
"not",
"None",
"return",
"False"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/cmake/developer_package/cpplint/cpplint.py#L5227-L5240 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | MaskedArray.toflex | (self) | return record | Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
* the ``_data`` field stores the ``_data`` part of the array.
* the ``_mask`` field stores the ``_mask`` part of the array.
Parameters
----------
None
Returns
-------
record : ndarray
A new flexible-type `ndarray` with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape.
Notes
-----
A side-effect of transforming a masked array into a flexible `ndarray` is
that meta information (``fill_value``, ...) will be lost.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]] | Transforms a masked array into a flexible-type array. | [
"Transforms",
"a",
"masked",
"array",
"into",
"a",
"flexible",
"-",
"type",
"array",
"."
] | def toflex(self):
"""
Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
* the ``_data`` field stores the ``_data`` part of the array.
* the ``_mask`` field stores the ``_mask`` part of the array.
Parameters
----------
None
Returns
-------
record : ndarray
A new flexible-type `ndarray` with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape.
Notes
-----
A side-effect of transforming a masked array into a flexible `ndarray` is
that meta information (``fill_value``, ...) will be lost.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]]
"""
# Get the basic dtype ....
ddtype = self.dtype
# Make sure we have a mask
_mask = self._mask
if _mask is None:
_mask = make_mask_none(self.shape, ddtype)
# And get its dtype
mdtype = self._mask.dtype
#
record = np.ndarray(shape=self.shape,
dtype=[('_data', ddtype), ('_mask', mdtype)])
record['_data'] = self._data
record['_mask'] = self._mask
return record | [
"def",
"toflex",
"(",
"self",
")",
":",
"# Get the basic dtype ....",
"ddtype",
"=",
"self",
".",
"dtype",
"# Make sure we have a mask",
"_mask",
"=",
"self",
".",
"_mask",
"if",
"_mask",
"is",
"None",
":",
"_mask",
"=",
"make_mask_none",
"(",
"self",
".",
"shape",
",",
"ddtype",
")",
"# And get its dtype",
"mdtype",
"=",
"self",
".",
"_mask",
".",
"dtype",
"#",
"record",
"=",
"np",
".",
"ndarray",
"(",
"shape",
"=",
"self",
".",
"shape",
",",
"dtype",
"=",
"[",
"(",
"'_data'",
",",
"ddtype",
")",
",",
"(",
"'_mask'",
",",
"mdtype",
")",
"]",
")",
"record",
"[",
"'_data'",
"]",
"=",
"self",
".",
"_data",
"record",
"[",
"'_mask'",
"]",
"=",
"self",
".",
"_mask",
"return",
"record"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L5377-L5428 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/autograph/pyct/anno.py | python | dup | (node, copy_map, field_name='___pyct_anno') | Recursively copies annotations in an AST tree.
Args:
node: ast.AST
copy_map: Dict[Hashable, Hashable], maps a source anno key to a destination
key. All annotations with the source key will be copied to identical
annotations with the destination key.
field_name: str | Recursively copies annotations in an AST tree. | [
"Recursively",
"copies",
"annotations",
"in",
"an",
"AST",
"tree",
"."
] | def dup(node, copy_map, field_name='___pyct_anno'):
"""Recursively copies annotations in an AST tree.
Args:
node: ast.AST
copy_map: Dict[Hashable, Hashable], maps a source anno key to a destination
key. All annotations with the source key will be copied to identical
annotations with the destination key.
field_name: str
"""
for n in gast.walk(node):
for k in copy_map:
if hasanno(n, k, field_name):
setanno(n, copy_map[k], getanno(n, k, field_name), field_name) | [
"def",
"dup",
"(",
"node",
",",
"copy_map",
",",
"field_name",
"=",
"'___pyct_anno'",
")",
":",
"for",
"n",
"in",
"gast",
".",
"walk",
"(",
"node",
")",
":",
"for",
"k",
"in",
"copy_map",
":",
"if",
"hasanno",
"(",
"n",
",",
"k",
",",
"field_name",
")",
":",
"setanno",
"(",
"n",
",",
"copy_map",
"[",
"k",
"]",
",",
"getanno",
"(",
"n",
",",
"k",
",",
"field_name",
")",
",",
"field_name",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/pyct/anno.py#L161-L174 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/BASIC/basparse.py | python | p_command_def_bad_arg | (p) | command : DEF ID LPAREN error RPAREN EQUALS expr | command : DEF ID LPAREN error RPAREN EQUALS expr | [
"command",
":",
"DEF",
"ID",
"LPAREN",
"error",
"RPAREN",
"EQUALS",
"expr"
] | def p_command_def_bad_arg(p):
'''command : DEF ID LPAREN error RPAREN EQUALS expr'''
p[0] = "BAD ARGUMENT IN DEF STATEMENT" | [
"def",
"p_command_def_bad_arg",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"\"BAD ARGUMENT IN DEF STATEMENT\""
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/BASIC/basparse.py#L229-L231 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/crashhandler.py | python | CrashHandler.__init__ | (self, app, contact_name=None, contact_email=None,
bug_tracker=None, show_crash_traceback=True, call_pdb=False) | Create a new crash handler
Parameters
----------
app : Application
A running :class:`Application` instance, which will be queried at
crash time for internal information.
contact_name : str
A string with the name of the person to contact.
contact_email : str
A string with the email address of the contact.
bug_tracker : str
A string with the URL for your project's bug tracker.
show_crash_traceback : bool
If false, don't print the crash traceback on stderr, only generate
the on-disk report
Non-argument instance attributes:
These instances contain some non-argument attributes which allow for
further customization of the crash handler's behavior. Please see the
source for further details. | Create a new crash handler | [
"Create",
"a",
"new",
"crash",
"handler"
] | def __init__(self, app, contact_name=None, contact_email=None,
bug_tracker=None, show_crash_traceback=True, call_pdb=False):
"""Create a new crash handler
Parameters
----------
app : Application
A running :class:`Application` instance, which will be queried at
crash time for internal information.
contact_name : str
A string with the name of the person to contact.
contact_email : str
A string with the email address of the contact.
bug_tracker : str
A string with the URL for your project's bug tracker.
show_crash_traceback : bool
If false, don't print the crash traceback on stderr, only generate
the on-disk report
Non-argument instance attributes:
These instances contain some non-argument attributes which allow for
further customization of the crash handler's behavior. Please see the
source for further details.
"""
self.crash_report_fname = "Crash_report_%s.txt" % app.name
self.app = app
self.call_pdb = call_pdb
#self.call_pdb = True # dbg
self.show_crash_traceback = show_crash_traceback
self.info = dict(app_name = app.name,
contact_name = contact_name,
contact_email = contact_email,
bug_tracker = bug_tracker,
crash_report_fname = self.crash_report_fname) | [
"def",
"__init__",
"(",
"self",
",",
"app",
",",
"contact_name",
"=",
"None",
",",
"contact_email",
"=",
"None",
",",
"bug_tracker",
"=",
"None",
",",
"show_crash_traceback",
"=",
"True",
",",
"call_pdb",
"=",
"False",
")",
":",
"self",
".",
"crash_report_fname",
"=",
"\"Crash_report_%s.txt\"",
"%",
"app",
".",
"name",
"self",
".",
"app",
"=",
"app",
"self",
".",
"call_pdb",
"=",
"call_pdb",
"#self.call_pdb = True # dbg",
"self",
".",
"show_crash_traceback",
"=",
"show_crash_traceback",
"self",
".",
"info",
"=",
"dict",
"(",
"app_name",
"=",
"app",
".",
"name",
",",
"contact_name",
"=",
"contact_name",
",",
"contact_email",
"=",
"contact_email",
",",
"bug_tracker",
"=",
"bug_tracker",
",",
"crash_report_fname",
"=",
"self",
".",
"crash_report_fname",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/crashhandler.py#L97-L135 | ||
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/build/lib.linux-x86_64-2.7/mxnet/executor_manager.py | python | DataParallelExecutorManager.load_data_batch | (self, data_batch) | load data and labels into arrays | load data and labels into arrays | [
"load",
"data",
"and",
"labels",
"into",
"arrays"
] | def load_data_batch(self, data_batch):
""" load data and labels into arrays """
if self.sym_gen is not None:
key = data_batch.bucket_key
if key not in self.execgrp_bucket:
# create new bucket entry
symbol = self.sym_gen(key)
execgrp = DataParallelExecutorGroup(symbol, self.arg_names,
self.param_names, self.ctx,
self.slices, data_batch,
shared_group=self.execgrp)
self.execgrp_bucket[key] = execgrp
self.curr_execgrp = self.execgrp_bucket[key]
else:
self.curr_execgrp = self.execgrp
self.curr_execgrp.load_data_batch(data_batch) | [
"def",
"load_data_batch",
"(",
"self",
",",
"data_batch",
")",
":",
"if",
"self",
".",
"sym_gen",
"is",
"not",
"None",
":",
"key",
"=",
"data_batch",
".",
"bucket_key",
"if",
"key",
"not",
"in",
"self",
".",
"execgrp_bucket",
":",
"# create new bucket entry",
"symbol",
"=",
"self",
".",
"sym_gen",
"(",
"key",
")",
"execgrp",
"=",
"DataParallelExecutorGroup",
"(",
"symbol",
",",
"self",
".",
"arg_names",
",",
"self",
".",
"param_names",
",",
"self",
".",
"ctx",
",",
"self",
".",
"slices",
",",
"data_batch",
",",
"shared_group",
"=",
"self",
".",
"execgrp",
")",
"self",
".",
"execgrp_bucket",
"[",
"key",
"]",
"=",
"execgrp",
"self",
".",
"curr_execgrp",
"=",
"self",
".",
"execgrp_bucket",
"[",
"key",
"]",
"else",
":",
"self",
".",
"curr_execgrp",
"=",
"self",
".",
"execgrp",
"self",
".",
"curr_execgrp",
".",
"load_data_batch",
"(",
"data_batch",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/executor_manager.py#L364-L381 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/connection.py | python | HTTPConnection.host | (self, value) | Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit. | Setter for the `host` property. | [
"Setter",
"for",
"the",
"host",
"property",
"."
] | def host(self, value):
"""
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit.
"""
self._dns_host = value | [
"def",
"host",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_dns_host",
"=",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/connection.py#L134-L141 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/retdec-3.2/scripts/type_extractor/type_extractor/parse_structs_unions.py | python | CompositeType.members_list | (self) | return self.members if self.members is not None else [] | Returns list of type's parameters. | Returns list of type's parameters. | [
"Returns",
"list",
"of",
"type",
"s",
"parameters",
"."
] | def members_list(self):
"""Returns list of type's parameters."""
return self.members if self.members is not None else [] | [
"def",
"members_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"members",
"if",
"self",
".",
"members",
"is",
"not",
"None",
"else",
"[",
"]"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/type_extractor/parse_structs_unions.py#L37-L39 | |
zeroc-ice/ice | 6df7df6039674d58fb5ab9a08e46f28591a210f7 | config/makeprops.py | python | PropertyHandler.deprecatedImpl | (self, propertyName) | Needs to be overridden in derived class | Needs to be overridden in derived class | [
"Needs",
"to",
"be",
"overridden",
"in",
"derived",
"class"
] | def deprecatedImpl(self, propertyName):
"""Needs to be overridden in derived class"""
pass | [
"def",
"deprecatedImpl",
"(",
"self",
",",
"propertyName",
")",
":",
"pass"
] | https://github.com/zeroc-ice/ice/blob/6df7df6039674d58fb5ab9a08e46f28591a210f7/config/makeprops.py#L222-L224 | ||
toggl-open-source/toggldesktop | 91865205885531cc8fd9e8d613dad49d625d56e7 | third_party/jsoncpp/scons-tools/srcdist.py | python | generate | (env) | Add builders and construction variables for the
SrcDist tool. | Add builders and construction variables for the
SrcDist tool. | [
"Add",
"builders",
"and",
"construction",
"variables",
"for",
"the",
"SrcDist",
"tool",
"."
] | def generate(env):
"""
Add builders and construction variables for the
SrcDist tool.
"""
## doxyfile_scanner = env.Scanner(
## DoxySourceScan,
## "DoxySourceScan",
## scan_check = DoxySourceScanCheck,
## )
if targz.exists(env):
srcdist_builder = targz.makeBuilder( srcDistEmitter )
env['BUILDERS']['SrcDist'] = srcdist_builder | [
"def",
"generate",
"(",
"env",
")",
":",
"## doxyfile_scanner = env.Scanner(",
"## DoxySourceScan,",
"## \"DoxySourceScan\",",
"## scan_check = DoxySourceScanCheck,",
"## )",
"if",
"targz",
".",
"exists",
"(",
"env",
")",
":",
"srcdist_builder",
"=",
"targz",
".",
"makeBuilder",
"(",
"srcDistEmitter",
")",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'SrcDist'",
"]",
"=",
"srcdist_builder"
] | https://github.com/toggl-open-source/toggldesktop/blob/91865205885531cc8fd9e8d613dad49d625d56e7/third_party/jsoncpp/scons-tools/srcdist.py#L159-L173 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/MSVSVersion.py | python | VisualStudioVersion._SetupScriptInternal | (self, target_arch) | Returns a command (with arguments) to be used to set up the
environment. | Returns a command (with arguments) to be used to set up the
environment. | [
"Returns",
"a",
"command",
"(",
"with",
"arguments",
")",
"to",
"be",
"used",
"to",
"set",
"up",
"the",
"environment",
"."
] | def _SetupScriptInternal(self, target_arch):
"""Returns a command (with arguments) to be used to set up the
environment."""
assert target_arch in ('x86', 'x64'), "target_arch not supported"
# If WindowsSDKDir is set and SetEnv.Cmd exists then we are using the
# depot_tools build tools and should run SetEnv.Cmd to set up the
# environment. The check for WindowsSDKDir alone is not sufficient because
# this is set by running vcvarsall.bat.
sdk_dir = os.environ.get('WindowsSDKDir', '')
setup_path = JoinPath(sdk_dir, 'Bin', 'SetEnv.Cmd')
if self.sdk_based and sdk_dir and os.path.exists(setup_path):
return [setup_path, '/' + target_arch]
is_host_arch_x64 = (
os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64' or
os.environ.get('PROCESSOR_ARCHITEW6432') == 'AMD64'
)
# For VS2017 (and newer) it's fairly easy
if self.short_name >= '2017':
script_path = JoinPath(self.path,
'VC', 'Auxiliary', 'Build', 'vcvarsall.bat')
# Always use a native executable, cross-compiling if necessary.
host_arch = 'amd64' if is_host_arch_x64 else 'x86'
msvc_target_arch = 'amd64' if target_arch == 'x64' else 'x86'
arg = host_arch
if host_arch != msvc_target_arch:
arg += '_' + msvc_target_arch
return [script_path, arg]
# We try to find the best version of the env setup batch.
vcvarsall = JoinPath(self.path, 'VC', 'vcvarsall.bat')
if target_arch == 'x86':
if self.short_name >= '2013' and self.short_name[-1] != 'e' and \
is_host_arch_x64:
# VS2013 and later, non-Express have a x64-x86 cross that we want
# to prefer.
return [vcvarsall, 'amd64_x86']
else:
# Otherwise, the standard x86 compiler. We don't use VC/vcvarsall.bat
# for x86 because vcvarsall calls vcvars32, which it can only find if
# VS??COMNTOOLS is set, which isn't guaranteed.
return [JoinPath(self.path, 'Common7', 'Tools', 'vsvars32.bat')]
elif target_arch == 'x64':
arg = 'x86_amd64'
# Use the 64-on-64 compiler if we're not using an express edition and
# we're running on a 64bit OS.
if self.short_name[-1] != 'e' and is_host_arch_x64:
arg = 'amd64'
return [vcvarsall, arg] | [
"def",
"_SetupScriptInternal",
"(",
"self",
",",
"target_arch",
")",
":",
"assert",
"target_arch",
"in",
"(",
"'x86'",
",",
"'x64'",
")",
",",
"\"target_arch not supported\"",
"# If WindowsSDKDir is set and SetEnv.Cmd exists then we are using the",
"# depot_tools build tools and should run SetEnv.Cmd to set up the",
"# environment. The check for WindowsSDKDir alone is not sufficient because",
"# this is set by running vcvarsall.bat.",
"sdk_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'WindowsSDKDir'",
",",
"''",
")",
"setup_path",
"=",
"JoinPath",
"(",
"sdk_dir",
",",
"'Bin'",
",",
"'SetEnv.Cmd'",
")",
"if",
"self",
".",
"sdk_based",
"and",
"sdk_dir",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"setup_path",
")",
":",
"return",
"[",
"setup_path",
",",
"'/'",
"+",
"target_arch",
"]",
"is_host_arch_x64",
"=",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'PROCESSOR_ARCHITECTURE'",
")",
"==",
"'AMD64'",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'PROCESSOR_ARCHITEW6432'",
")",
"==",
"'AMD64'",
")",
"# For VS2017 (and newer) it's fairly easy",
"if",
"self",
".",
"short_name",
">=",
"'2017'",
":",
"script_path",
"=",
"JoinPath",
"(",
"self",
".",
"path",
",",
"'VC'",
",",
"'Auxiliary'",
",",
"'Build'",
",",
"'vcvarsall.bat'",
")",
"# Always use a native executable, cross-compiling if necessary.",
"host_arch",
"=",
"'amd64'",
"if",
"is_host_arch_x64",
"else",
"'x86'",
"msvc_target_arch",
"=",
"'amd64'",
"if",
"target_arch",
"==",
"'x64'",
"else",
"'x86'",
"arg",
"=",
"host_arch",
"if",
"host_arch",
"!=",
"msvc_target_arch",
":",
"arg",
"+=",
"'_'",
"+",
"msvc_target_arch",
"return",
"[",
"script_path",
",",
"arg",
"]",
"# We try to find the best version of the env setup batch.",
"vcvarsall",
"=",
"JoinPath",
"(",
"self",
".",
"path",
",",
"'VC'",
",",
"'vcvarsall.bat'",
")",
"if",
"target_arch",
"==",
"'x86'",
":",
"if",
"self",
".",
"short_name",
">=",
"'2013'",
"and",
"self",
".",
"short_name",
"[",
"-",
"1",
"]",
"!=",
"'e'",
"and",
"is_host_arch_x64",
":",
"# VS2013 and later, non-Express have a x64-x86 cross that we want",
"# to prefer.",
"return",
"[",
"vcvarsall",
",",
"'amd64_x86'",
"]",
"else",
":",
"# Otherwise, the standard x86 compiler. We don't use VC/vcvarsall.bat",
"# for x86 because vcvarsall calls vcvars32, which it can only find if",
"# VS??COMNTOOLS is set, which isn't guaranteed.",
"return",
"[",
"JoinPath",
"(",
"self",
".",
"path",
",",
"'Common7'",
",",
"'Tools'",
",",
"'vsvars32.bat'",
")",
"]",
"elif",
"target_arch",
"==",
"'x64'",
":",
"arg",
"=",
"'x86_amd64'",
"# Use the 64-on-64 compiler if we're not using an express edition and",
"# we're running on a 64bit OS.",
"if",
"self",
".",
"short_name",
"[",
"-",
"1",
"]",
"!=",
"'e'",
"and",
"is_host_arch_x64",
":",
"arg",
"=",
"'amd64'",
"return",
"[",
"vcvarsall",
",",
"arg",
"]"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/MSVSVersion.py#L81-L132 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/layers/python/layers/optimizers.py | python | optimize_loss | (loss,
global_step,
learning_rate,
optimizer,
gradient_noise_scale=None,
gradient_multipliers=None,
clip_gradients=None,
learning_rate_decay_fn=None,
update_ops=None,
variables=None,
name=None,
summaries=None,
colocate_gradients_with_ops=False) | Given loss and parameters for optimizer, returns a training op.
Various ways of passing optimizers, include:
- string, name of the optimizer like 'SGD', 'Adam', see OPTIMIZER_CLS_NAMES
for full list. E.g. `optimize_loss(..., optimizer='Adam')`.
- function, takes learning rate `Tensor` as argument and must return
`Optimizer` instance. E.g. `optimize_loss(...,
optimizer=lambda lr: tf.train.MomentumOptimizer(lr, momentum=0.5))`.
Alternatively, if `learning_rate` is `None`, the function takes no
arguments. E.g. `optimize_loss(..., learning_rate=None,
optimizer=lambda: tf.train.MomentumOptimizer(0.5, momentum=0.5))`.
- class, subclass of `Optimizer` that takes only one required argument -
learning rate, such as AdamOptimizer, AdagradOptimizer.
E.g. `optimize_loss(..., optimizer=tf.train.AdagradOptimizer)`.
- object, instance of subclass of `Optimizer`.
E.g., `optimizer_loss(..., optimizer=tf.train.AdagradOptimizer(0.5))`.
Args:
loss: Tensor, 0 dimensional.
global_step: Tensor, step counter for each update.
learning_rate: float or Tensor, magnitude of update per each training step.
optimizer: string, class or optimizer instance, used as trainer.
string should be name of optimizer, like 'SGD',
'Adam', 'Adagrad'. Full list in OPTIMIZER_CLS_NAMES constant.
class should be sub-class of `tf.Optimizer` that implements
`compute_gradients` and `apply_gradients` functions.
optimizer instance should be instantiation of `tf.Optimizer`
sub-class and have `compute_gradients` and `apply_gradients`
functions.
gradient_noise_scale: float or None, adds 0-mean normal noise scaled by this
value.
gradient_multipliers: dict of variables or variable names to floats.
If present, gradients for specified
variables will be multiplied by given constant.
clip_gradients: float or `None`, clips gradients by this value.
learning_rate_decay_fn: function, takes `learning_rate` and `global_step`
`Tensor`s, returns `Tensor`.
Can be used to implement any learning rate decay
functions.
For example: `tf.train.exponential_decay`.
update_ops: list of update `Operation`s to execute at each step. If `None`,
uses elements of UPDATE_OPS collection. The order of execution
between `update_ops` and `loss` is non-deterministic.
variables: list of variables to optimize or
`None` to use all trainable variables.
name: The name for this operation is used to scope operations and summaries.
summaries: List of internal quantities to visualize on tensorboard. If not
set only the loss and the learning rate will be reported. The
complete list is in OPTIMIZER_SUMMARIES.
colocate_gradients_with_ops: If True, try colocating gradients with the
corresponding op.
Returns:
Training op.
Raises:
ValueError: if optimizer is wrong type. | Given loss and parameters for optimizer, returns a training op. | [
"Given",
"loss",
"and",
"parameters",
"for",
"optimizer",
"returns",
"a",
"training",
"op",
"."
] | def optimize_loss(loss,
global_step,
learning_rate,
optimizer,
gradient_noise_scale=None,
gradient_multipliers=None,
clip_gradients=None,
learning_rate_decay_fn=None,
update_ops=None,
variables=None,
name=None,
summaries=None,
colocate_gradients_with_ops=False):
"""Given loss and parameters for optimizer, returns a training op.
Various ways of passing optimizers, include:
- string, name of the optimizer like 'SGD', 'Adam', see OPTIMIZER_CLS_NAMES
for full list. E.g. `optimize_loss(..., optimizer='Adam')`.
- function, takes learning rate `Tensor` as argument and must return
`Optimizer` instance. E.g. `optimize_loss(...,
optimizer=lambda lr: tf.train.MomentumOptimizer(lr, momentum=0.5))`.
Alternatively, if `learning_rate` is `None`, the function takes no
arguments. E.g. `optimize_loss(..., learning_rate=None,
optimizer=lambda: tf.train.MomentumOptimizer(0.5, momentum=0.5))`.
- class, subclass of `Optimizer` that takes only one required argument -
learning rate, such as AdamOptimizer, AdagradOptimizer.
E.g. `optimize_loss(..., optimizer=tf.train.AdagradOptimizer)`.
- object, instance of subclass of `Optimizer`.
E.g., `optimizer_loss(..., optimizer=tf.train.AdagradOptimizer(0.5))`.
Args:
loss: Tensor, 0 dimensional.
global_step: Tensor, step counter for each update.
learning_rate: float or Tensor, magnitude of update per each training step.
optimizer: string, class or optimizer instance, used as trainer.
string should be name of optimizer, like 'SGD',
'Adam', 'Adagrad'. Full list in OPTIMIZER_CLS_NAMES constant.
class should be sub-class of `tf.Optimizer` that implements
`compute_gradients` and `apply_gradients` functions.
optimizer instance should be instantiation of `tf.Optimizer`
sub-class and have `compute_gradients` and `apply_gradients`
functions.
gradient_noise_scale: float or None, adds 0-mean normal noise scaled by this
value.
gradient_multipliers: dict of variables or variable names to floats.
If present, gradients for specified
variables will be multiplied by given constant.
clip_gradients: float or `None`, clips gradients by this value.
learning_rate_decay_fn: function, takes `learning_rate` and `global_step`
`Tensor`s, returns `Tensor`.
Can be used to implement any learning rate decay
functions.
For example: `tf.train.exponential_decay`.
update_ops: list of update `Operation`s to execute at each step. If `None`,
uses elements of UPDATE_OPS collection. The order of execution
between `update_ops` and `loss` is non-deterministic.
variables: list of variables to optimize or
`None` to use all trainable variables.
name: The name for this operation is used to scope operations and summaries.
summaries: List of internal quantities to visualize on tensorboard. If not
set only the loss and the learning rate will be reported. The
complete list is in OPTIMIZER_SUMMARIES.
colocate_gradients_with_ops: If True, try colocating gradients with the
corresponding op.
Returns:
Training op.
Raises:
ValueError: if optimizer is wrong type.
"""
with vs.variable_scope(name, "OptimizeLoss", [loss, global_step]):
# Update ops take UPDATE_OPS collection if not provided.
if update_ops is None:
update_ops = set(ops.get_collection(ops.GraphKeys.UPDATE_OPS))
# Make sure update ops are ran before computing loss.
if update_ops:
loss = control_flow_ops.with_dependencies(list(update_ops), loss)
# Learning rate variable, with possible decay.
lr = None
if learning_rate is not None:
if (isinstance(learning_rate, ops.Tensor)
and learning_rate.get_shape().ndims == 0):
lr = learning_rate
elif isinstance(learning_rate, float):
lr = vs.get_variable(
"learning_rate", [], trainable=False,
initializer=init_ops.constant_initializer(learning_rate))
else:
raise ValueError("Learning rate should be 0d Tensor or float. "
"Got %s of type %s" % (
str(learning_rate), str(type(learning_rate))))
if summaries is None:
summaries = ["loss", "learning_rate"]
if learning_rate is not None and learning_rate_decay_fn is not None:
lr = learning_rate_decay_fn(lr, global_step)
if "learning_rate" in summaries:
logging_ops.scalar_summary("learning_rate", lr)
# Create optimizer, given specified parameters.
if isinstance(optimizer, six.string_types):
if lr is None:
raise ValueError("Learning rate is None, but should be specified if "
"optimizer is string (%s)." % optimizer)
if optimizer not in OPTIMIZER_CLS_NAMES:
raise ValueError(
"Optimizer name should be one of [%s], you provided %s."
% (", ".join(OPTIMIZER_CLS_NAMES), optimizer))
opt = OPTIMIZER_CLS_NAMES[optimizer](learning_rate=lr)
elif (isinstance(optimizer, type)
and issubclass(optimizer, optimizer_.Optimizer)):
if lr is None:
raise ValueError("Learning rate is None, but should be specified if "
"optimizer is class (%s)." % optimizer)
opt = optimizer(learning_rate=lr)
elif isinstance(optimizer, optimizer_.Optimizer):
opt = optimizer
elif callable(optimizer):
if learning_rate is not None:
opt = optimizer(lr)
else:
opt = optimizer()
if not isinstance(opt, optimizer_.Optimizer):
raise ValueError("Unrecognized optimizer: function should return "
"subclass of Optimizer. Got %s." % str(opt))
else:
raise ValueError("Unrecognized optimizer: should be string, "
"subclass of Optimizer, instance of "
"subclass of Optimizer or function with one argument. "
"Got %s." % str(optimizer))
# All trainable variables, if specific variables are not specified.
if variables is None:
variables = vars_.trainable_variables()
# Compute gradients.
gradients = opt.compute_gradients(loss, variables,
colocate_gradients_with_ops=colocate_gradients_with_ops)
# Optionally add gradient noise.
if gradient_noise_scale is not None:
gradients = _add_scaled_noise_to_gradients(
gradients, gradient_noise_scale)
# Multiply some gradients.
if gradient_multipliers is not None:
gradients = _multiply_gradients(gradients, gradient_multipliers)
# Optionally clip gradients by global norm.
if clip_gradients is not None:
gradients = _clip_gradients_by_norm(gradients, clip_gradients)
# Add scalar summary for loss.
if "loss" in summaries:
logging_ops.scalar_summary("loss", loss)
# Add histograms for variables, gradients and gradient norms.
for gradient, variable in gradients:
if isinstance(gradient, ops.IndexedSlices):
grad_values = gradient.values
else:
grad_values = gradient
if grad_values is not None:
if "gradients" in summaries:
logging_ops.histogram_summary(variable.name + "/gradients",
grad_values)
if "gradient_norm" in summaries:
logging_ops.histogram_summary(variable.name + "/gradient_norm",
clip_ops.global_norm([grad_values]))
# Create gradient updates.
grad_updates = opt.apply_gradients(gradients,
global_step=global_step,
name="train")
# Ensure the train_tensor computes grad_updates.
train_tensor = control_flow_ops.with_dependencies([grad_updates], loss)
return train_tensor | [
"def",
"optimize_loss",
"(",
"loss",
",",
"global_step",
",",
"learning_rate",
",",
"optimizer",
",",
"gradient_noise_scale",
"=",
"None",
",",
"gradient_multipliers",
"=",
"None",
",",
"clip_gradients",
"=",
"None",
",",
"learning_rate_decay_fn",
"=",
"None",
",",
"update_ops",
"=",
"None",
",",
"variables",
"=",
"None",
",",
"name",
"=",
"None",
",",
"summaries",
"=",
"None",
",",
"colocate_gradients_with_ops",
"=",
"False",
")",
":",
"with",
"vs",
".",
"variable_scope",
"(",
"name",
",",
"\"OptimizeLoss\"",
",",
"[",
"loss",
",",
"global_step",
"]",
")",
":",
"# Update ops take UPDATE_OPS collection if not provided.",
"if",
"update_ops",
"is",
"None",
":",
"update_ops",
"=",
"set",
"(",
"ops",
".",
"get_collection",
"(",
"ops",
".",
"GraphKeys",
".",
"UPDATE_OPS",
")",
")",
"# Make sure update ops are ran before computing loss.",
"if",
"update_ops",
":",
"loss",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"list",
"(",
"update_ops",
")",
",",
"loss",
")",
"# Learning rate variable, with possible decay.",
"lr",
"=",
"None",
"if",
"learning_rate",
"is",
"not",
"None",
":",
"if",
"(",
"isinstance",
"(",
"learning_rate",
",",
"ops",
".",
"Tensor",
")",
"and",
"learning_rate",
".",
"get_shape",
"(",
")",
".",
"ndims",
"==",
"0",
")",
":",
"lr",
"=",
"learning_rate",
"elif",
"isinstance",
"(",
"learning_rate",
",",
"float",
")",
":",
"lr",
"=",
"vs",
".",
"get_variable",
"(",
"\"learning_rate\"",
",",
"[",
"]",
",",
"trainable",
"=",
"False",
",",
"initializer",
"=",
"init_ops",
".",
"constant_initializer",
"(",
"learning_rate",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Learning rate should be 0d Tensor or float. \"",
"\"Got %s of type %s\"",
"%",
"(",
"str",
"(",
"learning_rate",
")",
",",
"str",
"(",
"type",
"(",
"learning_rate",
")",
")",
")",
")",
"if",
"summaries",
"is",
"None",
":",
"summaries",
"=",
"[",
"\"loss\"",
",",
"\"learning_rate\"",
"]",
"if",
"learning_rate",
"is",
"not",
"None",
"and",
"learning_rate_decay_fn",
"is",
"not",
"None",
":",
"lr",
"=",
"learning_rate_decay_fn",
"(",
"lr",
",",
"global_step",
")",
"if",
"\"learning_rate\"",
"in",
"summaries",
":",
"logging_ops",
".",
"scalar_summary",
"(",
"\"learning_rate\"",
",",
"lr",
")",
"# Create optimizer, given specified parameters.",
"if",
"isinstance",
"(",
"optimizer",
",",
"six",
".",
"string_types",
")",
":",
"if",
"lr",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Learning rate is None, but should be specified if \"",
"\"optimizer is string (%s).\"",
"%",
"optimizer",
")",
"if",
"optimizer",
"not",
"in",
"OPTIMIZER_CLS_NAMES",
":",
"raise",
"ValueError",
"(",
"\"Optimizer name should be one of [%s], you provided %s.\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"OPTIMIZER_CLS_NAMES",
")",
",",
"optimizer",
")",
")",
"opt",
"=",
"OPTIMIZER_CLS_NAMES",
"[",
"optimizer",
"]",
"(",
"learning_rate",
"=",
"lr",
")",
"elif",
"(",
"isinstance",
"(",
"optimizer",
",",
"type",
")",
"and",
"issubclass",
"(",
"optimizer",
",",
"optimizer_",
".",
"Optimizer",
")",
")",
":",
"if",
"lr",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Learning rate is None, but should be specified if \"",
"\"optimizer is class (%s).\"",
"%",
"optimizer",
")",
"opt",
"=",
"optimizer",
"(",
"learning_rate",
"=",
"lr",
")",
"elif",
"isinstance",
"(",
"optimizer",
",",
"optimizer_",
".",
"Optimizer",
")",
":",
"opt",
"=",
"optimizer",
"elif",
"callable",
"(",
"optimizer",
")",
":",
"if",
"learning_rate",
"is",
"not",
"None",
":",
"opt",
"=",
"optimizer",
"(",
"lr",
")",
"else",
":",
"opt",
"=",
"optimizer",
"(",
")",
"if",
"not",
"isinstance",
"(",
"opt",
",",
"optimizer_",
".",
"Optimizer",
")",
":",
"raise",
"ValueError",
"(",
"\"Unrecognized optimizer: function should return \"",
"\"subclass of Optimizer. Got %s.\"",
"%",
"str",
"(",
"opt",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unrecognized optimizer: should be string, \"",
"\"subclass of Optimizer, instance of \"",
"\"subclass of Optimizer or function with one argument. \"",
"\"Got %s.\"",
"%",
"str",
"(",
"optimizer",
")",
")",
"# All trainable variables, if specific variables are not specified.",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"vars_",
".",
"trainable_variables",
"(",
")",
"# Compute gradients.",
"gradients",
"=",
"opt",
".",
"compute_gradients",
"(",
"loss",
",",
"variables",
",",
"colocate_gradients_with_ops",
"=",
"colocate_gradients_with_ops",
")",
"# Optionally add gradient noise.",
"if",
"gradient_noise_scale",
"is",
"not",
"None",
":",
"gradients",
"=",
"_add_scaled_noise_to_gradients",
"(",
"gradients",
",",
"gradient_noise_scale",
")",
"# Multiply some gradients.",
"if",
"gradient_multipliers",
"is",
"not",
"None",
":",
"gradients",
"=",
"_multiply_gradients",
"(",
"gradients",
",",
"gradient_multipliers",
")",
"# Optionally clip gradients by global norm.",
"if",
"clip_gradients",
"is",
"not",
"None",
":",
"gradients",
"=",
"_clip_gradients_by_norm",
"(",
"gradients",
",",
"clip_gradients",
")",
"# Add scalar summary for loss.",
"if",
"\"loss\"",
"in",
"summaries",
":",
"logging_ops",
".",
"scalar_summary",
"(",
"\"loss\"",
",",
"loss",
")",
"# Add histograms for variables, gradients and gradient norms.",
"for",
"gradient",
",",
"variable",
"in",
"gradients",
":",
"if",
"isinstance",
"(",
"gradient",
",",
"ops",
".",
"IndexedSlices",
")",
":",
"grad_values",
"=",
"gradient",
".",
"values",
"else",
":",
"grad_values",
"=",
"gradient",
"if",
"grad_values",
"is",
"not",
"None",
":",
"if",
"\"gradients\"",
"in",
"summaries",
":",
"logging_ops",
".",
"histogram_summary",
"(",
"variable",
".",
"name",
"+",
"\"/gradients\"",
",",
"grad_values",
")",
"if",
"\"gradient_norm\"",
"in",
"summaries",
":",
"logging_ops",
".",
"histogram_summary",
"(",
"variable",
".",
"name",
"+",
"\"/gradient_norm\"",
",",
"clip_ops",
".",
"global_norm",
"(",
"[",
"grad_values",
"]",
")",
")",
"# Create gradient updates.",
"grad_updates",
"=",
"opt",
".",
"apply_gradients",
"(",
"gradients",
",",
"global_step",
"=",
"global_step",
",",
"name",
"=",
"\"train\"",
")",
"# Ensure the train_tensor computes grad_updates.",
"train_tensor",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"grad_updates",
"]",
",",
"loss",
")",
"return",
"train_tensor"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/optimizers.py#L53-L234 | ||
tiny-dnn/tiny-dnn | c0f576f5cb7b35893f62127cb7aec18f77a3bcc5 | third_party/cpplint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
TODO(unknown): cpplint spends a fair bit of time matching parentheses.
Ideally we would want to index all opening and closing parentheses once
and have CloseExpression be just a simple lookup, but due to preprocessor
tricks, this is not so easy.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [ or <, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"or",
"<",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
TODO(unknown): cpplint spends a fair bit of time matching parentheses.
Ideally we would want to index all opening and closing parentheses once
and have CloseExpression be just a simple lookup, but due to preprocessor
tricks, this is not so easy.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
return (line, clean_lines.NumLines(), -1)
# Check first line
(end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while stack and linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find end of expression before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"(",
"line",
"[",
"pos",
"]",
"not",
"in",
"'({[<'",
")",
"or",
"Match",
"(",
"r'<[<=]'",
",",
"line",
"[",
"pos",
":",
"]",
")",
":",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")",
"# Check first line",
"(",
"end_pos",
",",
"stack",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"pos",
",",
"[",
"]",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Continue scanning forward",
"while",
"stack",
"and",
"linenum",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
"-",
"1",
":",
"linenum",
"+=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"(",
"end_pos",
",",
"stack",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"0",
",",
"stack",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Did not find end of expression before end of file, give up",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")"
] | https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L1767-L1808 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/interpreter.py | python | Interpreter.op_END_FINALLY | (self, inst) | no-op | no-op | [
"no",
"-",
"op"
] | def op_END_FINALLY(self, inst):
"no-op" | [
"def",
"op_END_FINALLY",
"(",
"self",
",",
"inst",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/interpreter.py#L794-L795 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | ext/ply/example/GardenSnake/GardenSnake.py | python | p_small_stmt | (p) | small_stmt : flow_stmt
| expr_stmt | small_stmt : flow_stmt
| expr_stmt | [
"small_stmt",
":",
"flow_stmt",
"|",
"expr_stmt"
] | def p_small_stmt(p):
"""small_stmt : flow_stmt
| expr_stmt"""
p[0] = p[1] | [
"def",
"p_small_stmt",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/GardenSnake/GardenSnake.py#L433-L436 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/loss/loss.py | python | DiceLoss.__init__ | (self, smooth=1e-5) | Initialize DiceLoss. | Initialize DiceLoss. | [
"Initialize",
"DiceLoss",
"."
] | def __init__(self, smooth=1e-5):
"""Initialize DiceLoss."""
super(DiceLoss, self).__init__()
self.smooth = validator.check_positive_float(smooth, "smooth")
self.reshape = P.Reshape() | [
"def",
"__init__",
"(",
"self",
",",
"smooth",
"=",
"1e-5",
")",
":",
"super",
"(",
"DiceLoss",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"smooth",
"=",
"validator",
".",
"check_positive_float",
"(",
"smooth",
",",
"\"smooth\"",
")",
"self",
".",
"reshape",
"=",
"P",
".",
"Reshape",
"(",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/loss/loss.py#L678-L682 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py | python | ZipInfo.FileHeader | (self, zip64=None) | return header + filename + extra | Return the per-file header as a string. | Return the per-file header as a string. | [
"Return",
"the",
"per",
"-",
"file",
"header",
"as",
"a",
"string",
"."
] | def FileHeader(self, zip64=None):
"""Return the per-file header as a string."""
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them after the file data
CRC = compress_size = file_size = 0
else:
CRC = self.CRC
compress_size = self.compress_size
file_size = self.file_size
extra = self.extra
if zip64 is None:
zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT
if zip64:
fmt = '<HHQQ'
extra = extra + struct.pack(fmt,
1, struct.calcsize(fmt)-4, file_size, compress_size)
if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
if not zip64:
raise LargeZipFile("Filesize would require ZIP64 extensions")
# File is larger than what fits into a 4 byte integer,
# fall back to the ZIP64 extension
file_size = 0xffffffff
compress_size = 0xffffffff
self.extract_version = max(45, self.extract_version)
self.create_version = max(45, self.extract_version)
filename, flag_bits = self._encodeFilenameFlags()
header = struct.pack(structFileHeader, stringFileHeader,
self.extract_version, self.reserved, flag_bits,
self.compress_type, dostime, dosdate, CRC,
compress_size, file_size,
len(filename), len(extra))
return header + filename + extra | [
"def",
"FileHeader",
"(",
"self",
",",
"zip64",
"=",
"None",
")",
":",
"dt",
"=",
"self",
".",
"date_time",
"dosdate",
"=",
"(",
"dt",
"[",
"0",
"]",
"-",
"1980",
")",
"<<",
"9",
"|",
"dt",
"[",
"1",
"]",
"<<",
"5",
"|",
"dt",
"[",
"2",
"]",
"dostime",
"=",
"dt",
"[",
"3",
"]",
"<<",
"11",
"|",
"dt",
"[",
"4",
"]",
"<<",
"5",
"|",
"(",
"dt",
"[",
"5",
"]",
"//",
"2",
")",
"if",
"self",
".",
"flag_bits",
"&",
"0x08",
":",
"# Set these to zero because we write them after the file data",
"CRC",
"=",
"compress_size",
"=",
"file_size",
"=",
"0",
"else",
":",
"CRC",
"=",
"self",
".",
"CRC",
"compress_size",
"=",
"self",
".",
"compress_size",
"file_size",
"=",
"self",
".",
"file_size",
"extra",
"=",
"self",
".",
"extra",
"if",
"zip64",
"is",
"None",
":",
"zip64",
"=",
"file_size",
">",
"ZIP64_LIMIT",
"or",
"compress_size",
">",
"ZIP64_LIMIT",
"if",
"zip64",
":",
"fmt",
"=",
"'<HHQQ'",
"extra",
"=",
"extra",
"+",
"struct",
".",
"pack",
"(",
"fmt",
",",
"1",
",",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"-",
"4",
",",
"file_size",
",",
"compress_size",
")",
"if",
"file_size",
">",
"ZIP64_LIMIT",
"or",
"compress_size",
">",
"ZIP64_LIMIT",
":",
"if",
"not",
"zip64",
":",
"raise",
"LargeZipFile",
"(",
"\"Filesize would require ZIP64 extensions\"",
")",
"# File is larger than what fits into a 4 byte integer,",
"# fall back to the ZIP64 extension",
"file_size",
"=",
"0xffffffff",
"compress_size",
"=",
"0xffffffff",
"self",
".",
"extract_version",
"=",
"max",
"(",
"45",
",",
"self",
".",
"extract_version",
")",
"self",
".",
"create_version",
"=",
"max",
"(",
"45",
",",
"self",
".",
"extract_version",
")",
"filename",
",",
"flag_bits",
"=",
"self",
".",
"_encodeFilenameFlags",
"(",
")",
"header",
"=",
"struct",
".",
"pack",
"(",
"structFileHeader",
",",
"stringFileHeader",
",",
"self",
".",
"extract_version",
",",
"self",
".",
"reserved",
",",
"flag_bits",
",",
"self",
".",
"compress_type",
",",
"dostime",
",",
"dosdate",
",",
"CRC",
",",
"compress_size",
",",
"file_size",
",",
"len",
"(",
"filename",
")",
",",
"len",
"(",
"extra",
")",
")",
"return",
"header",
"+",
"filename",
"+",
"extra"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py#L329-L366 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/isapi/install.py | python | MergeStandardOptions | (options, params) | Take an options object generated by the command line and merge
the values into the IISParameters object. | Take an options object generated by the command line and merge
the values into the IISParameters object. | [
"Take",
"an",
"options",
"object",
"generated",
"by",
"the",
"command",
"line",
"and",
"merge",
"the",
"values",
"into",
"the",
"IISParameters",
"object",
"."
] | def MergeStandardOptions(options, params):
"""
Take an options object generated by the command line and merge
the values into the IISParameters object.
"""
pass | [
"def",
"MergeStandardOptions",
"(",
"options",
",",
"params",
")",
":",
"pass"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/isapi/install.py#L640-L645 | ||
smartdevicelink/sdl_core | 68f082169e0a40fccd9eb0db3c83911c28870f07 | tools/InterfaceGenerator/generator/parsers/JSONRPC.py | python | Parser.__init__ | (self) | Constructor. | Constructor. | [
"Constructor",
"."
] | def __init__(self):
"""Constructor."""
super(Parser, self).__init__()
self._interface_name = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"Parser",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_interface_name",
"=",
"None"
] | https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/InterfaceGenerator/generator/parsers/JSONRPC.py#L18-L21 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/common/exceptions.py | python | MooseDocsException.message | (self) | return self.__message | Return the message supplied to the constructor. | Return the message supplied to the constructor. | [
"Return",
"the",
"message",
"supplied",
"to",
"the",
"constructor",
"."
] | def message(self):
"""Return the message supplied to the constructor."""
return self.__message | [
"def",
"message",
"(",
"self",
")",
":",
"return",
"self",
".",
"__message"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/common/exceptions.py#L31-L33 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/tools/tensorflow_builder/config_detector/config_detector.py | python | manage_all_configs | (save_results, filename) | Manages configuration detection and retrieval based on user input.
Args:
save_results: Boolean indicating whether to save the results to a file.
filename: String that is the name of the output JSON file. | Manages configuration detection and retrieval based on user input. | [
"Manages",
"configuration",
"detection",
"and",
"retrieval",
"based",
"on",
"user",
"input",
"."
] | def manage_all_configs(save_results, filename):
"""Manages configuration detection and retrieval based on user input.
Args:
save_results: Boolean indicating whether to save the results to a file.
filename: String that is the name of the output JSON file.
"""
# Get all configs
all_configs = get_all_configs()
# Print all configs based on user input
print_all_configs(all_configs[0], all_configs[1], all_configs[2])
# Save all configs to a file based on user request
if save_results:
save_to_file(all_configs[3], filename) | [
"def",
"manage_all_configs",
"(",
"save_results",
",",
"filename",
")",
":",
"# Get all configs",
"all_configs",
"=",
"get_all_configs",
"(",
")",
"# Print all configs based on user input",
"print_all_configs",
"(",
"all_configs",
"[",
"0",
"]",
",",
"all_configs",
"[",
"1",
"]",
",",
"all_configs",
"[",
"2",
"]",
")",
"# Save all configs to a file based on user request",
"if",
"save_results",
":",
"save_to_file",
"(",
"all_configs",
"[",
"3",
"]",
",",
"filename",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/tools/tensorflow_builder/config_detector/config_detector.py#L637-L650 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/png/png.py | python | Reader.read | (self, lenient=False) | return self.width, self.height, pixels, meta | Read the PNG file and decode it. Returns (`width`, `height`,
`pixels`, `metadata`).
May use excessive memory.
`pixels` are returned in boxed row flat pixel format.
If the optional `lenient` argument evaluates to True,
checksum failures will raise warnings rather than exceptions. | Read the PNG file and decode it. Returns (`width`, `height`,
`pixels`, `metadata`). | [
"Read",
"the",
"PNG",
"file",
"and",
"decode",
"it",
".",
"Returns",
"(",
"width",
"height",
"pixels",
"metadata",
")",
"."
] | def read(self, lenient=False):
"""
Read the PNG file and decode it. Returns (`width`, `height`,
`pixels`, `metadata`).
May use excessive memory.
`pixels` are returned in boxed row flat pixel format.
If the optional `lenient` argument evaluates to True,
checksum failures will raise warnings rather than exceptions.
"""
def iteridat():
"""Iterator that yields all the ``IDAT`` chunks as strings."""
while True:
try:
type, data = self.chunk(lenient=lenient)
except ValueError, e:
raise ChunkError(e.args[0])
if type == 'IEND':
# http://www.w3.org/TR/PNG/#11IEND
break
if type != 'IDAT':
continue
# type == 'IDAT'
# http://www.w3.org/TR/PNG/#11IDAT
if self.colormap and not self.plte:
warnings.warn("PLTE chunk is required before IDAT chunk")
yield data
def iterdecomp(idat):
"""Iterator that yields decompressed strings. `idat` should
be an iterator that yields the ``IDAT`` chunk data.
"""
# Currently, with no max_length paramter to decompress, this
# routine will do one yield per IDAT chunk. So not very
# incremental.
d = zlib.decompressobj()
# Each IDAT chunk is passed to the decompressor, then any
# remaining state is decompressed out.
for data in idat:
# :todo: add a max_length argument here to limit output
# size.
yield array('B', d.decompress(data))
yield array('B', d.flush())
self.preamble(lenient=lenient)
raw = iterdecomp(iteridat())
if self.interlace:
raw = array('B', itertools.chain(*raw))
arraycode = 'BH'[self.bitdepth>8]
# Like :meth:`group` but producing an array.array object for
# each row.
pixels = itertools.imap(lambda *row: array(arraycode, row),
*[iter(self.deinterlace(raw))]*self.width*self.planes)
else:
pixels = self.iterboxed(self.iterstraight(raw))
meta = dict()
for attr in 'greyscale alpha planes bitdepth interlace'.split():
meta[attr] = getattr(self, attr)
meta['size'] = (self.width, self.height)
for attr in 'gamma transparent background'.split():
a = getattr(self, attr, None)
if a is not None:
meta[attr] = a
if self.plte:
meta['palette'] = self.palette()
return self.width, self.height, pixels, meta | [
"def",
"read",
"(",
"self",
",",
"lenient",
"=",
"False",
")",
":",
"def",
"iteridat",
"(",
")",
":",
"\"\"\"Iterator that yields all the ``IDAT`` chunks as strings.\"\"\"",
"while",
"True",
":",
"try",
":",
"type",
",",
"data",
"=",
"self",
".",
"chunk",
"(",
"lenient",
"=",
"lenient",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"ChunkError",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
"if",
"type",
"==",
"'IEND'",
":",
"# http://www.w3.org/TR/PNG/#11IEND",
"break",
"if",
"type",
"!=",
"'IDAT'",
":",
"continue",
"# type == 'IDAT'",
"# http://www.w3.org/TR/PNG/#11IDAT",
"if",
"self",
".",
"colormap",
"and",
"not",
"self",
".",
"plte",
":",
"warnings",
".",
"warn",
"(",
"\"PLTE chunk is required before IDAT chunk\"",
")",
"yield",
"data",
"def",
"iterdecomp",
"(",
"idat",
")",
":",
"\"\"\"Iterator that yields decompressed strings. `idat` should\n be an iterator that yields the ``IDAT`` chunk data.\n \"\"\"",
"# Currently, with no max_length paramter to decompress, this",
"# routine will do one yield per IDAT chunk. So not very",
"# incremental.",
"d",
"=",
"zlib",
".",
"decompressobj",
"(",
")",
"# Each IDAT chunk is passed to the decompressor, then any",
"# remaining state is decompressed out.",
"for",
"data",
"in",
"idat",
":",
"# :todo: add a max_length argument here to limit output",
"# size.",
"yield",
"array",
"(",
"'B'",
",",
"d",
".",
"decompress",
"(",
"data",
")",
")",
"yield",
"array",
"(",
"'B'",
",",
"d",
".",
"flush",
"(",
")",
")",
"self",
".",
"preamble",
"(",
"lenient",
"=",
"lenient",
")",
"raw",
"=",
"iterdecomp",
"(",
"iteridat",
"(",
")",
")",
"if",
"self",
".",
"interlace",
":",
"raw",
"=",
"array",
"(",
"'B'",
",",
"itertools",
".",
"chain",
"(",
"*",
"raw",
")",
")",
"arraycode",
"=",
"'BH'",
"[",
"self",
".",
"bitdepth",
">",
"8",
"]",
"# Like :meth:`group` but producing an array.array object for",
"# each row.",
"pixels",
"=",
"itertools",
".",
"imap",
"(",
"lambda",
"*",
"row",
":",
"array",
"(",
"arraycode",
",",
"row",
")",
",",
"*",
"[",
"iter",
"(",
"self",
".",
"deinterlace",
"(",
"raw",
")",
")",
"]",
"*",
"self",
".",
"width",
"*",
"self",
".",
"planes",
")",
"else",
":",
"pixels",
"=",
"self",
".",
"iterboxed",
"(",
"self",
".",
"iterstraight",
"(",
"raw",
")",
")",
"meta",
"=",
"dict",
"(",
")",
"for",
"attr",
"in",
"'greyscale alpha planes bitdepth interlace'",
".",
"split",
"(",
")",
":",
"meta",
"[",
"attr",
"]",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"meta",
"[",
"'size'",
"]",
"=",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"for",
"attr",
"in",
"'gamma transparent background'",
".",
"split",
"(",
")",
":",
"a",
"=",
"getattr",
"(",
"self",
",",
"attr",
",",
"None",
")",
"if",
"a",
"is",
"not",
"None",
":",
"meta",
"[",
"attr",
"]",
"=",
"a",
"if",
"self",
".",
"plte",
":",
"meta",
"[",
"'palette'",
"]",
"=",
"self",
".",
"palette",
"(",
")",
"return",
"self",
".",
"width",
",",
"self",
".",
"height",
",",
"pixels",
",",
"meta"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L1866-L1936 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/importDXF.py | python | decodeName | (name) | return decodedName | Decode the encoded name into utf8 or latin1.
Parameters
----------
name : str
The string to decode.
Returns
-------
str
The decoded string in utf8, latin1, or the original `name`
if the decoding was not needed, for example,
when using Python 3. | Decode the encoded name into utf8 or latin1. | [
"Decode",
"the",
"encoded",
"name",
"into",
"utf8",
"or",
"latin1",
"."
] | def decodeName(name):
"""Decode the encoded name into utf8 or latin1.
Parameters
----------
name : str
The string to decode.
Returns
-------
str
The decoded string in utf8, latin1, or the original `name`
if the decoding was not needed, for example,
when using Python 3.
"""
try:
decodedName = (name.decode("utf8"))
except UnicodeDecodeError:
try:
decodedName = (name.decode("latin1"))
except UnicodeDecodeError:
print("dxf: error: couldn't determine character encoding")
decodedName = name
except AttributeError:
# this is python3 (nothing to do)
decodedName = name
return decodedName | [
"def",
"decodeName",
"(",
"name",
")",
":",
"try",
":",
"decodedName",
"=",
"(",
"name",
".",
"decode",
"(",
"\"utf8\"",
")",
")",
"except",
"UnicodeDecodeError",
":",
"try",
":",
"decodedName",
"=",
"(",
"name",
".",
"decode",
"(",
"\"latin1\"",
")",
")",
"except",
"UnicodeDecodeError",
":",
"print",
"(",
"\"dxf: error: couldn't determine character encoding\"",
")",
"decodedName",
"=",
"name",
"except",
"AttributeError",
":",
"# this is python3 (nothing to do)",
"decodedName",
"=",
"name",
"return",
"decodedName"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/importDXF.py#L214-L240 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/ltisys.py | python | StateSpace._copy | (self, system) | Copy the parameters of another `StateSpace` system.
Parameters
----------
system : instance of `StateSpace`
The state-space system that is to be copied | Copy the parameters of another `StateSpace` system. | [
"Copy",
"the",
"parameters",
"of",
"another",
"StateSpace",
"system",
"."
] | def _copy(self, system):
"""
Copy the parameters of another `StateSpace` system.
Parameters
----------
system : instance of `StateSpace`
The state-space system that is to be copied
"""
self.A = system.A
self.B = system.B
self.C = system.C
self.D = system.D | [
"def",
"_copy",
"(",
"self",
",",
"system",
")",
":",
"self",
".",
"A",
"=",
"system",
".",
"A",
"self",
".",
"B",
"=",
"system",
".",
"B",
"self",
".",
"C",
"=",
"system",
".",
"C",
"self",
".",
"D",
"=",
"system",
".",
"D"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/ltisys.py#L1548-L1561 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/tools/run_perf.py | python | ResultTracker.AddRunnableDuration | (self, runnable, duration) | Records a duration of a specific run of the runnable. | Records a duration of a specific run of the runnable. | [
"Records",
"a",
"duration",
"of",
"a",
"specific",
"run",
"of",
"the",
"runnable",
"."
] | def AddRunnableDuration(self, runnable, duration):
"""Records a duration of a specific run of the runnable."""
if runnable.name not in self.runnables:
self.runnables[runnable.name] = {
'graphs': runnable.graphs,
'durations': [duration],
'timeout': runnable.timeout,
}
else:
existing_entry = self.runnables[runnable.name]
assert runnable.timeout == existing_entry['timeout']
assert runnable.graphs == existing_entry['graphs']
existing_entry['durations'].append(duration) | [
"def",
"AddRunnableDuration",
"(",
"self",
",",
"runnable",
",",
"duration",
")",
":",
"if",
"runnable",
".",
"name",
"not",
"in",
"self",
".",
"runnables",
":",
"self",
".",
"runnables",
"[",
"runnable",
".",
"name",
"]",
"=",
"{",
"'graphs'",
":",
"runnable",
".",
"graphs",
",",
"'durations'",
":",
"[",
"duration",
"]",
",",
"'timeout'",
":",
"runnable",
".",
"timeout",
",",
"}",
"else",
":",
"existing_entry",
"=",
"self",
".",
"runnables",
"[",
"runnable",
".",
"name",
"]",
"assert",
"runnable",
".",
"timeout",
"==",
"existing_entry",
"[",
"'timeout'",
"]",
"assert",
"runnable",
".",
"graphs",
"==",
"existing_entry",
"[",
"'graphs'",
"]",
"existing_entry",
"[",
"'durations'",
"]",
".",
"append",
"(",
"duration",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/run_perf.py#L210-L222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.