nwo
stringlengths 5
86
| sha
stringlengths 40
40
| path
stringlengths 4
189
| language
stringclasses 1
value | identifier
stringlengths 1
94
| parameters
stringlengths 2
4.03k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
11.5k
| docstring
stringlengths 1
33.2k
| docstring_summary
stringlengths 0
5.15k
| docstring_tokens
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecStamp | (self, path) | Simple stamp command. | Simple stamp command. | [
"Simple",
"stamp",
"command",
"."
] | def ExecStamp(self, path):
"""Simple stamp command."""
open(path, 'w').close() | [
"def",
"ExecStamp",
"(",
"self",
",",
"path",
")",
":",
"open",
"(",
"path",
",",
"'w'",
")",
".",
"close",
"(",
")"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/win_tool.py#L69-L71 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/DocXMLRPCServer.py | python | ServerHTMLDoc.markup | (self, text, escape=None, funcs={}, classes={}, methods={}) | return ''.join(results) | Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names. | Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names. | [
"Mark",
"up",
"some",
"plain",
"text",
"given",
"a",
"context",
"of",
"symbols",
"to",
"look",
"for",
".",
"Each",
"context",
"dictionary",
"maps",
"object",
"names",
"to",
"anchor",
"names",
"."
] | def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
"""Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names."""
escape = escape or self.escape
results = []
here = 0
# XXX Note that this regular expression does not allow for the
# hyperlinking of arbitrary strings being used as method
# names. Only methods with names consisting of word characters
# and '.'s are hyperlinked.
pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
r'RFC[- ]?(\d+)|'
r'PEP[- ]?(\d+)|'
r'(self\.)?((?:\w|\.)+))\b')
while 1:
match = pattern.search(text, here)
if not match: break
start, end = match.span()
results.append(escape(text[here:start]))
all, scheme, rfc, pep, selfdot, name = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append('<a href="%s">%s</a>' % (url, url))
elif rfc:
url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif pep:
url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif text[end:end+1] == '(':
results.append(self.namelink(name, methods, funcs, classes))
elif selfdot:
results.append('self.<strong>%s</strong>' % name)
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return ''.join(results) | [
"def",
"markup",
"(",
"self",
",",
"text",
",",
"escape",
"=",
"None",
",",
"funcs",
"=",
"{",
"}",
",",
"classes",
"=",
"{",
"}",
",",
"methods",
"=",
"{",
"}",
")",
":",
"escape",
"=",
"escape",
"or",
"self",
".",
"escape",
"results",
"=",
"[",
"]",
"here",
"=",
"0",
"# XXX Note that this regular expression does not allow for the",
"# hyperlinking of arbitrary strings being used as method",
"# names. Only methods with names consisting of word characters",
"# and '.'s are hyperlinked.",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'\\b((http|ftp)://\\S+[\\w/]|'",
"r'RFC[- ]?(\\d+)|'",
"r'PEP[- ]?(\\d+)|'",
"r'(self\\.)?((?:\\w|\\.)+))\\b'",
")",
"while",
"1",
":",
"match",
"=",
"pattern",
".",
"search",
"(",
"text",
",",
"here",
")",
"if",
"not",
"match",
":",
"break",
"start",
",",
"end",
"=",
"match",
".",
"span",
"(",
")",
"results",
".",
"append",
"(",
"escape",
"(",
"text",
"[",
"here",
":",
"start",
"]",
")",
")",
"all",
",",
"scheme",
",",
"rfc",
",",
"pep",
",",
"selfdot",
",",
"name",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"scheme",
":",
"url",
"=",
"escape",
"(",
"all",
")",
".",
"replace",
"(",
"'\"'",
",",
"'"'",
")",
"results",
".",
"append",
"(",
"'<a href=\"%s\">%s</a>'",
"%",
"(",
"url",
",",
"url",
")",
")",
"elif",
"rfc",
":",
"url",
"=",
"'http://www.rfc-editor.org/rfc/rfc%d.txt'",
"%",
"int",
"(",
"rfc",
")",
"results",
".",
"append",
"(",
"'<a href=\"%s\">%s</a>'",
"%",
"(",
"url",
",",
"escape",
"(",
"all",
")",
")",
")",
"elif",
"pep",
":",
"url",
"=",
"'http://www.python.org/dev/peps/pep-%04d/'",
"%",
"int",
"(",
"pep",
")",
"results",
".",
"append",
"(",
"'<a href=\"%s\">%s</a>'",
"%",
"(",
"url",
",",
"escape",
"(",
"all",
")",
")",
")",
"elif",
"text",
"[",
"end",
":",
"end",
"+",
"1",
"]",
"==",
"'('",
":",
"results",
".",
"append",
"(",
"self",
".",
"namelink",
"(",
"name",
",",
"methods",
",",
"funcs",
",",
"classes",
")",
")",
"elif",
"selfdot",
":",
"results",
".",
"append",
"(",
"'self.<strong>%s</strong>'",
"%",
"name",
")",
"else",
":",
"results",
".",
"append",
"(",
"self",
".",
"namelink",
"(",
"name",
",",
"classes",
")",
")",
"here",
"=",
"end",
"results",
".",
"append",
"(",
"escape",
"(",
"text",
"[",
"here",
":",
"]",
")",
")",
"return",
"''",
".",
"join",
"(",
"results",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/DocXMLRPCServer.py#L26-L65 |
|
christinaa/LLVM-VideoCore4 | 7773c3c9e5d22b785d4b96ed0acea37c8aa9c183 | utils/lit/lit/discovery.py | python | getTestSuite | (item, litConfig, cache) | return ts, tuple(relative + tuple(components)) | getTestSuite(item, litConfig, cache) -> (suite, relative_path)
Find the test suite containing @arg item.
@retval (None, ...) - Indicates no test suite contains @arg item.
@retval (suite, relative_path) - The suite that @arg item is in, and its
relative path inside that suite. | getTestSuite(item, litConfig, cache) -> (suite, relative_path) | [
"getTestSuite",
"(",
"item",
"litConfig",
"cache",
")",
"-",
">",
"(",
"suite",
"relative_path",
")"
] | def getTestSuite(item, litConfig, cache):
"""getTestSuite(item, litConfig, cache) -> (suite, relative_path)
Find the test suite containing @arg item.
@retval (None, ...) - Indicates no test suite contains @arg item.
@retval (suite, relative_path) - The suite that @arg item is in, and its
relative path inside that suite.
"""
def search1(path):
# Check for a site config or a lit config.
cfgpath = dirContainsTestSuite(path, litConfig)
# If we didn't find a config file, keep looking.
if not cfgpath:
parent,base = os.path.split(path)
if parent == path:
return (None, ())
ts, relative = search(parent)
return (ts, relative + (base,))
# We found a test suite, create a new config for it and load it.
if litConfig.debug:
litConfig.note('loading suite config %r' % cfgpath)
cfg = TestingConfig.fromdefaults(litConfig)
cfg.load_from_path(cfgpath, litConfig)
source_root = os.path.realpath(cfg.test_source_root or path)
exec_root = os.path.realpath(cfg.test_exec_root or path)
return Test.TestSuite(cfg.name, source_root, exec_root, cfg), ()
def search(path):
# Check for an already instantiated test suite.
res = cache.get(path)
if res is None:
cache[path] = res = search1(path)
return res
# Canonicalize the path.
item = os.path.realpath(item)
# Skip files and virtual components.
components = []
while not os.path.isdir(item):
parent,base = os.path.split(item)
if parent == item:
return (None, ())
components.append(base)
item = parent
components.reverse()
ts, relative = search(item)
return ts, tuple(relative + tuple(components)) | [
"def",
"getTestSuite",
"(",
"item",
",",
"litConfig",
",",
"cache",
")",
":",
"def",
"search1",
"(",
"path",
")",
":",
"# Check for a site config or a lit config.",
"cfgpath",
"=",
"dirContainsTestSuite",
"(",
"path",
",",
"litConfig",
")",
"# If we didn't find a config file, keep looking.",
"if",
"not",
"cfgpath",
":",
"parent",
",",
"base",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"parent",
"==",
"path",
":",
"return",
"(",
"None",
",",
"(",
")",
")",
"ts",
",",
"relative",
"=",
"search",
"(",
"parent",
")",
"return",
"(",
"ts",
",",
"relative",
"+",
"(",
"base",
",",
")",
")",
"# We found a test suite, create a new config for it and load it.",
"if",
"litConfig",
".",
"debug",
":",
"litConfig",
".",
"note",
"(",
"'loading suite config %r'",
"%",
"cfgpath",
")",
"cfg",
"=",
"TestingConfig",
".",
"fromdefaults",
"(",
"litConfig",
")",
"cfg",
".",
"load_from_path",
"(",
"cfgpath",
",",
"litConfig",
")",
"source_root",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"cfg",
".",
"test_source_root",
"or",
"path",
")",
"exec_root",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"cfg",
".",
"test_exec_root",
"or",
"path",
")",
"return",
"Test",
".",
"TestSuite",
"(",
"cfg",
".",
"name",
",",
"source_root",
",",
"exec_root",
",",
"cfg",
")",
",",
"(",
")",
"def",
"search",
"(",
"path",
")",
":",
"# Check for an already instantiated test suite.",
"res",
"=",
"cache",
".",
"get",
"(",
"path",
")",
"if",
"res",
"is",
"None",
":",
"cache",
"[",
"path",
"]",
"=",
"res",
"=",
"search1",
"(",
"path",
")",
"return",
"res",
"# Canonicalize the path.",
"item",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"item",
")",
"# Skip files and virtual components.",
"components",
"=",
"[",
"]",
"while",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"item",
")",
":",
"parent",
",",
"base",
"=",
"os",
".",
"path",
".",
"split",
"(",
"item",
")",
"if",
"parent",
"==",
"item",
":",
"return",
"(",
"None",
",",
"(",
")",
")",
"components",
".",
"append",
"(",
"base",
")",
"item",
"=",
"parent",
"components",
".",
"reverse",
"(",
")",
"ts",
",",
"relative",
"=",
"search",
"(",
"item",
")",
"return",
"ts",
",",
"tuple",
"(",
"relative",
"+",
"tuple",
"(",
"components",
")",
")"
] | https://github.com/christinaa/LLVM-VideoCore4/blob/7773c3c9e5d22b785d4b96ed0acea37c8aa9c183/utils/lit/lit/discovery.py#L21-L74 |
|
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/progress/progress.py | python | ProgressBar.reset | (self) | return self | Resets the current progress to the start point | Resets the current progress to the start point | [
"Resets",
"the",
"current",
"progress",
"to",
"the",
"start",
"point"
] | def reset(self):
"""Resets the current progress to the start point"""
self.progress = self._get_progress(self.start)
return self | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"progress",
"=",
"self",
".",
"_get_progress",
"(",
"self",
".",
"start",
")",
"return",
"self"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/progress/progress.py#L78-L81 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | TaskBarIcon.__init__ | (self, *args, **kwargs) | __init__(self, int iconType=TBI_DEFAULT_TYPE) -> TaskBarIcon | __init__(self, int iconType=TBI_DEFAULT_TYPE) -> TaskBarIcon | [
"__init__",
"(",
"self",
"int",
"iconType",
"=",
"TBI_DEFAULT_TYPE",
")",
"-",
">",
"TaskBarIcon"
] | def __init__(self, *args, **kwargs):
"""__init__(self, int iconType=TBI_DEFAULT_TYPE) -> TaskBarIcon"""
_windows_.TaskBarIcon_swiginit(self,_windows_.new_TaskBarIcon(*args, **kwargs))
self._setOORInfo(self);TaskBarIcon._setCallbackInfo(self, self, TaskBarIcon) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_windows_",
".",
"TaskBarIcon_swiginit",
"(",
"self",
",",
"_windows_",
".",
"new_TaskBarIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")",
"TaskBarIcon",
".",
"_setCallbackInfo",
"(",
"self",
",",
"self",
",",
"TaskBarIcon",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2810-L2813 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/hmac.py | python | HMAC._current | (self) | return h | Return a hash object for the current state.
To be used only internally with digest() and hexdigest(). | Return a hash object for the current state. | [
"Return",
"a",
"hash",
"object",
"for",
"the",
"current",
"state",
"."
] | def _current(self):
"""Return a hash object for the current state.
To be used only internally with digest() and hexdigest().
"""
h = self.outer.copy()
h.update(self.inner.digest())
return h | [
"def",
"_current",
"(",
"self",
")",
":",
"h",
"=",
"self",
".",
"outer",
".",
"copy",
"(",
")",
"h",
".",
"update",
"(",
"self",
".",
"inner",
".",
"digest",
"(",
")",
")",
"return",
"h"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/hmac.py#L117-L124 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/parse.py | python | Parser.pop | (self) | Pop a nonterminal. (Internal) | Pop a nonterminal. (Internal) | [
"Pop",
"a",
"nonterminal",
".",
"(",
"Internal",
")"
] | def pop(self):
"""Pop a nonterminal. (Internal)"""
popdfa, popstate, popnode = self.stack.pop()
newnode = self.convert(self.grammar, popnode)
if newnode is not None:
if self.stack:
dfa, state, node = self.stack[-1]
node[-1].append(newnode)
else:
self.rootnode = newnode
self.rootnode.used_names = self.used_names | [
"def",
"pop",
"(",
"self",
")",
":",
"popdfa",
",",
"popstate",
",",
"popnode",
"=",
"self",
".",
"stack",
".",
"pop",
"(",
")",
"newnode",
"=",
"self",
".",
"convert",
"(",
"self",
".",
"grammar",
",",
"popnode",
")",
"if",
"newnode",
"is",
"not",
"None",
":",
"if",
"self",
".",
"stack",
":",
"dfa",
",",
"state",
",",
"node",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"node",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"newnode",
")",
"else",
":",
"self",
".",
"rootnode",
"=",
"newnode",
"self",
".",
"rootnode",
".",
"used_names",
"=",
"self",
".",
"used_names"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/parse.py#L191-L201 |
||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | FieldDefn.GetTypeName | (self, *args) | return _ogr.FieldDefn_GetTypeName(self, *args) | r"""GetTypeName(FieldDefn self) -> char const * | r"""GetTypeName(FieldDefn self) -> char const * | [
"r",
"GetTypeName",
"(",
"FieldDefn",
"self",
")",
"-",
">",
"char",
"const",
"*"
] | def GetTypeName(self, *args):
r"""GetTypeName(FieldDefn self) -> char const *"""
return _ogr.FieldDefn_GetTypeName(self, *args) | [
"def",
"GetTypeName",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"FieldDefn_GetTypeName",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L5278-L5280 |
|
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/msvs.py | python | _ConvertToolsToExpectedForm | (tools) | return tool_list | Convert tools to a form expected by Visual Studio.
Arguments:
tools: A dictionary of settings; the tool name is the key.
Returns:
A list of Tool objects. | Convert tools to a form expected by Visual Studio. | [
"Convert",
"tools",
"to",
"a",
"form",
"expected",
"by",
"Visual",
"Studio",
"."
] | def _ConvertToolsToExpectedForm(tools):
"""Convert tools to a form expected by Visual Studio.
Arguments:
tools: A dictionary of settings; the tool name is the key.
Returns:
A list of Tool objects.
"""
tool_list = []
for tool, settings in tools.iteritems():
# Collapse settings with lists.
settings_fixed = {}
for setting, value in settings.iteritems():
if type(value) == list:
if ((tool == 'VCLinkerTool' and
setting == 'AdditionalDependencies') or
setting == 'AdditionalOptions'):
settings_fixed[setting] = ' '.join(value)
else:
settings_fixed[setting] = ';'.join(value)
else:
settings_fixed[setting] = value
# Add in this tool.
tool_list.append(MSVSProject.Tool(tool, settings_fixed))
return tool_list | [
"def",
"_ConvertToolsToExpectedForm",
"(",
"tools",
")",
":",
"tool_list",
"=",
"[",
"]",
"for",
"tool",
",",
"settings",
"in",
"tools",
".",
"iteritems",
"(",
")",
":",
"# Collapse settings with lists.",
"settings_fixed",
"=",
"{",
"}",
"for",
"setting",
",",
"value",
"in",
"settings",
".",
"iteritems",
"(",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"list",
":",
"if",
"(",
"(",
"tool",
"==",
"'VCLinkerTool'",
"and",
"setting",
"==",
"'AdditionalDependencies'",
")",
"or",
"setting",
"==",
"'AdditionalOptions'",
")",
":",
"settings_fixed",
"[",
"setting",
"]",
"=",
"' '",
".",
"join",
"(",
"value",
")",
"else",
":",
"settings_fixed",
"[",
"setting",
"]",
"=",
"';'",
".",
"join",
"(",
"value",
")",
"else",
":",
"settings_fixed",
"[",
"setting",
"]",
"=",
"value",
"# Add in this tool.",
"tool_list",
".",
"append",
"(",
"MSVSProject",
".",
"Tool",
"(",
"tool",
",",
"settings_fixed",
")",
")",
"return",
"tool_list"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/msvs.py#L1345-L1369 |
|
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | CreateArg | (arg_string) | Creates an Argument. | Creates an Argument. | [
"Creates",
"an",
"Argument",
"."
] | def CreateArg(arg_string):
"""Creates an Argument."""
arg_parts = arg_string.split()
if len(arg_parts) == 1 and arg_parts[0] == 'void':
return None
# Is this a pointer argument?
elif arg_string.find('*') >= 0:
if arg_parts[0] == 'NonImmediate':
return NonImmediatePointerArgument(
arg_parts[-1],
" ".join(arg_parts[1:-1]))
else:
return PointerArgument(
arg_parts[-1],
" ".join(arg_parts[0:-1]))
# Is this a resource argument? Must come after pointer check.
elif arg_parts[0].startswith('GLidBind'):
return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
elif arg_parts[0].startswith('GLidZero'):
return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
elif arg_parts[0].startswith('GLid'):
return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
elif arg_parts[0].startswith('GLboolean'):
return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
elif arg_parts[0].startswith('GLintUniformLocation'):
return UniformLocationArgument(arg_parts[-1])
elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
not arg_parts[0].startswith('GLintptr')):
return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
elif (arg_parts[0].startswith('GLsizeiNotNegative') or
arg_parts[0].startswith('GLintptrNotNegative')):
return SizeNotNegativeArgument(arg_parts[-1],
" ".join(arg_parts[0:-1]),
arg_parts[0][0:-11])
elif arg_parts[0].startswith('GLsize'):
return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
else:
return Argument(arg_parts[-1], " ".join(arg_parts[0:-1])) | [
"def",
"CreateArg",
"(",
"arg_string",
")",
":",
"arg_parts",
"=",
"arg_string",
".",
"split",
"(",
")",
"if",
"len",
"(",
"arg_parts",
")",
"==",
"1",
"and",
"arg_parts",
"[",
"0",
"]",
"==",
"'void'",
":",
"return",
"None",
"# Is this a pointer argument?",
"elif",
"arg_string",
".",
"find",
"(",
"'*'",
")",
">=",
"0",
":",
"if",
"arg_parts",
"[",
"0",
"]",
"==",
"'NonImmediate'",
":",
"return",
"NonImmediatePointerArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"1",
":",
"-",
"1",
"]",
")",
")",
"else",
":",
"return",
"PointerArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"# Is this a resource argument? Must come after pointer check.",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLidBind'",
")",
":",
"return",
"ResourceIdBindArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLidZero'",
")",
":",
"return",
"ResourceIdZeroArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLid'",
")",
":",
"return",
"ResourceIdArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLenum'",
")",
"and",
"len",
"(",
"arg_parts",
"[",
"0",
"]",
")",
">",
"6",
":",
"return",
"EnumArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLboolean'",
")",
"and",
"len",
"(",
"arg_parts",
"[",
"0",
"]",
")",
">",
"9",
":",
"return",
"ValidatedBoolArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLboolean'",
")",
":",
"return",
"BoolArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLintUniformLocation'",
")",
":",
"return",
"UniformLocationArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
")",
"elif",
"(",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLint'",
")",
"and",
"len",
"(",
"arg_parts",
"[",
"0",
"]",
")",
">",
"5",
"and",
"not",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLintptr'",
")",
")",
":",
"return",
"IntArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"elif",
"(",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLsizeiNotNegative'",
")",
"or",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLintptrNotNegative'",
")",
")",
":",
"return",
"SizeNotNegativeArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
",",
"arg_parts",
"[",
"0",
"]",
"[",
"0",
":",
"-",
"11",
"]",
")",
"elif",
"arg_parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"'GLsize'",
")",
":",
"return",
"SizeArgument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"else",
":",
"return",
"Argument",
"(",
"arg_parts",
"[",
"-",
"1",
"]",
",",
"\" \"",
".",
"join",
"(",
"arg_parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L6811-L6852 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py | python | HTTPMessage.readheaders | (self) | Read header lines.
Read header lines up to the entirely blank line that terminates them.
The (normally blank) line that ends the headers is skipped, but not
included in the returned list. If a non-header line ends the headers,
(which is an error), an attempt is made to backspace over it; it is
never included in the returned list.
The variable self.status is set to the empty string if all went well,
otherwise it is an error message. The variable self.headers is a
completely uninterpreted list of lines contained in the header (so
printing them will reproduce the header exactly as it appears in the
file).
If multiple header fields with the same name occur, they are combined
according to the rules in RFC 2616 sec 4.2:
Appending each subsequent field-value to the first, each separated
by a comma. The order in which header fields with the same field-name
are received is significant to the interpretation of the combined
field value. | Read header lines. | [
"Read",
"header",
"lines",
"."
] | def readheaders(self):
"""Read header lines.
Read header lines up to the entirely blank line that terminates them.
The (normally blank) line that ends the headers is skipped, but not
included in the returned list. If a non-header line ends the headers,
(which is an error), an attempt is made to backspace over it; it is
never included in the returned list.
The variable self.status is set to the empty string if all went well,
otherwise it is an error message. The variable self.headers is a
completely uninterpreted list of lines contained in the header (so
printing them will reproduce the header exactly as it appears in the
file).
If multiple header fields with the same name occur, they are combined
according to the rules in RFC 2616 sec 4.2:
Appending each subsequent field-value to the first, each separated
by a comma. The order in which header fields with the same field-name
are received is significant to the interpretation of the combined
field value.
"""
# XXX The implementation overrides the readheaders() method of
# rfc822.Message. The base class design isn't amenable to
# customized behavior here so the method here is a copy of the
# base class code with a few small changes.
self.dict = {}
self.unixfrom = ''
self.headers = hlist = []
self.status = ''
headerseen = ""
firstline = 1
startofline = unread = tell = None
if hasattr(self.fp, 'unread'):
unread = self.fp.unread
elif self.seekable:
tell = self.fp.tell
while True:
if tell:
try:
startofline = tell()
except IOError:
startofline = tell = None
self.seekable = 0
line = self.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
if not line:
self.status = 'EOF in headers'
break
# Skip unix From name time lines
if firstline and line.startswith('From '):
self.unixfrom = self.unixfrom + line
continue
firstline = 0
if headerseen and line[0] in ' \t':
# XXX Not sure if continuation lines are handled properly
# for http and/or for repeating headers
# It's a continuation line.
hlist.append(line)
self.addcontinue(headerseen, line.strip())
continue
elif self.iscomment(line):
# It's a comment. Ignore it.
continue
elif self.islast(line):
# Note! No pushback here! The delimiter line gets eaten.
break
headerseen = self.isheader(line)
if headerseen:
# It's a legal header line, save it.
hlist.append(line)
self.addheader(headerseen, line[len(headerseen)+1:].strip())
continue
else:
# It's not a header line; throw it back and stop here.
if not self.dict:
self.status = 'No headers'
else:
self.status = 'Non-header line where header expected'
# Try to undo the read.
if unread:
unread(line)
elif tell:
self.fp.seek(startofline)
else:
self.status = self.status + '; bad seek'
break | [
"def",
"readheaders",
"(",
"self",
")",
":",
"# XXX The implementation overrides the readheaders() method of",
"# rfc822.Message. The base class design isn't amenable to",
"# customized behavior here so the method here is a copy of the",
"# base class code with a few small changes.",
"self",
".",
"dict",
"=",
"{",
"}",
"self",
".",
"unixfrom",
"=",
"''",
"self",
".",
"headers",
"=",
"hlist",
"=",
"[",
"]",
"self",
".",
"status",
"=",
"''",
"headerseen",
"=",
"\"\"",
"firstline",
"=",
"1",
"startofline",
"=",
"unread",
"=",
"tell",
"=",
"None",
"if",
"hasattr",
"(",
"self",
".",
"fp",
",",
"'unread'",
")",
":",
"unread",
"=",
"self",
".",
"fp",
".",
"unread",
"elif",
"self",
".",
"seekable",
":",
"tell",
"=",
"self",
".",
"fp",
".",
"tell",
"while",
"True",
":",
"if",
"tell",
":",
"try",
":",
"startofline",
"=",
"tell",
"(",
")",
"except",
"IOError",
":",
"startofline",
"=",
"tell",
"=",
"None",
"self",
".",
"seekable",
"=",
"0",
"line",
"=",
"self",
".",
"fp",
".",
"readline",
"(",
"_MAXLINE",
"+",
"1",
")",
"if",
"len",
"(",
"line",
")",
">",
"_MAXLINE",
":",
"raise",
"LineTooLong",
"(",
"\"header line\"",
")",
"if",
"not",
"line",
":",
"self",
".",
"status",
"=",
"'EOF in headers'",
"break",
"# Skip unix From name time lines",
"if",
"firstline",
"and",
"line",
".",
"startswith",
"(",
"'From '",
")",
":",
"self",
".",
"unixfrom",
"=",
"self",
".",
"unixfrom",
"+",
"line",
"continue",
"firstline",
"=",
"0",
"if",
"headerseen",
"and",
"line",
"[",
"0",
"]",
"in",
"' \\t'",
":",
"# XXX Not sure if continuation lines are handled properly",
"# for http and/or for repeating headers",
"# It's a continuation line.",
"hlist",
".",
"append",
"(",
"line",
")",
"self",
".",
"addcontinue",
"(",
"headerseen",
",",
"line",
".",
"strip",
"(",
")",
")",
"continue",
"elif",
"self",
".",
"iscomment",
"(",
"line",
")",
":",
"# It's a comment. Ignore it.",
"continue",
"elif",
"self",
".",
"islast",
"(",
"line",
")",
":",
"# Note! No pushback here! The delimiter line gets eaten.",
"break",
"headerseen",
"=",
"self",
".",
"isheader",
"(",
"line",
")",
"if",
"headerseen",
":",
"# It's a legal header line, save it.",
"hlist",
".",
"append",
"(",
"line",
")",
"self",
".",
"addheader",
"(",
"headerseen",
",",
"line",
"[",
"len",
"(",
"headerseen",
")",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
")",
"continue",
"else",
":",
"# It's not a header line; throw it back and stop here.",
"if",
"not",
"self",
".",
"dict",
":",
"self",
".",
"status",
"=",
"'No headers'",
"else",
":",
"self",
".",
"status",
"=",
"'Non-header line where header expected'",
"# Try to undo the read.",
"if",
"unread",
":",
"unread",
"(",
"line",
")",
"elif",
"tell",
":",
"self",
".",
"fp",
".",
"seek",
"(",
"startofline",
")",
"else",
":",
"self",
".",
"status",
"=",
"self",
".",
"status",
"+",
"'; bad seek'",
"break"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py#L234-L323 |
||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/kokkos-kernels/scripts/analysis/batched/pd.py | python | kkt_parse_exespace | (ln) | return tuple([int(i) for i in v]) | Parse an ExecSpace line -> (#nodes, #cores, #threads/core). | Parse an ExecSpace line -> (#nodes, #cores, #threads/core). | [
"Parse",
"an",
"ExecSpace",
"line",
"-",
">",
"(",
"#nodes",
"#cores",
"#threads",
"/",
"core",
")",
"."
] | def kkt_parse_exespace(ln):
'Parse an ExecSpace line -> (#nodes, #cores, #threads/core).'
v = kkt_parse_exespace_re(ln)
if len(v) == 0:
return ()
if len(v) != 3:
print 'Parse error; ln = ' + ln
return ()
return tuple([int(i) for i in v]) | [
"def",
"kkt_parse_exespace",
"(",
"ln",
")",
":",
"v",
"=",
"kkt_parse_exespace_re",
"(",
"ln",
")",
"if",
"len",
"(",
"v",
")",
"==",
"0",
":",
"return",
"(",
")",
"if",
"len",
"(",
"v",
")",
"!=",
"3",
":",
"print",
"'Parse error; ln = '",
"+",
"ln",
"return",
"(",
")",
"return",
"tuple",
"(",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"v",
"]",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/kokkos-kernels/scripts/analysis/batched/pd.py#L175-L183 |
|
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | api/ctpx/ctptd.py | python | CtpTd.onRspQryNotice | (self, NoticeField, RspInfoField, requestId, final) | 请求查询客户通知响应 | 请求查询客户通知响应 | [
"请求查询客户通知响应"
] | def onRspQryNotice(self, NoticeField, RspInfoField, requestId, final):
"""请求查询客户通知响应"""
pass | [
"def",
"onRspQryNotice",
"(",
"self",
",",
"NoticeField",
",",
"RspInfoField",
",",
"requestId",
",",
"final",
")",
":",
"pass"
] | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L250-L252 |
||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/Crypto/PublicKey/qNEW.py | python | construct | (tuple) | return obj | construct(tuple:(long,long,long,long)|(long,long,long,long,long)
Construct a qNEW object from a 4- or 5-tuple of numbers. | construct(tuple:(long,long,long,long)|(long,long,long,long,long)
Construct a qNEW object from a 4- or 5-tuple of numbers. | [
"construct",
"(",
"tuple",
":",
"(",
"long",
"long",
"long",
"long",
")",
"|",
"(",
"long",
"long",
"long",
"long",
"long",
")",
"Construct",
"a",
"qNEW",
"object",
"from",
"a",
"4",
"-",
"or",
"5",
"-",
"tuple",
"of",
"numbers",
"."
] | def construct(tuple):
"""construct(tuple:(long,long,long,long)|(long,long,long,long,long)
Construct a qNEW object from a 4- or 5-tuple of numbers.
"""
obj=qNEWobj()
if len(tuple) not in [4,5]:
raise error, 'argument for construct() wrong length'
for i in range(len(tuple)):
field = obj.keydata[i]
setattr(obj, field, tuple[i])
return obj | [
"def",
"construct",
"(",
"tuple",
")",
":",
"obj",
"=",
"qNEWobj",
"(",
")",
"if",
"len",
"(",
"tuple",
")",
"not",
"in",
"[",
"4",
",",
"5",
"]",
":",
"raise",
"error",
",",
"'argument for construct() wrong length'",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"tuple",
")",
")",
":",
"field",
"=",
"obj",
".",
"keydata",
"[",
"i",
"]",
"setattr",
"(",
"obj",
",",
"field",
",",
"tuple",
"[",
"i",
"]",
")",
"return",
"obj"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/Crypto/PublicKey/qNEW.py#L107-L117 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/f2py/crackfortran.py | python | is_free_format | (file) | return result | Check if file is in free format Fortran. | Check if file is in free format Fortran. | [
"Check",
"if",
"file",
"is",
"in",
"free",
"format",
"Fortran",
"."
] | def is_free_format(file):
"""Check if file is in free format Fortran."""
# f90 allows both fixed and free format, assuming fixed unless
# signs of free format are detected.
result = 0
with open(file, 'r') as f:
line = f.readline()
n = 15 # the number of non-comment lines to scan for hints
if _has_f_header(line):
n = 0
elif _has_f90_header(line):
n = 0
result = 1
while n > 0 and line:
if line[0] != '!' and line.strip():
n -= 1
if (line[0] != '\t' and _free_f90_start(line[:5])) or line[-2:-1] == '&':
result = 1
break
line = f.readline()
return result | [
"def",
"is_free_format",
"(",
"file",
")",
":",
"# f90 allows both fixed and free format, assuming fixed unless",
"# signs of free format are detected.",
"result",
"=",
"0",
"with",
"open",
"(",
"file",
",",
"'r'",
")",
"as",
"f",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"n",
"=",
"15",
"# the number of non-comment lines to scan for hints",
"if",
"_has_f_header",
"(",
"line",
")",
":",
"n",
"=",
"0",
"elif",
"_has_f90_header",
"(",
"line",
")",
":",
"n",
"=",
"0",
"result",
"=",
"1",
"while",
"n",
">",
"0",
"and",
"line",
":",
"if",
"line",
"[",
"0",
"]",
"!=",
"'!'",
"and",
"line",
".",
"strip",
"(",
")",
":",
"n",
"-=",
"1",
"if",
"(",
"line",
"[",
"0",
"]",
"!=",
"'\\t'",
"and",
"_free_f90_start",
"(",
"line",
"[",
":",
"5",
"]",
")",
")",
"or",
"line",
"[",
"-",
"2",
":",
"-",
"1",
"]",
"==",
"'&'",
":",
"result",
"=",
"1",
"break",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/f2py/crackfortran.py#L306-L326 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListLineData.GetMode | (self) | return self._owner.GetListCtrl().GetAGWWindowStyleFlag() & ULC_MASK_TYPE | Returns the current highlighting mode. | Returns the current highlighting mode. | [
"Returns",
"the",
"current",
"highlighting",
"mode",
"."
] | def GetMode(self):
""" Returns the current highlighting mode. """
return self._owner.GetListCtrl().GetAGWWindowStyleFlag() & ULC_MASK_TYPE | [
"def",
"GetMode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_owner",
".",
"GetListCtrl",
"(",
")",
".",
"GetAGWWindowStyleFlag",
"(",
")",
"&",
"ULC_MASK_TYPE"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L3869-L3872 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py | python | DNNLinearCombinedRegressor.predict_scores | (self, x=None, input_fn=None, batch_size=None,
as_iterable=True) | return preds[key] | Returns predicted scores for given features.
Args:
x: features.
input_fn: Input function. If set, x must be None.
batch_size: Override default batch size.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
Returns:
Numpy array of predicted scores (or an iterable of predicted scores if
as_iterable is True). If `label_dimension == 1`, the shape of the output
is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`. | Returns predicted scores for given features. | [
"Returns",
"predicted",
"scores",
"for",
"given",
"features",
"."
] | def predict_scores(self, x=None, input_fn=None, batch_size=None,
as_iterable=True):
"""Returns predicted scores for given features.
Args:
x: features.
input_fn: Input function. If set, x must be None.
batch_size: Override default batch size.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
Returns:
Numpy array of predicted scores (or an iterable of predicted scores if
as_iterable is True). If `label_dimension == 1`, the shape of the output
is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`.
"""
key = prediction_key.PredictionKey.SCORES
preds = super(DNNLinearCombinedRegressor, self).predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key] | [
"def",
"predict_scores",
"(",
"self",
",",
"x",
"=",
"None",
",",
"input_fn",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"as_iterable",
"=",
"True",
")",
":",
"key",
"=",
"prediction_key",
".",
"PredictionKey",
".",
"SCORES",
"preds",
"=",
"super",
"(",
"DNNLinearCombinedRegressor",
",",
"self",
")",
".",
"predict",
"(",
"x",
"=",
"x",
",",
"input_fn",
"=",
"input_fn",
",",
"batch_size",
"=",
"batch_size",
",",
"outputs",
"=",
"[",
"key",
"]",
",",
"as_iterable",
"=",
"as_iterable",
")",
"if",
"as_iterable",
":",
"return",
"(",
"pred",
"[",
"key",
"]",
"for",
"pred",
"in",
"preds",
")",
"return",
"preds",
"[",
"key",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L1114-L1141 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/examples/speech_commands/label_wav_dir.py | python | load_graph | (filename) | Unpersists graph from file as default graph. | Unpersists graph from file as default graph. | [
"Unpersists",
"graph",
"from",
"file",
"as",
"default",
"graph",
"."
] | def load_graph(filename):
"""Unpersists graph from file as default graph."""
with tf.gfile.GFile(filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='') | [
"def",
"load_graph",
"(",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"graph_def",
"=",
"tf",
".",
"GraphDef",
"(",
")",
"graph_def",
".",
"ParseFromString",
"(",
"f",
".",
"read",
"(",
")",
")",
"tf",
".",
"import_graph_def",
"(",
"graph_def",
",",
"name",
"=",
"''",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/examples/speech_commands/label_wav_dir.py#L47-L52 |
||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/find-in-mountain-array.py | python | Solution.findInMountainArray | (self, target, mountain_arr) | return -1 | :type target: integer
:type mountain_arr: MountainArray
:rtype: integer | :type target: integer
:type mountain_arr: MountainArray
:rtype: integer | [
":",
"type",
"target",
":",
"integer",
":",
"type",
"mountain_arr",
":",
"MountainArray",
":",
"rtype",
":",
"integer"
] | def findInMountainArray(self, target, mountain_arr):
"""
:type target: integer
:type mountain_arr: MountainArray
:rtype: integer
"""
def binarySearch(A, left, right, check):
while left <= right:
mid = left + (right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
peak = binarySearch(mountain_arr, 0, mountain_arr.length()-1,
lambda x: mountain_arr.get(x) >= mountain_arr.get(x+1))
left = binarySearch(mountain_arr, 0, peak,
lambda x: mountain_arr.get(x) >= target)
if left <= peak and mountain_arr.get(left) == target:
return left
right = binarySearch(mountain_arr, peak, mountain_arr.length()-1,
lambda x: mountain_arr.get(x) <= target)
if right <= mountain_arr.length()-1 and mountain_arr.get(right) == target:
return right
return -1 | [
"def",
"findInMountainArray",
"(",
"self",
",",
"target",
",",
"mountain_arr",
")",
":",
"def",
"binarySearch",
"(",
"A",
",",
"left",
",",
"right",
",",
"check",
")",
":",
"while",
"left",
"<=",
"right",
":",
"mid",
"=",
"left",
"+",
"(",
"right",
"-",
"left",
")",
"//",
"2",
"if",
"check",
"(",
"mid",
")",
":",
"right",
"=",
"mid",
"-",
"1",
"else",
":",
"left",
"=",
"mid",
"+",
"1",
"return",
"left",
"peak",
"=",
"binarySearch",
"(",
"mountain_arr",
",",
"0",
",",
"mountain_arr",
".",
"length",
"(",
")",
"-",
"1",
",",
"lambda",
"x",
":",
"mountain_arr",
".",
"get",
"(",
"x",
")",
">=",
"mountain_arr",
".",
"get",
"(",
"x",
"+",
"1",
")",
")",
"left",
"=",
"binarySearch",
"(",
"mountain_arr",
",",
"0",
",",
"peak",
",",
"lambda",
"x",
":",
"mountain_arr",
".",
"get",
"(",
"x",
")",
">=",
"target",
")",
"if",
"left",
"<=",
"peak",
"and",
"mountain_arr",
".",
"get",
"(",
"left",
")",
"==",
"target",
":",
"return",
"left",
"right",
"=",
"binarySearch",
"(",
"mountain_arr",
",",
"peak",
",",
"mountain_arr",
".",
"length",
"(",
")",
"-",
"1",
",",
"lambda",
"x",
":",
"mountain_arr",
".",
"get",
"(",
"x",
")",
"<=",
"target",
")",
"if",
"right",
"<=",
"mountain_arr",
".",
"length",
"(",
")",
"-",
"1",
"and",
"mountain_arr",
".",
"get",
"(",
"right",
")",
"==",
"target",
":",
"return",
"right",
"return",
"-",
"1"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-in-mountain-array.py#L24-L49 |
|
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | docs/doxygen/graphbuilder.py | python | Node.format | (self) | return result | Format this node for 'dot'. | Format this node for 'dot'. | [
"Format",
"this",
"node",
"for",
"dot",
"."
] | def format(self):
"""Format this node for 'dot'."""
# TODO: Take indent as a parameter to make output marginally nicer.
result = ''
if self._children:
result += ' subgraph cluster_{0} {{\n' \
.format(self._nodename)
result += ' label = "{0}"\n'.format(self._label)
for child in self._children:
result += child.format()
result += ' }\n'
else:
properties = 'label="{0}"'.format(self._label)
if self._properties:
properties += ', ' + self._properties
if self._style:
properties += ', style="{0}"'.format(self._style)
result += ' {0} [{1}]\n'.format(self._nodename, properties)
return result | [
"def",
"format",
"(",
"self",
")",
":",
"# TODO: Take indent as a parameter to make output marginally nicer.",
"result",
"=",
"''",
"if",
"self",
".",
"_children",
":",
"result",
"+=",
"' subgraph cluster_{0} {{\\n'",
".",
"format",
"(",
"self",
".",
"_nodename",
")",
"result",
"+=",
"' label = \"{0}\"\\n'",
".",
"format",
"(",
"self",
".",
"_label",
")",
"for",
"child",
"in",
"self",
".",
"_children",
":",
"result",
"+=",
"child",
".",
"format",
"(",
")",
"result",
"+=",
"' }\\n'",
"else",
":",
"properties",
"=",
"'label=\"{0}\"'",
".",
"format",
"(",
"self",
".",
"_label",
")",
"if",
"self",
".",
"_properties",
":",
"properties",
"+=",
"', '",
"+",
"self",
".",
"_properties",
"if",
"self",
".",
"_style",
":",
"properties",
"+=",
"', style=\"{0}\"'",
".",
"format",
"(",
"self",
".",
"_style",
")",
"result",
"+=",
"' {0} [{1}]\\n'",
".",
"format",
"(",
"self",
".",
"_nodename",
",",
"properties",
")",
"return",
"result"
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/docs/doxygen/graphbuilder.py#L214-L232 |
|
limbo018/DREAMPlace | 146c3b9fd003d1acd52c96d9fd02e3f0a05154e4 | dreamplace/PlaceDB.py | python | PlaceDB.area | (self) | return self.width*self.height | @return area of layout | [] | def area(self):
"""
@return area of layout
"""
return self.width*self.height | [
"def",
"area",
"(",
"self",
")",
":",
"return",
"self",
".",
"width",
"*",
"self",
".",
"height"
] | https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/PlaceDB.py#L240-L244 |
||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBTrace.GetTraceData | (self, error, buf, offset, thread_id) | return _lldb.SBTrace_GetTraceData(self, error, buf, offset, thread_id) | GetTraceData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t | GetTraceData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t | [
"GetTraceData",
"(",
"SBTrace",
"self",
"SBError",
"error",
"void",
"*",
"buf",
"size_t",
"offset",
"lldb",
"::",
"tid_t",
"thread_id",
")",
"-",
">",
"size_t"
] | def GetTraceData(self, error, buf, offset, thread_id):
"""GetTraceData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t"""
return _lldb.SBTrace_GetTraceData(self, error, buf, offset, thread_id) | [
"def",
"GetTraceData",
"(",
"self",
",",
"error",
",",
"buf",
",",
"offset",
",",
"thread_id",
")",
":",
"return",
"_lldb",
".",
"SBTrace_GetTraceData",
"(",
"self",
",",
"error",
",",
"buf",
",",
"offset",
",",
"thread_id",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12232-L12234 |
|
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_options_view.py | python | TFAsymmetryFittingOptionsView.set_tf_asymmetry_mode | (self, tf_asymmetry_on: bool) | Hides or shows the normalisation options depending on if TF Asymmetry fitting mode is on or off. | Hides or shows the normalisation options depending on if TF Asymmetry fitting mode is on or off. | [
"Hides",
"or",
"shows",
"the",
"normalisation",
"options",
"depending",
"on",
"if",
"TF",
"Asymmetry",
"fitting",
"mode",
"is",
"on",
"or",
"off",
"."
] | def set_tf_asymmetry_mode(self, tf_asymmetry_on: bool) -> None:
"""Hides or shows the normalisation options depending on if TF Asymmetry fitting mode is on or off."""
if tf_asymmetry_on:
self.show_normalisation_options()
else:
self.hide_normalisation_options() | [
"def",
"set_tf_asymmetry_mode",
"(",
"self",
",",
"tf_asymmetry_on",
":",
"bool",
")",
"->",
"None",
":",
"if",
"tf_asymmetry_on",
":",
"self",
".",
"show_normalisation_options",
"(",
")",
"else",
":",
"self",
".",
"hide_normalisation_options",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_options_view.py#L36-L41 |
||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/check_ops.py | python | _assert_rank_condition | (
x, rank, static_condition, dynamic_condition, data, summarize) | return control_flow_ops.Assert(condition, data, summarize=summarize) | Assert `x` has a rank that satisfies a given condition.
Args:
x: Numeric `Tensor`.
rank: Scalar `Tensor`.
static_condition: A python function that takes `[actual_rank, given_rank]`
and returns `True` if the condition is satisfied, `False` otherwise.
dynamic_condition: An `op` that takes [actual_rank, given_rank] and return
`True` if the condition is satisfied, `False` otherwise.
data: The tensors to print out if the condition is false. Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of each tensor.
Returns:
Op raising `InvalidArgumentError` if `x` fails dynamic_condition.
Raises:
ValueError: If static checks determine `x` fails static_condition. | Assert `x` has a rank that satisfies a given condition. | [
"Assert",
"x",
"has",
"a",
"rank",
"that",
"satisfies",
"a",
"given",
"condition",
"."
] | def _assert_rank_condition(
x, rank, static_condition, dynamic_condition, data, summarize):
"""Assert `x` has a rank that satisfies a given condition.
Args:
x: Numeric `Tensor`.
rank: Scalar `Tensor`.
static_condition: A python function that takes `[actual_rank, given_rank]`
and returns `True` if the condition is satisfied, `False` otherwise.
dynamic_condition: An `op` that takes [actual_rank, given_rank] and return
`True` if the condition is satisfied, `False` otherwise.
data: The tensors to print out if the condition is false. Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of each tensor.
Returns:
Op raising `InvalidArgumentError` if `x` fails dynamic_condition.
Raises:
ValueError: If static checks determine `x` fails static_condition.
"""
assert_type(rank, dtypes.int32)
# Attempt to statically defined rank.
rank_static = tensor_util.constant_value(rank)
if rank_static is not None:
if rank_static.ndim != 0:
raise ValueError('Rank must be a scalar.')
x_rank_static = x.get_shape().ndims
if x_rank_static is not None:
if not static_condition(x_rank_static, rank_static):
raise ValueError(
'Static rank condition failed', x_rank_static, rank_static)
return control_flow_ops.no_op(name='static_checks_determined_all_ok')
condition = dynamic_condition(array_ops.rank(x), rank)
# Add the condition that `rank` must have rank zero. Prevents the bug where
# someone does assert_rank(x, [n]), rather than assert_rank(x, n).
if rank_static is None:
this_data = ['Rank must be a scalar. Received rank: ', rank]
rank_check = assert_rank(rank, 0, data=this_data)
condition = control_flow_ops.with_dependencies([rank_check], condition)
return control_flow_ops.Assert(condition, data, summarize=summarize) | [
"def",
"_assert_rank_condition",
"(",
"x",
",",
"rank",
",",
"static_condition",
",",
"dynamic_condition",
",",
"data",
",",
"summarize",
")",
":",
"assert_type",
"(",
"rank",
",",
"dtypes",
".",
"int32",
")",
"# Attempt to statically defined rank.",
"rank_static",
"=",
"tensor_util",
".",
"constant_value",
"(",
"rank",
")",
"if",
"rank_static",
"is",
"not",
"None",
":",
"if",
"rank_static",
".",
"ndim",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'Rank must be a scalar.'",
")",
"x_rank_static",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims",
"if",
"x_rank_static",
"is",
"not",
"None",
":",
"if",
"not",
"static_condition",
"(",
"x_rank_static",
",",
"rank_static",
")",
":",
"raise",
"ValueError",
"(",
"'Static rank condition failed'",
",",
"x_rank_static",
",",
"rank_static",
")",
"return",
"control_flow_ops",
".",
"no_op",
"(",
"name",
"=",
"'static_checks_determined_all_ok'",
")",
"condition",
"=",
"dynamic_condition",
"(",
"array_ops",
".",
"rank",
"(",
"x",
")",
",",
"rank",
")",
"# Add the condition that `rank` must have rank zero. Prevents the bug where",
"# someone does assert_rank(x, [n]), rather than assert_rank(x, n).",
"if",
"rank_static",
"is",
"None",
":",
"this_data",
"=",
"[",
"'Rank must be a scalar. Received rank: '",
",",
"rank",
"]",
"rank_check",
"=",
"assert_rank",
"(",
"rank",
",",
"0",
",",
"data",
"=",
"this_data",
")",
"condition",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"rank_check",
"]",
",",
"condition",
")",
"return",
"control_flow_ops",
".",
"Assert",
"(",
"condition",
",",
"data",
",",
"summarize",
"=",
"summarize",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/check_ops.py#L1015-L1060 |
|
shader-slang/slang | b8982fcf43b86c1e39dcc3dd19bff2821633eda6 | external/vulkan/registry/generator.py | python | OutputGenerator.isStructAlwaysValid | (self, structname) | return True | Try to do check if a structure is always considered valid (i.e. there's no rules to its acceptance). | Try to do check if a structure is always considered valid (i.e. there's no rules to its acceptance). | [
"Try",
"to",
"do",
"check",
"if",
"a",
"structure",
"is",
"always",
"considered",
"valid",
"(",
"i",
".",
"e",
".",
"there",
"s",
"no",
"rules",
"to",
"its",
"acceptance",
")",
"."
] | def isStructAlwaysValid(self, structname):
"""Try to do check if a structure is always considered valid (i.e. there's no rules to its acceptance)."""
# A conventions object is required for this call.
if not self.conventions:
raise RuntimeError("To use isStructAlwaysValid, be sure your options include a Conventions object.")
if self.conventions.type_always_valid(structname):
return True
category = self.getTypeCategory(structname)
if self.conventions.category_requires_validation(category):
return False
info = self.registry.typedict.get(structname)
assert(info is not None)
members = info.getMembers()
for member in members:
member_name = getElemName(member)
if member_name in (self.conventions.structtype_member_name,
self.conventions.nextpointer_member_name):
return False
if member.get('noautovalidity'):
return False
member_type = getElemType(member)
if member_type in ('void', 'char') or self.paramIsArray(member) or self.paramIsPointer(member):
return False
if self.conventions.type_always_valid(member_type):
continue
member_category = self.getTypeCategory(member_type)
if self.conventions.category_requires_validation(member_category):
return False
if member_category in ('struct', 'union'):
if self.isStructAlwaysValid(member_type) is False:
return False
return True | [
"def",
"isStructAlwaysValid",
"(",
"self",
",",
"structname",
")",
":",
"# A conventions object is required for this call.",
"if",
"not",
"self",
".",
"conventions",
":",
"raise",
"RuntimeError",
"(",
"\"To use isStructAlwaysValid, be sure your options include a Conventions object.\"",
")",
"if",
"self",
".",
"conventions",
".",
"type_always_valid",
"(",
"structname",
")",
":",
"return",
"True",
"category",
"=",
"self",
".",
"getTypeCategory",
"(",
"structname",
")",
"if",
"self",
".",
"conventions",
".",
"category_requires_validation",
"(",
"category",
")",
":",
"return",
"False",
"info",
"=",
"self",
".",
"registry",
".",
"typedict",
".",
"get",
"(",
"structname",
")",
"assert",
"(",
"info",
"is",
"not",
"None",
")",
"members",
"=",
"info",
".",
"getMembers",
"(",
")",
"for",
"member",
"in",
"members",
":",
"member_name",
"=",
"getElemName",
"(",
"member",
")",
"if",
"member_name",
"in",
"(",
"self",
".",
"conventions",
".",
"structtype_member_name",
",",
"self",
".",
"conventions",
".",
"nextpointer_member_name",
")",
":",
"return",
"False",
"if",
"member",
".",
"get",
"(",
"'noautovalidity'",
")",
":",
"return",
"False",
"member_type",
"=",
"getElemType",
"(",
"member",
")",
"if",
"member_type",
"in",
"(",
"'void'",
",",
"'char'",
")",
"or",
"self",
".",
"paramIsArray",
"(",
"member",
")",
"or",
"self",
".",
"paramIsPointer",
"(",
"member",
")",
":",
"return",
"False",
"if",
"self",
".",
"conventions",
".",
"type_always_valid",
"(",
"member_type",
")",
":",
"continue",
"member_category",
"=",
"self",
".",
"getTypeCategory",
"(",
"member_type",
")",
"if",
"self",
".",
"conventions",
".",
"category_requires_validation",
"(",
"member_category",
")",
":",
"return",
"False",
"if",
"member_category",
"in",
"(",
"'struct'",
",",
"'union'",
")",
":",
"if",
"self",
".",
"isStructAlwaysValid",
"(",
"member_type",
")",
"is",
"False",
":",
"return",
"False",
"return",
"True"
] | https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/generator.py#L874-L918 |
|
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | SynthText_Chinese/gen_cartoon.py | python | add_res_to_db | (imgname,res,db) | Add the synthetically generated text image instance
and other metadata to the dataset. | Add the synthetically generated text image instance
and other metadata to the dataset. | [
"Add",
"the",
"synthetically",
"generated",
"text",
"image",
"instance",
"and",
"other",
"metadata",
"to",
"the",
"dataset",
"."
] | def add_res_to_db(imgname,res,db):
"""
Add the synthetically generated text image instance
and other metadata to the dataset.
"""
ninstance = len(res)
for i in xrange(ninstance):
print colorize(Color.GREEN,'added into the db %s '%res[i]['txt'])
dname = "%s_%d"%(imgname, i)
db['data'].create_dataset(dname,data=res[i]['img'])
db['data'][dname].attrs['charBB'] = res[i]['charBB']
db['data'][dname].attrs['wordBB'] = res[i]['wordBB']
print 'type of res[i][\'txt\'] ',type(res[i]['txt'])
#db['data'][dname].attrs['txt'] = res[i]['txt']
db['data'][dname].attrs.create('txt', res[i]['txt'], dtype=h5py.special_dtype(vlen=unicode))
print 'type of db ',type(db['data'][dname].attrs['txt'])
print colorize(Color.GREEN,'successfully added')
print res[i]['txt']
print res[i]['img'].shape
print 'charBB',res[i]['charBB'].shape
print 'charBB',res[i]['charBB']
print 'wordBB',res[i]['wordBB'].shape
print 'wordBB',res[i]['wordBB']
'''
img = Image.fromarray(res[i]['img'])
hsv_img=np.array(rgb2hsv(img))
print 'hsv_img_shape',hsv_img.shape
print 'hsv_img',hsv_img
H=hsv_img[:,:,2]
print 'H_channel',H.shape,H
#img = Image.fromarray(db['data'][dname][:])
''' | [
"def",
"add_res_to_db",
"(",
"imgname",
",",
"res",
",",
"db",
")",
":",
"ninstance",
"=",
"len",
"(",
"res",
")",
"for",
"i",
"in",
"xrange",
"(",
"ninstance",
")",
":",
"print",
"colorize",
"(",
"Color",
".",
"GREEN",
",",
"'added into the db %s '",
"%",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
")",
"dname",
"=",
"\"%s_%d\"",
"%",
"(",
"imgname",
",",
"i",
")",
"db",
"[",
"'data'",
"]",
".",
"create_dataset",
"(",
"dname",
",",
"data",
"=",
"res",
"[",
"i",
"]",
"[",
"'img'",
"]",
")",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
"[",
"'charBB'",
"]",
"=",
"res",
"[",
"i",
"]",
"[",
"'charBB'",
"]",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
"[",
"'wordBB'",
"]",
"=",
"res",
"[",
"i",
"]",
"[",
"'wordBB'",
"]",
"print",
"'type of res[i][\\'txt\\'] '",
",",
"type",
"(",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
")",
"#db['data'][dname].attrs['txt'] = res[i]['txt']",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
".",
"create",
"(",
"'txt'",
",",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
",",
"dtype",
"=",
"h5py",
".",
"special_dtype",
"(",
"vlen",
"=",
"unicode",
")",
")",
"print",
"'type of db '",
",",
"type",
"(",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
"[",
"'txt'",
"]",
")",
"print",
"colorize",
"(",
"Color",
".",
"GREEN",
",",
"'successfully added'",
")",
"print",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
"print",
"res",
"[",
"i",
"]",
"[",
"'img'",
"]",
".",
"shape",
"print",
"'charBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'charBB'",
"]",
".",
"shape",
"print",
"'charBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'charBB'",
"]",
"print",
"'wordBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'wordBB'",
"]",
".",
"shape",
"print",
"'wordBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'wordBB'",
"]",
"'''\n img = Image.fromarray(res[i]['img'])\n hsv_img=np.array(rgb2hsv(img))\n print 'hsv_img_shape',hsv_img.shape\n print 'hsv_img',hsv_img\n H=hsv_img[:,:,2]\n print 'H_channel',H.shape,H\n #img = Image.fromarray(db['data'][dname][:])\n '''"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/gen_cartoon.py#L64-L97 |
||
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/client.py | python | IClient.Shutdown | (self) | Closes Skype application. | Closes Skype application. | [
"Closes",
"Skype",
"application",
"."
] | def Shutdown(self):
'''Closes Skype application.
'''
self._Skype._API.Shutdown() | [
"def",
"Shutdown",
"(",
"self",
")",
":",
"self",
".",
"_Skype",
".",
"_API",
".",
"Shutdown",
"(",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/client.py#L234-L237 |
||
pgRouting/osm2pgrouting | 8491929fc4037d308f271e84d59bb96da3c28aa2 | tools/cpplint.py | python | NestingState.InTemplateArgumentList | (self, clean_lines, linenum, pos) | return False | Check if current position is inside template argument list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: position just after the suspected template argument.
Returns:
True if (linenum, pos) is inside template arguments. | Check if current position is inside template argument list. | [
"Check",
"if",
"current",
"position",
"is",
"inside",
"template",
"argument",
"list",
"."
] | def InTemplateArgumentList(self, clean_lines, linenum, pos):
"""Check if current position is inside template argument list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: position just after the suspected template argument.
Returns:
True if (linenum, pos) is inside template arguments.
"""
while linenum < clean_lines.NumLines():
# Find the earliest character that might indicate a template argument
line = clean_lines.elided[linenum]
match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
if not match:
linenum += 1
pos = 0
continue
token = match.group(1)
pos += len(match.group(0))
# These things do not look like template argument list:
# class Suspect {
# class Suspect x; }
if token in ('{', '}', ';'): return False
# These things look like template argument list:
# template <class Suspect>
# template <class Suspect = default_value>
# template <class Suspect[]>
# template <class Suspect...>
if token in ('>', '=', '[', ']', '.'): return True
# Check if token is an unmatched '<'.
# If not, move on to the next character.
if token != '<':
pos += 1
if pos >= len(line):
linenum += 1
pos = 0
continue
# We can't be sure if we just find a single '<', and need to
# find the matching '>'.
(_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
if end_pos < 0:
# Not sure if template argument list or syntax error in file
return False
linenum = end_line
pos = end_pos
return False | [
"def",
"InTemplateArgumentList",
"(",
"self",
",",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"while",
"linenum",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"# Find the earliest character that might indicate a template argument",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"match",
"=",
"Match",
"(",
"r'^[^{};=\\[\\]\\.<>]*(.)'",
",",
"line",
"[",
"pos",
":",
"]",
")",
"if",
"not",
"match",
":",
"linenum",
"+=",
"1",
"pos",
"=",
"0",
"continue",
"token",
"=",
"match",
".",
"group",
"(",
"1",
")",
"pos",
"+=",
"len",
"(",
"match",
".",
"group",
"(",
"0",
")",
")",
"# These things do not look like template argument list:",
"# class Suspect {",
"# class Suspect x; }",
"if",
"token",
"in",
"(",
"'{'",
",",
"'}'",
",",
"';'",
")",
":",
"return",
"False",
"# These things look like template argument list:",
"# template <class Suspect>",
"# template <class Suspect = default_value>",
"# template <class Suspect[]>",
"# template <class Suspect...>",
"if",
"token",
"in",
"(",
"'>'",
",",
"'='",
",",
"'['",
",",
"']'",
",",
"'.'",
")",
":",
"return",
"True",
"# Check if token is an unmatched '<'.",
"# If not, move on to the next character.",
"if",
"token",
"!=",
"'<'",
":",
"pos",
"+=",
"1",
"if",
"pos",
">=",
"len",
"(",
"line",
")",
":",
"linenum",
"+=",
"1",
"pos",
"=",
"0",
"continue",
"# We can't be sure if we just find a single '<', and need to",
"# find the matching '>'.",
"(",
"_",
",",
"end_line",
",",
"end_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
"-",
"1",
")",
"if",
"end_pos",
"<",
"0",
":",
"# Not sure if template argument list or syntax error in file",
"return",
"False",
"linenum",
"=",
"end_line",
"pos",
"=",
"end_pos",
"return",
"False"
] | https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L2264-L2314 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | GenericDirCtrl.GetFilterIndex | (*args, **kwargs) | return _controls_.GenericDirCtrl_GetFilterIndex(*args, **kwargs) | GetFilterIndex(self) -> int | GetFilterIndex(self) -> int | [
"GetFilterIndex",
"(",
"self",
")",
"-",
">",
"int"
] | def GetFilterIndex(*args, **kwargs):
"""GetFilterIndex(self) -> int"""
return _controls_.GenericDirCtrl_GetFilterIndex(*args, **kwargs) | [
"def",
"GetFilterIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"GenericDirCtrl_GetFilterIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5725-L5727 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py | python | Fixed.validate | (self, other) | return True | validate against an existing storable | validate against an existing storable | [
"validate",
"against",
"an",
"existing",
"storable"
] | def validate(self, other):
""" validate against an existing storable """
if other is None:
return
return True | [
"def",
"validate",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"None",
":",
"return",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py#L2590-L2594 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | PageSetupDialogData.SetPaperSize | (*args, **kwargs) | return _windows_.PageSetupDialogData_SetPaperSize(*args, **kwargs) | SetPaperSize(self, Size size) | SetPaperSize(self, Size size) | [
"SetPaperSize",
"(",
"self",
"Size",
"size",
")"
] | def SetPaperSize(*args, **kwargs):
"""SetPaperSize(self, Size size)"""
return _windows_.PageSetupDialogData_SetPaperSize(*args, **kwargs) | [
"def",
"SetPaperSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_SetPaperSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L4975-L4977 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/message.py | python | Message.items | (self) | return [(k, self.policy.header_fetch_parse(k, v))
for k, v in self._headers] | Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list. | Get all the message's header fields and values. | [
"Get",
"all",
"the",
"message",
"s",
"header",
"fields",
"and",
"values",
"."
] | def items(self):
"""Get all the message's header fields and values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
"""
return [(k, self.policy.header_fetch_parse(k, v))
for k, v in self._headers] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"k",
",",
"self",
".",
"policy",
".",
"header_fetch_parse",
"(",
"k",
",",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_headers",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/message.py#L451-L460 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/ide/activegrid/tool/FindService.py | python | FindService.GetFindString | (self) | return wx.ConfigBase_Get().Read(FIND_MATCHPATTERN, "") | Load the search pattern from registry | Load the search pattern from registry | [
"Load",
"the",
"search",
"pattern",
"from",
"registry"
] | def GetFindString(self):
""" Load the search pattern from registry """
return wx.ConfigBase_Get().Read(FIND_MATCHPATTERN, "") | [
"def",
"GetFindString",
"(",
"self",
")",
":",
"return",
"wx",
".",
"ConfigBase_Get",
"(",
")",
".",
"Read",
"(",
"FIND_MATCHPATTERN",
",",
"\"\"",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/tool/FindService.py#L292-L294 |
|
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosbag/src/rosbag/bag.py | python | Bag._get_compression | (self) | return self._compression | Get the compression method to use for writing. | Get the compression method to use for writing. | [
"Get",
"the",
"compression",
"method",
"to",
"use",
"for",
"writing",
"."
] | def _get_compression(self):
"""Get the compression method to use for writing."""
return self._compression | [
"def",
"_get_compression",
"(",
"self",
")",
":",
"return",
"self",
".",
"_compression"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosbag/src/rosbag/bag.py#L222-L224 |
|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/patch_updater.py | python | extract_paths | (file) | return paths | Extract the list of modified paths from the patch file. | Extract the list of modified paths from the patch file. | [
"Extract",
"the",
"list",
"of",
"modified",
"paths",
"from",
"the",
"patch",
"file",
"."
] | def extract_paths(file):
""" Extract the list of modified paths from the patch file. """
paths = []
fp = open(file)
for line in fp:
if line[:4] != '+++ ':
continue
match = re.match('^([^\t]+)', line[4:])
if not match:
continue
paths.append(match.group(1).strip())
return paths | [
"def",
"extract_paths",
"(",
"file",
")",
":",
"paths",
"=",
"[",
"]",
"fp",
"=",
"open",
"(",
"file",
")",
"for",
"line",
"in",
"fp",
":",
"if",
"line",
"[",
":",
"4",
"]",
"!=",
"'+++ '",
":",
"continue",
"match",
"=",
"re",
".",
"match",
"(",
"'^([^\\t]+)'",
",",
"line",
"[",
"4",
":",
"]",
")",
"if",
"not",
"match",
":",
"continue",
"paths",
".",
"append",
"(",
"match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
"return",
"paths"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/patch_updater.py#L22-L33 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/aliaspass.py | python | AliasPass._MaybeReportError | (self, err) | Report an error to the handler (if registered). | Report an error to the handler (if registered). | [
"Report",
"an",
"error",
"to",
"the",
"handler",
"(",
"if",
"registered",
")",
"."
] | def _MaybeReportError(self, err):
"""Report an error to the handler (if registered)."""
if self._error_handler:
self._error_handler.HandleError(err) | [
"def",
"_MaybeReportError",
"(",
"self",
",",
"err",
")",
":",
"if",
"self",
".",
"_error_handler",
":",
"self",
".",
"_error_handler",
".",
"HandleError",
"(",
"err",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/aliaspass.py#L145-L148 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/cluster/hierarchy.py | python | ClusterNode.pre_order | (self, func=(lambda x: x.id)) | return preorder | Perform pre-order traversal without recursive function calls.
When a leaf node is first encountered, ``func`` is called with
the leaf node as its argument, and its result is appended to
the list.
For example, the statement::
ids = root.pre_order(lambda x: x.id)
returns a list of the node ids corresponding to the leaf nodes
of the tree as they appear from left to right.
Parameters
----------
func : function
Applied to each leaf ClusterNode object in the pre-order traversal.
Given the ``i``-th leaf node in the pre-order traversal ``n[i]``,
the result of ``func(n[i])`` is stored in ``L[i]``. If not
provided, the index of the original observation to which the node
corresponds is used.
Returns
-------
L : list
The pre-order traversal. | Perform pre-order traversal without recursive function calls. | [
"Perform",
"pre",
"-",
"order",
"traversal",
"without",
"recursive",
"function",
"calls",
"."
] | def pre_order(self, func=(lambda x: x.id)):
"""
Perform pre-order traversal without recursive function calls.
When a leaf node is first encountered, ``func`` is called with
the leaf node as its argument, and its result is appended to
the list.
For example, the statement::
ids = root.pre_order(lambda x: x.id)
returns a list of the node ids corresponding to the leaf nodes
of the tree as they appear from left to right.
Parameters
----------
func : function
Applied to each leaf ClusterNode object in the pre-order traversal.
Given the ``i``-th leaf node in the pre-order traversal ``n[i]``,
the result of ``func(n[i])`` is stored in ``L[i]``. If not
provided, the index of the original observation to which the node
corresponds is used.
Returns
-------
L : list
The pre-order traversal.
"""
# Do a preorder traversal, caching the result. To avoid having to do
# recursion, we'll store the previous index we've visited in a vector.
n = self.count
curNode = [None] * (2 * n)
lvisited = set()
rvisited = set()
curNode[0] = self
k = 0
preorder = []
while k >= 0:
nd = curNode[k]
ndid = nd.id
if nd.is_leaf():
preorder.append(func(nd))
k = k - 1
else:
if ndid not in lvisited:
curNode[k + 1] = nd.left
lvisited.add(ndid)
k = k + 1
elif ndid not in rvisited:
curNode[k + 1] = nd.right
rvisited.add(ndid)
k = k + 1
# If we've visited the left and right of this non-leaf
# node already, go up in the tree.
else:
k = k - 1
return preorder | [
"def",
"pre_order",
"(",
"self",
",",
"func",
"=",
"(",
"lambda",
"x",
":",
"x",
".",
"id",
")",
")",
":",
"# Do a preorder traversal, caching the result. To avoid having to do",
"# recursion, we'll store the previous index we've visited in a vector.",
"n",
"=",
"self",
".",
"count",
"curNode",
"=",
"[",
"None",
"]",
"*",
"(",
"2",
"*",
"n",
")",
"lvisited",
"=",
"set",
"(",
")",
"rvisited",
"=",
"set",
"(",
")",
"curNode",
"[",
"0",
"]",
"=",
"self",
"k",
"=",
"0",
"preorder",
"=",
"[",
"]",
"while",
"k",
">=",
"0",
":",
"nd",
"=",
"curNode",
"[",
"k",
"]",
"ndid",
"=",
"nd",
".",
"id",
"if",
"nd",
".",
"is_leaf",
"(",
")",
":",
"preorder",
".",
"append",
"(",
"func",
"(",
"nd",
")",
")",
"k",
"=",
"k",
"-",
"1",
"else",
":",
"if",
"ndid",
"not",
"in",
"lvisited",
":",
"curNode",
"[",
"k",
"+",
"1",
"]",
"=",
"nd",
".",
"left",
"lvisited",
".",
"add",
"(",
"ndid",
")",
"k",
"=",
"k",
"+",
"1",
"elif",
"ndid",
"not",
"in",
"rvisited",
":",
"curNode",
"[",
"k",
"+",
"1",
"]",
"=",
"nd",
".",
"right",
"rvisited",
".",
"add",
"(",
"ndid",
")",
"k",
"=",
"k",
"+",
"1",
"# If we've visited the left and right of this non-leaf",
"# node already, go up in the tree.",
"else",
":",
"k",
"=",
"k",
"-",
"1",
"return",
"preorder"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/cluster/hierarchy.py#L1266-L1326 |
|
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/transport.py | python | Transport.fileno | (self) | return None | Get a file descriptor for select() if available | Get a file descriptor for select() if available | [
"Get",
"a",
"file",
"descriptor",
"for",
"select",
"()",
"if",
"available"
] | def fileno(self):
"""
Get a file descriptor for select() if available
"""
return None | [
"def",
"fileno",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/transport.py#L86-L90 |
|
ROCmSoftwarePlatform/hipCaffe | 4ec5d482515cce532348553b6db6d00d015675d5 | python/caffe/draw.py | python | get_layer_label | (layer, rankdir) | return node_label | Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer | Define node label based on layer type. | [
"Define",
"node",
"label",
"based",
"on",
"layer",
"type",
"."
] | def get_layer_label(layer, rankdir):
"""Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer
"""
if rankdir in ('TB', 'BT'):
# If graph orientation is vertical, horizontal space is free and
# vertical space is not; separate words with spaces
separator = ' '
else:
# If graph orientation is horizontal, vertical space is free and
# horizontal space is not; separate words with newlines
separator = '\\n'
if layer.type == 'Convolution' or layer.type == 'Deconvolution':
# Outer double quotes needed or else colon characters don't parse
# properly
node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
layer.type,
separator,
layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size._values) else 1,
separator,
layer.convolution_param.stride[0] if len(layer.convolution_param.stride._values) else 1,
separator,
layer.convolution_param.pad[0] if len(layer.convolution_param.pad._values) else 0)
elif layer.type == 'Pooling':
pooling_types_dict = get_pooling_types_dict()
node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
pooling_types_dict[layer.pooling_param.pool],
layer.type,
separator,
layer.pooling_param.kernel_size,
separator,
layer.pooling_param.stride,
separator,
layer.pooling_param.pad)
else:
node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type)
return node_label | [
"def",
"get_layer_label",
"(",
"layer",
",",
"rankdir",
")",
":",
"if",
"rankdir",
"in",
"(",
"'TB'",
",",
"'BT'",
")",
":",
"# If graph orientation is vertical, horizontal space is free and",
"# vertical space is not; separate words with spaces",
"separator",
"=",
"' '",
"else",
":",
"# If graph orientation is horizontal, vertical space is free and",
"# horizontal space is not; separate words with newlines",
"separator",
"=",
"'\\\\n'",
"if",
"layer",
".",
"type",
"==",
"'Convolution'",
"or",
"layer",
".",
"type",
"==",
"'Deconvolution'",
":",
"# Outer double quotes needed or else colon characters don't parse",
"# properly",
"node_label",
"=",
"'\"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d\"'",
"%",
"(",
"layer",
".",
"name",
",",
"separator",
",",
"layer",
".",
"type",
",",
"separator",
",",
"layer",
".",
"convolution_param",
".",
"kernel_size",
"[",
"0",
"]",
"if",
"len",
"(",
"layer",
".",
"convolution_param",
".",
"kernel_size",
".",
"_values",
")",
"else",
"1",
",",
"separator",
",",
"layer",
".",
"convolution_param",
".",
"stride",
"[",
"0",
"]",
"if",
"len",
"(",
"layer",
".",
"convolution_param",
".",
"stride",
".",
"_values",
")",
"else",
"1",
",",
"separator",
",",
"layer",
".",
"convolution_param",
".",
"pad",
"[",
"0",
"]",
"if",
"len",
"(",
"layer",
".",
"convolution_param",
".",
"pad",
".",
"_values",
")",
"else",
"0",
")",
"elif",
"layer",
".",
"type",
"==",
"'Pooling'",
":",
"pooling_types_dict",
"=",
"get_pooling_types_dict",
"(",
")",
"node_label",
"=",
"'\"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d\"'",
"%",
"(",
"layer",
".",
"name",
",",
"separator",
",",
"pooling_types_dict",
"[",
"layer",
".",
"pooling_param",
".",
"pool",
"]",
",",
"layer",
".",
"type",
",",
"separator",
",",
"layer",
".",
"pooling_param",
".",
"kernel_size",
",",
"separator",
",",
"layer",
".",
"pooling_param",
".",
"stride",
",",
"separator",
",",
"layer",
".",
"pooling_param",
".",
"pad",
")",
"else",
":",
"node_label",
"=",
"'\"%s%s(%s)\"'",
"%",
"(",
"layer",
".",
"name",
",",
"separator",
",",
"layer",
".",
"type",
")",
"return",
"node_label"
] | https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/python/caffe/draw.py#L62-L114 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py | python | set_build_var | (environ_cp,
var_name,
query_item,
option_name,
enabled_by_default,
bazel_config_name=None) | Set if query_item will be enabled for the build.
Ask user if query_item will be enabled. Default is used if no input is given.
Set subprocess environment variable and write to .bazelrc if enabled.
Args:
environ_cp: copy of the os.environ.
var_name: string for name of environment variable, e.g. "TF_NEED_CUDA".
query_item: string for feature related to the variable, e.g. "CUDA for
Nvidia GPUs".
option_name: string for option to define in .bazelrc.
enabled_by_default: boolean for default behavior.
bazel_config_name: Name for Bazel --config argument to enable build feature. | Set if query_item will be enabled for the build. | [
"Set",
"if",
"query_item",
"will",
"be",
"enabled",
"for",
"the",
"build",
"."
] | def set_build_var(environ_cp,
var_name,
query_item,
option_name,
enabled_by_default,
bazel_config_name=None):
"""Set if query_item will be enabled for the build.
Ask user if query_item will be enabled. Default is used if no input is given.
Set subprocess environment variable and write to .bazelrc if enabled.
Args:
environ_cp: copy of the os.environ.
var_name: string for name of environment variable, e.g. "TF_NEED_CUDA".
query_item: string for feature related to the variable, e.g. "CUDA for
Nvidia GPUs".
option_name: string for option to define in .bazelrc.
enabled_by_default: boolean for default behavior.
bazel_config_name: Name for Bazel --config argument to enable build feature.
"""
var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
environ_cp[var_name] = var
if var == '1':
write_to_bazelrc('build:%s --define %s=true' %
(bazel_config_name, option_name))
write_to_bazelrc('build --config=%s' % bazel_config_name)
elif bazel_config_name is not None:
# TODO(mikecase): Migrate all users of configure.py to use --config Bazel
# options and not to set build configs through environment variables.
write_to_bazelrc('build:%s --define %s=true' %
(bazel_config_name, option_name)) | [
"def",
"set_build_var",
"(",
"environ_cp",
",",
"var_name",
",",
"query_item",
",",
"option_name",
",",
"enabled_by_default",
",",
"bazel_config_name",
"=",
"None",
")",
":",
"var",
"=",
"str",
"(",
"int",
"(",
"get_var",
"(",
"environ_cp",
",",
"var_name",
",",
"query_item",
",",
"enabled_by_default",
")",
")",
")",
"environ_cp",
"[",
"var_name",
"]",
"=",
"var",
"if",
"var",
"==",
"'1'",
":",
"write_to_bazelrc",
"(",
"'build:%s --define %s=true'",
"%",
"(",
"bazel_config_name",
",",
"option_name",
")",
")",
"write_to_bazelrc",
"(",
"'build --config=%s'",
"%",
"bazel_config_name",
")",
"elif",
"bazel_config_name",
"is",
"not",
"None",
":",
"# TODO(mikecase): Migrate all users of configure.py to use --config Bazel",
"# options and not to set build configs through environment variables.",
"write_to_bazelrc",
"(",
"'build:%s --define %s=true'",
"%",
"(",
"bazel_config_name",
",",
"option_name",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py#L370-L401 |
||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/losses/python/metric_learning/metric_loss_ops.py | python | compute_gt_cluster_score | (pairwise_distances, labels) | return gt_cluster_score | Compute ground truth facility location score.
Loop over each unique classes and compute average travel distances.
Args:
pairwise_distances: 2-D Tensor of pairwise distances.
labels: 1-D Tensor of ground truth cluster assignment.
Returns:
gt_cluster_score: dtypes.float32 score. | Compute ground truth facility location score. | [
"Compute",
"ground",
"truth",
"facility",
"location",
"score",
"."
] | def compute_gt_cluster_score(pairwise_distances, labels):
"""Compute ground truth facility location score.
Loop over each unique classes and compute average travel distances.
Args:
pairwise_distances: 2-D Tensor of pairwise distances.
labels: 1-D Tensor of ground truth cluster assignment.
Returns:
gt_cluster_score: dtypes.float32 score.
"""
unique_class_ids = array_ops.unique(labels)[0]
num_classes = array_ops.size(unique_class_ids)
iteration = array_ops.constant(0)
gt_cluster_score = array_ops.constant(0.0, dtype=dtypes.float32)
def func_cond(iteration, gt_cluster_score):
del gt_cluster_score # Unused argument.
return iteration < num_classes
def func_body(iteration, gt_cluster_score):
"""Per each cluster, compute the average travel distance."""
mask = math_ops.equal(labels, unique_class_ids[iteration])
this_cluster_ids = array_ops.where(mask)
pairwise_distances_subset = array_ops.transpose(
array_ops.gather(
array_ops.transpose(
array_ops.gather(pairwise_distances, this_cluster_ids)),
this_cluster_ids))
this_cluster_score = -1.0 * math_ops.reduce_min(
math_ops.reduce_sum(
pairwise_distances_subset, axis=0))
return iteration + 1, gt_cluster_score + this_cluster_score
_, gt_cluster_score = control_flow_ops.while_loop(
func_cond, func_body, [iteration, gt_cluster_score])
return gt_cluster_score | [
"def",
"compute_gt_cluster_score",
"(",
"pairwise_distances",
",",
"labels",
")",
":",
"unique_class_ids",
"=",
"array_ops",
".",
"unique",
"(",
"labels",
")",
"[",
"0",
"]",
"num_classes",
"=",
"array_ops",
".",
"size",
"(",
"unique_class_ids",
")",
"iteration",
"=",
"array_ops",
".",
"constant",
"(",
"0",
")",
"gt_cluster_score",
"=",
"array_ops",
".",
"constant",
"(",
"0.0",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
"def",
"func_cond",
"(",
"iteration",
",",
"gt_cluster_score",
")",
":",
"del",
"gt_cluster_score",
"# Unused argument.",
"return",
"iteration",
"<",
"num_classes",
"def",
"func_body",
"(",
"iteration",
",",
"gt_cluster_score",
")",
":",
"\"\"\"Per each cluster, compute the average travel distance.\"\"\"",
"mask",
"=",
"math_ops",
".",
"equal",
"(",
"labels",
",",
"unique_class_ids",
"[",
"iteration",
"]",
")",
"this_cluster_ids",
"=",
"array_ops",
".",
"where",
"(",
"mask",
")",
"pairwise_distances_subset",
"=",
"array_ops",
".",
"transpose",
"(",
"array_ops",
".",
"gather",
"(",
"array_ops",
".",
"transpose",
"(",
"array_ops",
".",
"gather",
"(",
"pairwise_distances",
",",
"this_cluster_ids",
")",
")",
",",
"this_cluster_ids",
")",
")",
"this_cluster_score",
"=",
"-",
"1.0",
"*",
"math_ops",
".",
"reduce_min",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"pairwise_distances_subset",
",",
"axis",
"=",
"0",
")",
")",
"return",
"iteration",
"+",
"1",
",",
"gt_cluster_score",
"+",
"this_cluster_score",
"_",
",",
"gt_cluster_score",
"=",
"control_flow_ops",
".",
"while_loop",
"(",
"func_cond",
",",
"func_body",
",",
"[",
"iteration",
",",
"gt_cluster_score",
"]",
")",
"return",
"gt_cluster_score"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/losses/python/metric_learning/metric_loss_ops.py#L906-L943 |
|
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/bindings/python/clang/cindex.py | python | Type.get_align | (self) | return conf.lib.clang_Type_getAlignOf(self) | Retrieve the alignment of the record. | Retrieve the alignment of the record. | [
"Retrieve",
"the",
"alignment",
"of",
"the",
"record",
"."
] | def get_align(self):
"""
Retrieve the alignment of the record.
"""
return conf.lib.clang_Type_getAlignOf(self) | [
"def",
"get_align",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Type_getAlignOf",
"(",
"self",
")"
] | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L1959-L1963 |
|
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | bindings/experimental/distrdf/python/DistRDF/Ranges.py | python | get_balanced_ranges | (nentries, npartitions) | return ranges | Builds range pairs from the given values of the number of entries in
the dataset and number of partitions required. Each range contains the
same amount of entries, except for those cases where the number of
entries is not a multiple of the partitions.
Args:
nentries (int): The number of entries in a dataset.
npartitions (int): The number of partititions the sequence of entries
should be split in.
Returns:
list[DistRDF.Ranges.EmptySourceRange]: Each element of the list contains
the start and end entry of the corresponding range. | Builds range pairs from the given values of the number of entries in
the dataset and number of partitions required. Each range contains the
same amount of entries, except for those cases where the number of
entries is not a multiple of the partitions. | [
"Builds",
"range",
"pairs",
"from",
"the",
"given",
"values",
"of",
"the",
"number",
"of",
"entries",
"in",
"the",
"dataset",
"and",
"number",
"of",
"partitions",
"required",
".",
"Each",
"range",
"contains",
"the",
"same",
"amount",
"of",
"entries",
"except",
"for",
"those",
"cases",
"where",
"the",
"number",
"of",
"entries",
"is",
"not",
"a",
"multiple",
"of",
"the",
"partitions",
"."
] | def get_balanced_ranges(nentries, npartitions):
"""
Builds range pairs from the given values of the number of entries in
the dataset and number of partitions required. Each range contains the
same amount of entries, except for those cases where the number of
entries is not a multiple of the partitions.
Args:
nentries (int): The number of entries in a dataset.
npartitions (int): The number of partititions the sequence of entries
should be split in.
Returns:
list[DistRDF.Ranges.EmptySourceRange]: Each element of the list contains
the start and end entry of the corresponding range.
"""
partition_size = nentries // npartitions
i = 0 # Iterator
ranges = []
remainder = nentries % npartitions
rangeid = 0 # Keep track of the current range id
while i < nentries:
# Start value of current range
start = i
end = i = start + partition_size
if remainder:
# If the modulo value is not
# exhausted, add '1' to the end
# of the current range
end = i = end + 1
remainder -= 1
ranges.append(EmptySourceRange(rangeid, start, end))
rangeid += 1
return ranges | [
"def",
"get_balanced_ranges",
"(",
"nentries",
",",
"npartitions",
")",
":",
"partition_size",
"=",
"nentries",
"//",
"npartitions",
"i",
"=",
"0",
"# Iterator",
"ranges",
"=",
"[",
"]",
"remainder",
"=",
"nentries",
"%",
"npartitions",
"rangeid",
"=",
"0",
"# Keep track of the current range id",
"while",
"i",
"<",
"nentries",
":",
"# Start value of current range",
"start",
"=",
"i",
"end",
"=",
"i",
"=",
"start",
"+",
"partition_size",
"if",
"remainder",
":",
"# If the modulo value is not",
"# exhausted, add '1' to the end",
"# of the current range",
"end",
"=",
"i",
"=",
"end",
"+",
"1",
"remainder",
"-=",
"1",
"ranges",
".",
"append",
"(",
"EmptySourceRange",
"(",
"rangeid",
",",
"start",
",",
"end",
")",
")",
"rangeid",
"+=",
"1",
"return",
"ranges"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/experimental/distrdf/python/DistRDF/Ranges.py#L258-L300 |
|
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/tools/gcc.py | python | init | (version = None, command = None, options = None) | Initializes the gcc toolset for the given version. If necessary, command may
be used to specify where the compiler is located. The parameter 'options' is a
space-delimited list of options, each one specified as
<option-name>option-value. Valid option names are: cxxflags, linkflags and
linker-type. Accepted linker-type values are gnu, darwin, osf, hpux or sun
and the default value will be selected based on the current OS.
Example:
using gcc : 3.4 : : <cxxflags>foo <linkflags>bar <linker-type>sun ; | Initializes the gcc toolset for the given version. If necessary, command may
be used to specify where the compiler is located. The parameter 'options' is a
space-delimited list of options, each one specified as
<option-name>option-value. Valid option names are: cxxflags, linkflags and
linker-type. Accepted linker-type values are gnu, darwin, osf, hpux or sun
and the default value will be selected based on the current OS.
Example:
using gcc : 3.4 : : <cxxflags>foo <linkflags>bar <linker-type>sun ; | [
"Initializes",
"the",
"gcc",
"toolset",
"for",
"the",
"given",
"version",
".",
"If",
"necessary",
"command",
"may",
"be",
"used",
"to",
"specify",
"where",
"the",
"compiler",
"is",
"located",
".",
"The",
"parameter",
"options",
"is",
"a",
"space",
"-",
"delimited",
"list",
"of",
"options",
"each",
"one",
"specified",
"as",
"<option",
"-",
"name",
">",
"option",
"-",
"value",
".",
"Valid",
"option",
"names",
"are",
":",
"cxxflags",
"linkflags",
"and",
"linker",
"-",
"type",
".",
"Accepted",
"linker",
"-",
"type",
"values",
"are",
"gnu",
"darwin",
"osf",
"hpux",
"or",
"sun",
"and",
"the",
"default",
"value",
"will",
"be",
"selected",
"based",
"on",
"the",
"current",
"OS",
".",
"Example",
":",
"using",
"gcc",
":",
"3",
".",
"4",
":",
":",
"<cxxflags",
">",
"foo",
"<linkflags",
">",
"bar",
"<linker",
"-",
"type",
">",
"sun",
";"
] | def init(version = None, command = None, options = None):
"""
Initializes the gcc toolset for the given version. If necessary, command may
be used to specify where the compiler is located. The parameter 'options' is a
space-delimited list of options, each one specified as
<option-name>option-value. Valid option names are: cxxflags, linkflags and
linker-type. Accepted linker-type values are gnu, darwin, osf, hpux or sun
and the default value will be selected based on the current OS.
Example:
using gcc : 3.4 : : <cxxflags>foo <linkflags>bar <linker-type>sun ;
"""
options = to_seq(options)
command = to_seq(command)
# Information about the gcc command...
# The command.
command = to_seq(common.get_invocation_command('gcc', 'g++', command))
# The root directory of the tool install.
root = feature.get_values('<root>', options)
root = root[0] if root else ''
# The bin directory where to find the command to execute.
bin = None
# The flavor of compiler.
flavor = feature.get_values('<flavor>', options)
flavor = flavor[0] if flavor else ''
# Autodetect the root and bin dir if not given.
if command:
if not bin:
bin = common.get_absolute_tool_path(command[-1])
if not root:
root = os.path.dirname(bin)
# Autodetect the version and flavor if not given.
if command:
machine_info = subprocess.Popen(command + ['-dumpmachine'], stdout=subprocess.PIPE).communicate()[0]
machine = __machine_match.search(machine_info).group(1)
version_info = subprocess.Popen(command + ['-dumpversion'], stdout=subprocess.PIPE).communicate()[0]
version = __version_match.search(version_info).group(1)
if not flavor and machine.find('mingw') != -1:
flavor = 'mingw'
condition = None
if flavor:
condition = common.check_init_parameters('gcc', None,
('version', version),
('flavor', flavor))
else:
condition = common.check_init_parameters('gcc', None,
('version', version))
if command:
command = command[0]
common.handle_options('gcc', condition, command, options)
linker = feature.get_values('<linker-type>', options)
if not linker:
if os_name() == 'OSF':
linker = 'osf'
elif os_name() == 'HPUX':
linker = 'hpux' ;
else:
linker = 'gnu'
init_link_flags('gcc', linker, condition)
# If gcc is installed in non-standard location, we'd need to add
# LD_LIBRARY_PATH when running programs created with it (for unit-test/run
# rules).
if command:
# On multilib 64-bit boxes, there are both 32-bit and 64-bit libraries
# and all must be added to LD_LIBRARY_PATH. The linker will pick the
# right ones. Note that we don't provide a clean way to build 32-bit
# binary with 64-bit compiler, but user can always pass -m32 manually.
lib_path = [os.path.join(root, 'bin'),
os.path.join(root, 'lib'),
os.path.join(root, 'lib32'),
os.path.join(root, 'lib64')]
if debug():
print 'notice: using gcc libraries ::', condition, '::', lib_path
toolset.flags('gcc.link', 'RUN_PATH', condition, lib_path)
# If it's not a system gcc install we should adjust the various programs as
# needed to prefer using the install specific versions. This is essential
# for correct use of MinGW and for cross-compiling.
# - The archive builder.
archiver = common.get_invocation_command('gcc',
'ar', feature.get_values('<archiver>', options), [bin], path_last=True)
toolset.flags('gcc.archive', '.AR', condition, [archiver])
if debug():
print 'notice: using gcc archiver ::', condition, '::', archiver
# - Ranlib
ranlib = common.get_invocation_command('gcc',
'ranlib', feature.get_values('<ranlib>', options), [bin], path_last=True)
toolset.flags('gcc.archive', '.RANLIB', condition, [ranlib])
if debug():
print 'notice: using gcc archiver ::', condition, '::', ranlib
# - The resource compiler.
rc_command = common.get_invocation_command_nodefault('gcc',
'windres', feature.get_values('<rc>', options), [bin], path_last=True)
rc_type = feature.get_values('<rc-type>', options)
if not rc_type:
rc_type = 'windres'
if not rc_command:
# If we can't find an RC compiler we fallback to a null RC compiler that
# creates empty object files. This allows the same Jamfiles to work
# across the board. The null RC uses the assembler to create the empty
# objects, so configure that.
rc_command = common.get_invocation_command('gcc', 'as', [], [bin], path_last=True)
rc_type = 'null'
rc.configure([rc_command], condition, ['<rc-type>' + rc_type]) | [
"def",
"init",
"(",
"version",
"=",
"None",
",",
"command",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"to_seq",
"(",
"options",
")",
"command",
"=",
"to_seq",
"(",
"command",
")",
"# Information about the gcc command...",
"# The command.",
"command",
"=",
"to_seq",
"(",
"common",
".",
"get_invocation_command",
"(",
"'gcc'",
",",
"'g++'",
",",
"command",
")",
")",
"# The root directory of the tool install.",
"root",
"=",
"feature",
".",
"get_values",
"(",
"'<root>'",
",",
"options",
")",
"root",
"=",
"root",
"[",
"0",
"]",
"if",
"root",
"else",
"''",
"# The bin directory where to find the command to execute.",
"bin",
"=",
"None",
"# The flavor of compiler.",
"flavor",
"=",
"feature",
".",
"get_values",
"(",
"'<flavor>'",
",",
"options",
")",
"flavor",
"=",
"flavor",
"[",
"0",
"]",
"if",
"flavor",
"else",
"''",
"# Autodetect the root and bin dir if not given.",
"if",
"command",
":",
"if",
"not",
"bin",
":",
"bin",
"=",
"common",
".",
"get_absolute_tool_path",
"(",
"command",
"[",
"-",
"1",
"]",
")",
"if",
"not",
"root",
":",
"root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"bin",
")",
"# Autodetect the version and flavor if not given.",
"if",
"command",
":",
"machine_info",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
"+",
"[",
"'-dumpmachine'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"machine",
"=",
"__machine_match",
".",
"search",
"(",
"machine_info",
")",
".",
"group",
"(",
"1",
")",
"version_info",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
"+",
"[",
"'-dumpversion'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"version",
"=",
"__version_match",
".",
"search",
"(",
"version_info",
")",
".",
"group",
"(",
"1",
")",
"if",
"not",
"flavor",
"and",
"machine",
".",
"find",
"(",
"'mingw'",
")",
"!=",
"-",
"1",
":",
"flavor",
"=",
"'mingw'",
"condition",
"=",
"None",
"if",
"flavor",
":",
"condition",
"=",
"common",
".",
"check_init_parameters",
"(",
"'gcc'",
",",
"None",
",",
"(",
"'version'",
",",
"version",
")",
",",
"(",
"'flavor'",
",",
"flavor",
")",
")",
"else",
":",
"condition",
"=",
"common",
".",
"check_init_parameters",
"(",
"'gcc'",
",",
"None",
",",
"(",
"'version'",
",",
"version",
")",
")",
"if",
"command",
":",
"command",
"=",
"command",
"[",
"0",
"]",
"common",
".",
"handle_options",
"(",
"'gcc'",
",",
"condition",
",",
"command",
",",
"options",
")",
"linker",
"=",
"feature",
".",
"get_values",
"(",
"'<linker-type>'",
",",
"options",
")",
"if",
"not",
"linker",
":",
"if",
"os_name",
"(",
")",
"==",
"'OSF'",
":",
"linker",
"=",
"'osf'",
"elif",
"os_name",
"(",
")",
"==",
"'HPUX'",
":",
"linker",
"=",
"'hpux'",
"else",
":",
"linker",
"=",
"'gnu'",
"init_link_flags",
"(",
"'gcc'",
",",
"linker",
",",
"condition",
")",
"# If gcc is installed in non-standard location, we'd need to add",
"# LD_LIBRARY_PATH when running programs created with it (for unit-test/run",
"# rules).",
"if",
"command",
":",
"# On multilib 64-bit boxes, there are both 32-bit and 64-bit libraries",
"# and all must be added to LD_LIBRARY_PATH. The linker will pick the",
"# right ones. Note that we don't provide a clean way to build 32-bit",
"# binary with 64-bit compiler, but user can always pass -m32 manually.",
"lib_path",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'bin'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'lib'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'lib32'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'lib64'",
")",
"]",
"if",
"debug",
"(",
")",
":",
"print",
"'notice: using gcc libraries ::'",
",",
"condition",
",",
"'::'",
",",
"lib_path",
"toolset",
".",
"flags",
"(",
"'gcc.link'",
",",
"'RUN_PATH'",
",",
"condition",
",",
"lib_path",
")",
"# If it's not a system gcc install we should adjust the various programs as",
"# needed to prefer using the install specific versions. This is essential",
"# for correct use of MinGW and for cross-compiling.",
"# - The archive builder.",
"archiver",
"=",
"common",
".",
"get_invocation_command",
"(",
"'gcc'",
",",
"'ar'",
",",
"feature",
".",
"get_values",
"(",
"'<archiver>'",
",",
"options",
")",
",",
"[",
"bin",
"]",
",",
"path_last",
"=",
"True",
")",
"toolset",
".",
"flags",
"(",
"'gcc.archive'",
",",
"'.AR'",
",",
"condition",
",",
"[",
"archiver",
"]",
")",
"if",
"debug",
"(",
")",
":",
"print",
"'notice: using gcc archiver ::'",
",",
"condition",
",",
"'::'",
",",
"archiver",
"# - Ranlib",
"ranlib",
"=",
"common",
".",
"get_invocation_command",
"(",
"'gcc'",
",",
"'ranlib'",
",",
"feature",
".",
"get_values",
"(",
"'<ranlib>'",
",",
"options",
")",
",",
"[",
"bin",
"]",
",",
"path_last",
"=",
"True",
")",
"toolset",
".",
"flags",
"(",
"'gcc.archive'",
",",
"'.RANLIB'",
",",
"condition",
",",
"[",
"ranlib",
"]",
")",
"if",
"debug",
"(",
")",
":",
"print",
"'notice: using gcc archiver ::'",
",",
"condition",
",",
"'::'",
",",
"ranlib",
"# - The resource compiler.",
"rc_command",
"=",
"common",
".",
"get_invocation_command_nodefault",
"(",
"'gcc'",
",",
"'windres'",
",",
"feature",
".",
"get_values",
"(",
"'<rc>'",
",",
"options",
")",
",",
"[",
"bin",
"]",
",",
"path_last",
"=",
"True",
")",
"rc_type",
"=",
"feature",
".",
"get_values",
"(",
"'<rc-type>'",
",",
"options",
")",
"if",
"not",
"rc_type",
":",
"rc_type",
"=",
"'windres'",
"if",
"not",
"rc_command",
":",
"# If we can't find an RC compiler we fallback to a null RC compiler that",
"# creates empty object files. This allows the same Jamfiles to work",
"# across the board. The null RC uses the assembler to create the empty",
"# objects, so configure that.",
"rc_command",
"=",
"common",
".",
"get_invocation_command",
"(",
"'gcc'",
",",
"'as'",
",",
"[",
"]",
",",
"[",
"bin",
"]",
",",
"path_last",
"=",
"True",
")",
"rc_type",
"=",
"'null'",
"rc",
".",
"configure",
"(",
"[",
"rc_command",
"]",
",",
"condition",
",",
"[",
"'<rc-type>'",
"+",
"rc_type",
"]",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/tools/gcc.py#L87-L203 |
||
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/mac/Build/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/mac/Build/cpplint.py#L770-L772 |
|
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/jacoco_instr.py | python | _InstrumentClassFiles | (instrument_cmd,
input_path,
output_path,
temp_dir,
affected_source_files=None) | Instruments class files from input jar.
Args:
instrument_cmd: JaCoCo instrument command.
input_path: The input path to non-instrumented jar.
output_path: The output path to instrumented jar.
temp_dir: The temporary directory.
affected_source_files: The affected source file paths to input jar.
Default is None, which means instrumenting all class files in jar. | Instruments class files from input jar. | [
"Instruments",
"class",
"files",
"from",
"input",
"jar",
"."
] | def _InstrumentClassFiles(instrument_cmd,
input_path,
output_path,
temp_dir,
affected_source_files=None):
"""Instruments class files from input jar.
Args:
instrument_cmd: JaCoCo instrument command.
input_path: The input path to non-instrumented jar.
output_path: The output path to instrumented jar.
temp_dir: The temporary directory.
affected_source_files: The affected source file paths to input jar.
Default is None, which means instrumenting all class files in jar.
"""
affected_classes = None
unaffected_members = None
if affected_source_files:
affected_classes, unaffected_members = _GetAffectedClasses(
input_path, affected_source_files)
# Extract affected class files.
with zipfile.ZipFile(input_path) as f:
f.extractall(temp_dir, affected_classes)
instrumented_dir = os.path.join(temp_dir, 'instrumented')
# Instrument extracted class files.
instrument_cmd.extend([temp_dir, '--dest', instrumented_dir])
build_utils.CheckOutput(instrument_cmd)
if affected_source_files and unaffected_members:
# Extract unaffected members to instrumented_dir.
with zipfile.ZipFile(input_path) as f:
f.extractall(instrumented_dir, unaffected_members)
# Zip all files to output_path
build_utils.ZipDir(output_path, instrumented_dir) | [
"def",
"_InstrumentClassFiles",
"(",
"instrument_cmd",
",",
"input_path",
",",
"output_path",
",",
"temp_dir",
",",
"affected_source_files",
"=",
"None",
")",
":",
"affected_classes",
"=",
"None",
"unaffected_members",
"=",
"None",
"if",
"affected_source_files",
":",
"affected_classes",
",",
"unaffected_members",
"=",
"_GetAffectedClasses",
"(",
"input_path",
",",
"affected_source_files",
")",
"# Extract affected class files.",
"with",
"zipfile",
".",
"ZipFile",
"(",
"input_path",
")",
"as",
"f",
":",
"f",
".",
"extractall",
"(",
"temp_dir",
",",
"affected_classes",
")",
"instrumented_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"'instrumented'",
")",
"# Instrument extracted class files.",
"instrument_cmd",
".",
"extend",
"(",
"[",
"temp_dir",
",",
"'--dest'",
",",
"instrumented_dir",
"]",
")",
"build_utils",
".",
"CheckOutput",
"(",
"instrument_cmd",
")",
"if",
"affected_source_files",
"and",
"unaffected_members",
":",
"# Extract unaffected members to instrumented_dir.",
"with",
"zipfile",
".",
"ZipFile",
"(",
"input_path",
")",
"as",
"f",
":",
"f",
".",
"extractall",
"(",
"instrumented_dir",
",",
"unaffected_members",
")",
"# Zip all files to output_path",
"build_utils",
".",
"ZipDir",
"(",
"output_path",
",",
"instrumented_dir",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/jacoco_instr.py#L147-L184 |
||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/serialization.py | python | _class_and_config_for_serialized_keras_object | (
config,
module_objects=None,
custom_objects=None,
printable_module_name='object') | return (cls, cls_config) | Returns the class name and config for a serialized keras object. | Returns the class name and config for a serialized keras object. | [
"Returns",
"the",
"class",
"name",
"and",
"config",
"for",
"a",
"serialized",
"keras",
"object",
"."
] | def _class_and_config_for_serialized_keras_object(
config,
module_objects=None,
custom_objects=None,
printable_module_name='object'):
"""Returns the class name and config for a serialized keras object."""
if (not isinstance(config, dict) or 'class_name' not in config or
'config' not in config):
raise ValueError('Improper config format: ' + str(config))
class_name = config['class_name']
cls = _get_registered_object(class_name, custom_objects=custom_objects,
module_objects=module_objects)
if cls is None:
raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
cls_config = config['config']
deserialized_objects = {}
for key, item in cls_config.items():
if isinstance(item, dict) and '__passive_serialization__' in item:
deserialized_objects[key] = _deserialize_keras_object(
item,
module_objects=module_objects,
custom_objects=custom_objects,
printable_module_name='config_item')
elif (isinstance(item, six.string_types) and
tf_inspect.isfunction(_get_registered_object(item, custom_objects))):
# Handle custom functions here. When saving functions, we only save the
# function's name as a string. If we find a matching string in the custom
# objects during deserialization, we convert the string back to the
# original function.
# Note that a potential issue is that a string field could have a naming
# conflict with a custom function name, but this should be a rare case.
# This issue does not occur if a string field has a naming conflict with
# a custom object, since the config of an object will always be a dict.
deserialized_objects[key] = _get_registered_object(item, custom_objects)
for key, item in deserialized_objects.items():
cls_config[key] = deserialized_objects[key]
return (cls, cls_config) | [
"def",
"_class_and_config_for_serialized_keras_object",
"(",
"config",
",",
"module_objects",
"=",
"None",
",",
"custom_objects",
"=",
"None",
",",
"printable_module_name",
"=",
"'object'",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"config",
",",
"dict",
")",
"or",
"'class_name'",
"not",
"in",
"config",
"or",
"'config'",
"not",
"in",
"config",
")",
":",
"raise",
"ValueError",
"(",
"'Improper config format: '",
"+",
"str",
"(",
"config",
")",
")",
"class_name",
"=",
"config",
"[",
"'class_name'",
"]",
"cls",
"=",
"_get_registered_object",
"(",
"class_name",
",",
"custom_objects",
"=",
"custom_objects",
",",
"module_objects",
"=",
"module_objects",
")",
"if",
"cls",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown '",
"+",
"printable_module_name",
"+",
"': '",
"+",
"class_name",
")",
"cls_config",
"=",
"config",
"[",
"'config'",
"]",
"deserialized_objects",
"=",
"{",
"}",
"for",
"key",
",",
"item",
"in",
"cls_config",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
"and",
"'__passive_serialization__'",
"in",
"item",
":",
"deserialized_objects",
"[",
"key",
"]",
"=",
"_deserialize_keras_object",
"(",
"item",
",",
"module_objects",
"=",
"module_objects",
",",
"custom_objects",
"=",
"custom_objects",
",",
"printable_module_name",
"=",
"'config_item'",
")",
"elif",
"(",
"isinstance",
"(",
"item",
",",
"six",
".",
"string_types",
")",
"and",
"tf_inspect",
".",
"isfunction",
"(",
"_get_registered_object",
"(",
"item",
",",
"custom_objects",
")",
")",
")",
":",
"# Handle custom functions here. When saving functions, we only save the",
"# function's name as a string. If we find a matching string in the custom",
"# objects during deserialization, we convert the string back to the",
"# original function.",
"# Note that a potential issue is that a string field could have a naming",
"# conflict with a custom function name, but this should be a rare case.",
"# This issue does not occur if a string field has a naming conflict with",
"# a custom object, since the config of an object will always be a dict.",
"deserialized_objects",
"[",
"key",
"]",
"=",
"_get_registered_object",
"(",
"item",
",",
"custom_objects",
")",
"for",
"key",
",",
"item",
"in",
"deserialized_objects",
".",
"items",
"(",
")",
":",
"cls_config",
"[",
"key",
"]",
"=",
"deserialized_objects",
"[",
"key",
"]",
"return",
"(",
"cls",
",",
"cls_config",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/serialization.py#L289-L329 |
|
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/compiler.py | python | CodeGenerator.parameter_is_undeclared | (self, target) | return target in self._param_def_block[-1] | Checks if a given target is an undeclared parameter. | Checks if a given target is an undeclared parameter. | [
"Checks",
"if",
"a",
"given",
"target",
"is",
"an",
"undeclared",
"parameter",
"."
] | def parameter_is_undeclared(self, target):
"""Checks if a given target is an undeclared parameter."""
if not self._param_def_block:
return False
return target in self._param_def_block[-1] | [
"def",
"parameter_is_undeclared",
"(",
"self",
",",
"target",
")",
":",
"if",
"not",
"self",
".",
"_param_def_block",
":",
"return",
"False",
"return",
"target",
"in",
"self",
".",
"_param_def_block",
"[",
"-",
"1",
"]"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/compiler.py#L655-L659 |
|
networkit/networkit | 695b7a786a894a303fa8587597d5ef916e797729 | networkit/profiling/plot.py | python | Theme.set | (self, style="light", color=(0, 0, 1)) | sets style and color of the theme
Args:
style: ("light")
color: RGB tuple | sets style and color of the theme
Args:
style: ("light")
color: RGB tuple | [
"sets",
"style",
"and",
"color",
"of",
"the",
"theme",
"Args",
":",
"style",
":",
"(",
"light",
")",
"color",
":",
"RGB",
"tuple"
] | def set(self, style="light", color=(0, 0, 1)):
""" sets style and color of the theme
Args:
style: ("light")
color: RGB tuple
"""
if not have_mpl:
raise MissingDependencyError("matplotlib")
optionsStyle = ["light", "system"]
if style not in optionsStyle:
raise ValueError("possible style options: " + str(optionsStyle))
if len(color) != 3:
raise ValueError("(r,g,b) tuple required")
if style == "system":
self.__rcParams = mpl.rcParams
raise ValueError("not implemented, yet")
if style == "light":
self.__defaultColor = (0, 0, 0)
self.__defaultWidth = 1
self.__backgroundColor = (1, 1, 1)
self.__plotColor = Theme.RGBA2RGB(color, 0.6, self.__backgroundColor)
self.__plotWidth = 3
self.__faceColor = (color[0], color[1], color[2], 0.2)
self.__faceColorGray = "lightgray"
self.__edgeColor = (color[0], color[1], color[2], 0.6)
self.__edgeColorGray = (0, 0, 0)
self.__edgeWidth = 1
self.__gridColor = "lightgray"
self.__fontColor = (0, 0, 0)
self.__fontSize = 10
self.__color = color
self.__style = style | [
"def",
"set",
"(",
"self",
",",
"style",
"=",
"\"light\"",
",",
"color",
"=",
"(",
"0",
",",
"0",
",",
"1",
")",
")",
":",
"if",
"not",
"have_mpl",
":",
"raise",
"MissingDependencyError",
"(",
"\"matplotlib\"",
")",
"optionsStyle",
"=",
"[",
"\"light\"",
",",
"\"system\"",
"]",
"if",
"style",
"not",
"in",
"optionsStyle",
":",
"raise",
"ValueError",
"(",
"\"possible style options: \"",
"+",
"str",
"(",
"optionsStyle",
")",
")",
"if",
"len",
"(",
"color",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"(r,g,b) tuple required\"",
")",
"if",
"style",
"==",
"\"system\"",
":",
"self",
".",
"__rcParams",
"=",
"mpl",
".",
"rcParams",
"raise",
"ValueError",
"(",
"\"not implemented, yet\"",
")",
"if",
"style",
"==",
"\"light\"",
":",
"self",
".",
"__defaultColor",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
"self",
".",
"__defaultWidth",
"=",
"1",
"self",
".",
"__backgroundColor",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
"self",
".",
"__plotColor",
"=",
"Theme",
".",
"RGBA2RGB",
"(",
"color",
",",
"0.6",
",",
"self",
".",
"__backgroundColor",
")",
"self",
".",
"__plotWidth",
"=",
"3",
"self",
".",
"__faceColor",
"=",
"(",
"color",
"[",
"0",
"]",
",",
"color",
"[",
"1",
"]",
",",
"color",
"[",
"2",
"]",
",",
"0.2",
")",
"self",
".",
"__faceColorGray",
"=",
"\"lightgray\"",
"self",
".",
"__edgeColor",
"=",
"(",
"color",
"[",
"0",
"]",
",",
"color",
"[",
"1",
"]",
",",
"color",
"[",
"2",
"]",
",",
"0.6",
")",
"self",
".",
"__edgeColorGray",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
"self",
".",
"__edgeWidth",
"=",
"1",
"self",
".",
"__gridColor",
"=",
"\"lightgray\"",
"self",
".",
"__fontColor",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
"self",
".",
"__fontSize",
"=",
"10",
"self",
".",
"__color",
"=",
"color",
"self",
".",
"__style",
"=",
"style"
] | https://github.com/networkit/networkit/blob/695b7a786a894a303fa8587597d5ef916e797729/networkit/profiling/plot.py#L43-L78 |
||
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/win/Source/bin/jinja2/lexer.py | python | Lexer._normalize_newlines | (self, value) | return newline_re.sub(self.newline_sequence, value) | Called for strings and template data to normlize it to unicode. | Called for strings and template data to normlize it to unicode. | [
"Called",
"for",
"strings",
"and",
"template",
"data",
"to",
"normlize",
"it",
"to",
"unicode",
"."
] | def _normalize_newlines(self, value):
"""Called for strings and template data to normlize it to unicode."""
return newline_re.sub(self.newline_sequence, value) | [
"def",
"_normalize_newlines",
"(",
"self",
",",
"value",
")",
":",
"return",
"newline_re",
".",
"sub",
"(",
"self",
".",
"newline_sequence",
",",
"value",
")"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/lexer.py#L456-L458 |
|
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/ultisnips/plugin/UltiSnips/text_objects/_parser.py | python | TOParser.__init__ | (self, parent_to, text, indent) | The parser is responsible for turning tokens into Real TextObjects | The parser is responsible for turning tokens into Real TextObjects | [
"The",
"parser",
"is",
"responsible",
"for",
"turning",
"tokens",
"into",
"Real",
"TextObjects"
] | def __init__(self, parent_to, text, indent):
"""
The parser is responsible for turning tokens into Real TextObjects
"""
self._indent = indent
self._parent_to = parent_to
self._text = text | [
"def",
"__init__",
"(",
"self",
",",
"parent_to",
",",
"text",
",",
"indent",
")",
":",
"self",
".",
"_indent",
"=",
"indent",
"self",
".",
"_parent_to",
"=",
"parent_to",
"self",
".",
"_text",
"=",
"text"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/ultisnips/plugin/UltiSnips/text_objects/_parser.py#L28-L34 |
||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-filter/python/filter/qa_pm_remez.py | python | lporder | (freq1, freq2, delta_p, delta_s) | return n | FIR lowpass filter length estimator. | FIR lowpass filter length estimator. | [
"FIR",
"lowpass",
"filter",
"length",
"estimator",
"."
] | def lporder(freq1, freq2, delta_p, delta_s):
'''
FIR lowpass filter length estimator.
'''
df = abs(freq2 - freq1)
ddp = math.log10(delta_p)
dds = math.log10(delta_s)
a1 = 5.309e-3
a2 = 7.114e-2
a3 = -4.761e-1
a4 = -2.66e-3
a5 = -5.941e-1
a6 = -4.278e-1
b1 = 11.01217
b2 = 0.5124401
t1 = a1 * ddp * ddp
t2 = a2 * ddp
t3 = a4 * ddp * ddp
t4 = a5 * ddp
dinf = ((t1 + t2 + a3) * dds) + (t3 + t4 + a6)
ff = b1 + b2 * (ddp - dds)
n = dinf / df - ff * df + 1
return n | [
"def",
"lporder",
"(",
"freq1",
",",
"freq2",
",",
"delta_p",
",",
"delta_s",
")",
":",
"df",
"=",
"abs",
"(",
"freq2",
"-",
"freq1",
")",
"ddp",
"=",
"math",
".",
"log10",
"(",
"delta_p",
")",
"dds",
"=",
"math",
".",
"log10",
"(",
"delta_s",
")",
"a1",
"=",
"5.309e-3",
"a2",
"=",
"7.114e-2",
"a3",
"=",
"-",
"4.761e-1",
"a4",
"=",
"-",
"2.66e-3",
"a5",
"=",
"-",
"5.941e-1",
"a6",
"=",
"-",
"4.278e-1",
"b1",
"=",
"11.01217",
"b2",
"=",
"0.5124401",
"t1",
"=",
"a1",
"*",
"ddp",
"*",
"ddp",
"t2",
"=",
"a2",
"*",
"ddp",
"t3",
"=",
"a4",
"*",
"ddp",
"*",
"ddp",
"t4",
"=",
"a5",
"*",
"ddp",
"dinf",
"=",
"(",
"(",
"t1",
"+",
"t2",
"+",
"a3",
")",
"*",
"dds",
")",
"+",
"(",
"t3",
"+",
"t4",
"+",
"a6",
")",
"ff",
"=",
"b1",
"+",
"b2",
"*",
"(",
"ddp",
"-",
"dds",
")",
"n",
"=",
"dinf",
"/",
"df",
"-",
"ff",
"*",
"df",
"+",
"1",
"return",
"n"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-filter/python/filter/qa_pm_remez.py#L103-L129 |
|
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | src/visualizer/visualizer/ipython_view.py | python | ConsoleView.write | (self, text, editable=False) | !
Write given text to buffer.
@param text: Text to append.
@param editable: If true, added text is editable.
@return none | !
Write given text to buffer. | [
"!",
"Write",
"given",
"text",
"to",
"buffer",
"."
] | def write(self, text, editable=False):
"""!
Write given text to buffer.
@param text: Text to append.
@param editable: If true, added text is editable.
@return none
"""
GObject.idle_add(self._write, text, editable) | [
"def",
"write",
"(",
"self",
",",
"text",
",",
"editable",
"=",
"False",
")",
":",
"GObject",
".",
"idle_add",
"(",
"self",
".",
"_write",
",",
"text",
",",
"editable",
")"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/src/visualizer/visualizer/ipython_view.py#L390-L398 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewEvent.SetDataFormat | (*args, **kwargs) | return _dataview.DataViewEvent_SetDataFormat(*args, **kwargs) | SetDataFormat(self, wxDataFormat format) | SetDataFormat(self, wxDataFormat format) | [
"SetDataFormat",
"(",
"self",
"wxDataFormat",
"format",
")"
] | def SetDataFormat(*args, **kwargs):
"""SetDataFormat(self, wxDataFormat format)"""
return _dataview.DataViewEvent_SetDataFormat(*args, **kwargs) | [
"def",
"SetDataFormat",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewEvent_SetDataFormat",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1975-L1977 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py | python | ZipExtFile.readline | (self, limit=-1) | return line | Read and return a line from the stream.
If limit is specified, at most limit bytes will be read. | Read and return a line from the stream. | [
"Read",
"and",
"return",
"a",
"line",
"from",
"the",
"stream",
"."
] | def readline(self, limit=-1):
"""Read and return a line from the stream.
If limit is specified, at most limit bytes will be read.
"""
if not self._universal and limit < 0:
# Shortcut common case - newline found in buffer.
i = self._readbuffer.find('\n', self._offset) + 1
if i > 0:
line = self._readbuffer[self._offset: i]
self._offset = i
return line
if not self._universal:
return io.BufferedIOBase.readline(self, limit)
line = ''
while limit < 0 or len(line) < limit:
readahead = self.peek(2)
if readahead == '':
return line
#
# Search for universal newlines or line chunks.
#
# The pattern returns either a line chunk or a newline, but not
# both. Combined with peek(2), we are assured that the sequence
# '\r\n' is always retrieved completely and never split into
# separate newlines - '\r', '\n' due to coincidental readaheads.
#
match = self.PATTERN.search(readahead)
newline = match.group('newline')
if newline is not None:
if self.newlines is None:
self.newlines = []
if newline not in self.newlines:
self.newlines.append(newline)
self._offset += len(newline)
return line + '\n'
chunk = match.group('chunk')
if limit >= 0:
chunk = chunk[: limit - len(line)]
self._offset += len(chunk)
line += chunk
return line | [
"def",
"readline",
"(",
"self",
",",
"limit",
"=",
"-",
"1",
")",
":",
"if",
"not",
"self",
".",
"_universal",
"and",
"limit",
"<",
"0",
":",
"# Shortcut common case - newline found in buffer.",
"i",
"=",
"self",
".",
"_readbuffer",
".",
"find",
"(",
"'\\n'",
",",
"self",
".",
"_offset",
")",
"+",
"1",
"if",
"i",
">",
"0",
":",
"line",
"=",
"self",
".",
"_readbuffer",
"[",
"self",
".",
"_offset",
":",
"i",
"]",
"self",
".",
"_offset",
"=",
"i",
"return",
"line",
"if",
"not",
"self",
".",
"_universal",
":",
"return",
"io",
".",
"BufferedIOBase",
".",
"readline",
"(",
"self",
",",
"limit",
")",
"line",
"=",
"''",
"while",
"limit",
"<",
"0",
"or",
"len",
"(",
"line",
")",
"<",
"limit",
":",
"readahead",
"=",
"self",
".",
"peek",
"(",
"2",
")",
"if",
"readahead",
"==",
"''",
":",
"return",
"line",
"#",
"# Search for universal newlines or line chunks.",
"#",
"# The pattern returns either a line chunk or a newline, but not",
"# both. Combined with peek(2), we are assured that the sequence",
"# '\\r\\n' is always retrieved completely and never split into",
"# separate newlines - '\\r', '\\n' due to coincidental readaheads.",
"#",
"match",
"=",
"self",
".",
"PATTERN",
".",
"search",
"(",
"readahead",
")",
"newline",
"=",
"match",
".",
"group",
"(",
"'newline'",
")",
"if",
"newline",
"is",
"not",
"None",
":",
"if",
"self",
".",
"newlines",
"is",
"None",
":",
"self",
".",
"newlines",
"=",
"[",
"]",
"if",
"newline",
"not",
"in",
"self",
".",
"newlines",
":",
"self",
".",
"newlines",
".",
"append",
"(",
"newline",
")",
"self",
".",
"_offset",
"+=",
"len",
"(",
"newline",
")",
"return",
"line",
"+",
"'\\n'",
"chunk",
"=",
"match",
".",
"group",
"(",
"'chunk'",
")",
"if",
"limit",
">=",
"0",
":",
"chunk",
"=",
"chunk",
"[",
":",
"limit",
"-",
"len",
"(",
"line",
")",
"]",
"self",
".",
"_offset",
"+=",
"len",
"(",
"chunk",
")",
"line",
"+=",
"chunk",
"return",
"line"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py#L555-L603 |
|
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/filters.py | python | do_selectattr | (*args, **kwargs) | return select_or_reject(args, kwargs, lambda x: x, True) | Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
.. versionadded:: 2.7 | Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding. | [
"Filters",
"a",
"sequence",
"of",
"objects",
"by",
"applying",
"a",
"test",
"to",
"the",
"specified",
"attribute",
"of",
"each",
"object",
"and",
"only",
"selecting",
"the",
"objects",
"with",
"the",
"test",
"succeeding",
"."
] | def do_selectattr(*args, **kwargs):
"""Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
.. versionadded:: 2.7
"""
return select_or_reject(args, kwargs, lambda x: x, True) | [
"def",
"do_selectattr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"x",
",",
"True",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/filters.py#L1007-L1024 |
|
tensor-compiler/taco | d0654a84137169883973c40a951dfdb89883fd9c | python_bindings/pytaco/pytensor/taco_tensor.py | python | tensor_max | (t1, t2, out_format, dtype=None) | return _compute_bin_elt_wise_op(_cm.max, t1, t2, out_format, dtype) | Computes the element wise maximum of two tensors.
* If the two tensors are equal order, performs the operation element-wise
* If the two tensors have order N and M and N > M, requires the last M dimensions of the tensor with
order N be equal to the dimensions of the tensor with order M in order to broadcast.
Parameters
-----------
t1, t2: tensors, array_like
tensors or array_like input operands.
out_format: format, mode_format
* If a :class:`format` is specified, the result tensor is stored in the format out_format.
* If a :class:`mode_format` is specified, the result the result tensor has a with all of the dimensions
stored in the :class:`mode_format` passed in.
dtype: Datatype, optional
The datatype of the output tensor.
Notes
--------
The inner dimensions of the input tensor is broadcasted along the dimensions of whichever tensor has a higher
order.
Returns
---------
max: tensor
The element wise maximum of the input tensors broadcasted as required. | Computes the element wise maximum of two tensors. | [
"Computes",
"the",
"element",
"wise",
"maximum",
"of",
"two",
"tensors",
"."
] | def tensor_max(t1, t2, out_format, dtype=None):
"""
Computes the element wise maximum of two tensors.
* If the two tensors are equal order, performs the operation element-wise
* If the two tensors have order N and M and N > M, requires the last M dimensions of the tensor with
order N be equal to the dimensions of the tensor with order M in order to broadcast.
Parameters
-----------
t1, t2: tensors, array_like
tensors or array_like input operands.
out_format: format, mode_format
* If a :class:`format` is specified, the result tensor is stored in the format out_format.
* If a :class:`mode_format` is specified, the result the result tensor has a with all of the dimensions
stored in the :class:`mode_format` passed in.
dtype: Datatype, optional
The datatype of the output tensor.
Notes
--------
The inner dimensions of the input tensor is broadcasted along the dimensions of whichever tensor has a higher
order.
Returns
---------
max: tensor
The element wise maximum of the input tensors broadcasted as required.
"""
return _compute_bin_elt_wise_op(_cm.max, t1, t2, out_format, dtype) | [
"def",
"tensor_max",
"(",
"t1",
",",
"t2",
",",
"out_format",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"_compute_bin_elt_wise_op",
"(",
"_cm",
".",
"max",
",",
"t1",
",",
"t2",
",",
"out_format",
",",
"dtype",
")"
] | https://github.com/tensor-compiler/taco/blob/d0654a84137169883973c40a951dfdb89883fd9c/python_bindings/pytaco/pytensor/taco_tensor.py#L1336-L1369 |
|
vmware/concord-bft | ec036a384b4c81be0423d4b429bd37900b13b864 | tools/run-clang-tidy.py | python | merge_replacement_files | (tmpdir, mergefile) | Merge all replacement files in a directory into a single file | Merge all replacement files in a directory into a single file | [
"Merge",
"all",
"replacement",
"files",
"in",
"a",
"directory",
"into",
"a",
"single",
"file"
] | def merge_replacement_files(tmpdir, mergefile):
"""Merge all replacement files in a directory into a single file"""
# The fixes suggested by clang-tidy >= 4.0.0 are given under
# the top level key 'Diagnostics' in the output yaml files
mergekey="Diagnostics"
merged=[]
for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
content = yaml.safe_load(open(replacefile, 'r'))
if not content:
continue # Skip empty files.
merged.extend(content.get(mergekey, []))
if merged:
# MainSourceFile: The key is required by the definition inside
# include/clang/Tooling/ReplacementsYaml.h, but the value
# is actually never used inside clang-apply-replacements,
# so we set it to '' here.
output = { 'MainSourceFile': '', mergekey: merged }
with open(mergefile, 'w') as out:
yaml.safe_dump(output, out)
else:
# Empty the file:
open(mergefile, 'w').close() | [
"def",
"merge_replacement_files",
"(",
"tmpdir",
",",
"mergefile",
")",
":",
"# The fixes suggested by clang-tidy >= 4.0.0 are given under",
"# the top level key 'Diagnostics' in the output yaml files",
"mergekey",
"=",
"\"Diagnostics\"",
"merged",
"=",
"[",
"]",
"for",
"replacefile",
"in",
"glob",
".",
"iglob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"'*.yaml'",
")",
")",
":",
"content",
"=",
"yaml",
".",
"safe_load",
"(",
"open",
"(",
"replacefile",
",",
"'r'",
")",
")",
"if",
"not",
"content",
":",
"continue",
"# Skip empty files.",
"merged",
".",
"extend",
"(",
"content",
".",
"get",
"(",
"mergekey",
",",
"[",
"]",
")",
")",
"if",
"merged",
":",
"# MainSourceFile: The key is required by the definition inside",
"# include/clang/Tooling/ReplacementsYaml.h, but the value",
"# is actually never used inside clang-apply-replacements,",
"# so we set it to '' here.",
"output",
"=",
"{",
"'MainSourceFile'",
":",
"''",
",",
"mergekey",
":",
"merged",
"}",
"with",
"open",
"(",
"mergefile",
",",
"'w'",
")",
"as",
"out",
":",
"yaml",
".",
"safe_dump",
"(",
"output",
",",
"out",
")",
"else",
":",
"# Empty the file:",
"open",
"(",
"mergefile",
",",
"'w'",
")",
".",
"close",
"(",
")"
] | https://github.com/vmware/concord-bft/blob/ec036a384b4c81be0423d4b429bd37900b13b864/tools/run-clang-tidy.py#L132-L154 |
||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | samples/python/uff_ssd/utils/coco.py | python | is_coco_label | (label) | return label in COCO_CLASSES_SET | Returns boolean which tells if given label is COCO label.
Args:
label (str): object label
Returns:
bool: is given label a COCO class label | Returns boolean which tells if given label is COCO label. | [
"Returns",
"boolean",
"which",
"tells",
"if",
"given",
"label",
"is",
"COCO",
"label",
"."
] | def is_coco_label(label):
"""Returns boolean which tells if given label is COCO label.
Args:
label (str): object label
Returns:
bool: is given label a COCO class label
"""
return label in COCO_CLASSES_SET | [
"def",
"is_coco_label",
"(",
"label",
")",
":",
"return",
"label",
"in",
"COCO_CLASSES_SET"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/uff_ssd/utils/coco.py#L126-L134 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/core.py | python | read_data | (fobj, coding, count, bit_width) | return out | For definition and repetition levels
Reads with RLE/bitpacked hybrid, where length is given by first byte. | For definition and repetition levels | [
"For",
"definition",
"and",
"repetition",
"levels"
] | def read_data(fobj, coding, count, bit_width):
"""For definition and repetition levels
Reads with RLE/bitpacked hybrid, where length is given by first byte.
"""
out = np.empty(count, dtype=np.int32)
o = encoding.Numpy32(out)
if coding == parquet_thrift.Encoding.RLE:
while o.loc < count:
encoding.read_rle_bit_packed_hybrid(fobj, bit_width, o=o)
else:
raise NotImplementedError('Encoding %s' % coding)
return out | [
"def",
"read_data",
"(",
"fobj",
",",
"coding",
",",
"count",
",",
"bit_width",
")",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"count",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"o",
"=",
"encoding",
".",
"Numpy32",
"(",
"out",
")",
"if",
"coding",
"==",
"parquet_thrift",
".",
"Encoding",
".",
"RLE",
":",
"while",
"o",
".",
"loc",
"<",
"count",
":",
"encoding",
".",
"read_rle_bit_packed_hybrid",
"(",
"fobj",
",",
"bit_width",
",",
"o",
"=",
"o",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Encoding %s'",
"%",
"coding",
")",
"return",
"out"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/core.py#L35-L47 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/tkFileDialog.py | python | asksaveasfilename | (**options) | return SaveAs(**options).show() | Ask for a filename to save as | Ask for a filename to save as | [
"Ask",
"for",
"a",
"filename",
"to",
"save",
"as"
] | def asksaveasfilename(**options):
"Ask for a filename to save as"
return SaveAs(**options).show() | [
"def",
"asksaveasfilename",
"(",
"*",
"*",
"options",
")",
":",
"return",
"SaveAs",
"(",
"*",
"*",
"options",
")",
".",
"show",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/tkFileDialog.py#L127-L130 |
|
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/servermanager.py | python | ArrayListProperty.__len__ | (self) | return len(self.GetData()) | Returns the number of elements. | Returns the number of elements. | [
"Returns",
"the",
"number",
"of",
"elements",
"."
] | def __len__(self):
"""Returns the number of elements."""
return len(self.GetData()) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"GetData",
"(",
")",
")"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/servermanager.py#L1145-L1147 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py | python | _makeOperator | (operatorInput, expectedShape) | return operator | Takes a dense numpy array or a sparse matrix or
a function and makes an operator performing matrix * blockvector
products.
Examples
--------
>>> A = _makeOperator( arrayA, (n, n) )
>>> vectorB = A( vectorX ) | Takes a dense numpy array or a sparse matrix or
a function and makes an operator performing matrix * blockvector
products. | [
"Takes",
"a",
"dense",
"numpy",
"array",
"or",
"a",
"sparse",
"matrix",
"or",
"a",
"function",
"and",
"makes",
"an",
"operator",
"performing",
"matrix",
"*",
"blockvector",
"products",
"."
] | def _makeOperator(operatorInput, expectedShape):
"""Takes a dense numpy array or a sparse matrix or
a function and makes an operator performing matrix * blockvector
products.
Examples
--------
>>> A = _makeOperator( arrayA, (n, n) )
>>> vectorB = A( vectorX )
"""
if operatorInput is None:
def ident(x):
return x
operator = LinearOperator(expectedShape, ident, matmat=ident)
else:
operator = aslinearoperator(operatorInput)
if operator.shape != expectedShape:
raise ValueError('operator has invalid shape')
return operator | [
"def",
"_makeOperator",
"(",
"operatorInput",
",",
"expectedShape",
")",
":",
"if",
"operatorInput",
"is",
"None",
":",
"def",
"ident",
"(",
"x",
")",
":",
"return",
"x",
"operator",
"=",
"LinearOperator",
"(",
"expectedShape",
",",
"ident",
",",
"matmat",
"=",
"ident",
")",
"else",
":",
"operator",
"=",
"aslinearoperator",
"(",
"operatorInput",
")",
"if",
"operator",
".",
"shape",
"!=",
"expectedShape",
":",
"raise",
"ValueError",
"(",
"'operator has invalid shape'",
")",
"return",
"operator"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py#L63-L84 |
|
infinit/elle | a8154593c42743f45b9df09daf62b44630c24a02 | drake/src/drake/sched.py | python | Coroutine.step | (self) | Execute one step of the coroutine, until the next yield or freeze. | Execute one step of the coroutine, until the next yield or freeze. | [
"Execute",
"one",
"step",
"of",
"the",
"coroutine",
"until",
"the",
"next",
"yield",
"or",
"freeze",
"."
] | def step(self):
"""Execute one step of the coroutine, until the next yield or freeze."""
if self.done:
raise CoroutineDone()
if self.frozen:
raise CoroutineFrozen()
self.__started = True
self.__coro.parent = greenlet.getcurrent()
prev = Coroutine.__current
try:
Coroutine.__current = self
self.__coro.switch()
except Terminate:
assert not self.__coro
self.__done_set()
except Exception as e:
self.__done_set(e)
self.__traceback = e.__traceback__.tb_next
raise
else:
if not self.__coro:
self.__done_set()
finally:
Coroutine.__current = prev | [
"def",
"step",
"(",
"self",
")",
":",
"if",
"self",
".",
"done",
":",
"raise",
"CoroutineDone",
"(",
")",
"if",
"self",
".",
"frozen",
":",
"raise",
"CoroutineFrozen",
"(",
")",
"self",
".",
"__started",
"=",
"True",
"self",
".",
"__coro",
".",
"parent",
"=",
"greenlet",
".",
"getcurrent",
"(",
")",
"prev",
"=",
"Coroutine",
".",
"__current",
"try",
":",
"Coroutine",
".",
"__current",
"=",
"self",
"self",
".",
"__coro",
".",
"switch",
"(",
")",
"except",
"Terminate",
":",
"assert",
"not",
"self",
".",
"__coro",
"self",
".",
"__done_set",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"__done_set",
"(",
"e",
")",
"self",
".",
"__traceback",
"=",
"e",
".",
"__traceback__",
".",
"tb_next",
"raise",
"else",
":",
"if",
"not",
"self",
".",
"__coro",
":",
"self",
".",
"__done_set",
"(",
")",
"finally",
":",
"Coroutine",
".",
"__current",
"=",
"prev"
] | https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/sched.py#L509-L532 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/symtable.py | python | Symbol.get_namespace | (self) | return self.__namespaces[0] | Returns the single namespace bound to this name.
Raises ValueError if the name is bound to multiple namespaces. | Returns the single namespace bound to this name. | [
"Returns",
"the",
"single",
"namespace",
"bound",
"to",
"this",
"name",
"."
] | def get_namespace(self):
"""Returns the single namespace bound to this name.
Raises ValueError if the name is bound to multiple namespaces.
"""
if len(self.__namespaces) != 1:
raise ValueError, "name is bound to multiple namespaces"
return self.__namespaces[0] | [
"def",
"get_namespace",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"__namespaces",
")",
"!=",
"1",
":",
"raise",
"ValueError",
",",
"\"name is bound to multiple namespaces\"",
"return",
"self",
".",
"__namespaces",
"[",
"0",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/symtable.py#L227-L234 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/__init__.py | python | Environment.add | (self, dist) | Add `dist` if we ``can_add()`` it and it has not already been added | Add `dist` if we ``can_add()`` it and it has not already been added | [
"Add",
"dist",
"if",
"we",
"can_add",
"()",
"it",
"and",
"it",
"has",
"not",
"already",
"been",
"added"
] | def add(self, dist):
"""Add `dist` if we ``can_add()`` it and it has not already been added
"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True) | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"self",
".",
"can_add",
"(",
"dist",
")",
"and",
"dist",
".",
"has_version",
"(",
")",
":",
"dists",
"=",
"self",
".",
"_distmap",
".",
"setdefault",
"(",
"dist",
".",
"key",
",",
"[",
"]",
")",
"if",
"dist",
"not",
"in",
"dists",
":",
"dists",
".",
"append",
"(",
"dist",
")",
"dists",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'hashcmp'",
")",
",",
"reverse",
"=",
"True",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L1021-L1028 |
||
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py | python | ISkype.Voicemail | (self, Id) | return o | Queries the voicemail object.
@param Id: Voicemail Id.
@type Id: int
@return: A voicemail object.
@rtype: L{IVoicemail} | Queries the voicemail object. | [
"Queries",
"the",
"voicemail",
"object",
"."
] | def Voicemail(self, Id):
'''Queries the voicemail object.
@param Id: Voicemail Id.
@type Id: int
@return: A voicemail object.
@rtype: L{IVoicemail}
'''
o = IVoicemail(Id, self)
o.Type
return o | [
"def",
"Voicemail",
"(",
"self",
",",
"Id",
")",
":",
"o",
"=",
"IVoicemail",
"(",
"Id",
",",
"self",
")",
"o",
".",
"Type",
"return",
"o"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py#L874-L884 |
|
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/cpp.py | python | PreProcessor.stop_handling_includes | (self, t=None) | Causes the PreProcessor object to stop processing #import,
#include and #include_next lines.
This method will be called when a #if, #ifdef, #ifndef or #elif
evaluates False, or when we reach the #else in a #if, #ifdef,
#ifndef or #elif block where a condition already evaluated True. | Causes the PreProcessor object to stop processing #import,
#include and #include_next lines. | [
"Causes",
"the",
"PreProcessor",
"object",
"to",
"stop",
"processing",
"#import",
"#include",
"and",
"#include_next",
"lines",
"."
] | def stop_handling_includes(self, t=None):
"""
Causes the PreProcessor object to stop processing #import,
#include and #include_next lines.
This method will be called when a #if, #ifdef, #ifndef or #elif
evaluates False, or when we reach the #else in a #if, #ifdef,
#ifndef or #elif block where a condition already evaluated True.
"""
d = self.dispatch_table
d['import'] = self.do_nothing
d['include'] = self.do_nothing
d['include_next'] = self.do_nothing
d['define'] = self.do_nothing
d['undef'] = self.do_nothing | [
"def",
"stop_handling_includes",
"(",
"self",
",",
"t",
"=",
"None",
")",
":",
"d",
"=",
"self",
".",
"dispatch_table",
"d",
"[",
"'import'",
"]",
"=",
"self",
".",
"do_nothing",
"d",
"[",
"'include'",
"]",
"=",
"self",
".",
"do_nothing",
"d",
"[",
"'include_next'",
"]",
"=",
"self",
".",
"do_nothing",
"d",
"[",
"'define'",
"]",
"=",
"self",
".",
"do_nothing",
"d",
"[",
"'undef'",
"]",
"=",
"self",
".",
"do_nothing"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/cpp.py#L442-L456 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Image.SetRGB | (*args, **kwargs) | return _core_.Image_SetRGB(*args, **kwargs) | SetRGB(self, int x, int y, byte r, byte g, byte b)
Sets the pixel at the given coordinate. This routine performs
bounds-checks for the coordinate so it can be considered a safe way to
manipulate the data, but in some cases this might be too slow so that
the data will have to be set directly. In that case you will have to
get access to the image data using the `GetData` method. | SetRGB(self, int x, int y, byte r, byte g, byte b) | [
"SetRGB",
"(",
"self",
"int",
"x",
"int",
"y",
"byte",
"r",
"byte",
"g",
"byte",
"b",
")"
] | def SetRGB(*args, **kwargs):
"""
SetRGB(self, int x, int y, byte r, byte g, byte b)
Sets the pixel at the given coordinate. This routine performs
bounds-checks for the coordinate so it can be considered a safe way to
manipulate the data, but in some cases this might be too slow so that
the data will have to be set directly. In that case you will have to
get access to the image data using the `GetData` method.
"""
return _core_.Image_SetRGB(*args, **kwargs) | [
"def",
"SetRGB",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_SetRGB",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2998-L3008 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/ConfigParser.py | python | RawConfigParser._read | (self, fp, fpname) | Parse a sectioned setup file.
The sections in setup file contains a title line at the top,
indicated by a name in square brackets (`[]'), plus key/value
options lines, indicated by `name: value' format lines.
Continuations are represented by an embedded newline then
leading whitespace. Blank lines, lines beginning with a '#',
and just about everything else are ignored. | Parse a sectioned setup file. | [
"Parse",
"a",
"sectioned",
"setup",
"file",
"."
] | def _read(self, fp, fpname):
"""Parse a sectioned setup file.
The sections in setup file contains a title line at the top,
indicated by a name in square brackets (`[]'), plus key/value
options lines, indicated by `name: value' format lines.
Continuations are represented by an embedded newline then
leading whitespace. Blank lines, lines beginning with a '#',
and just about everything else are ignored.
"""
cursect = None # None, or a dictionary
optname = None
lineno = 0
e = None # None, or an exception
while True:
line = fp.readline()
if not line:
break
lineno = lineno + 1
# comment or blank line?
if line.strip() == '' or line[0] in '#;':
continue
if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
# no leading whitespace
continue
# continuation line?
if line[0].isspace() and cursect is not None and optname:
value = line.strip()
if value:
cursect[optname].append(value)
# a section header or option header?
else:
# is it a section header?
mo = self.SECTCRE.match(line)
if mo:
sectname = mo.group('header')
if sectname in self._sections:
cursect = self._sections[sectname]
elif sectname == DEFAULTSECT:
cursect = self._defaults
else:
cursect = self._dict()
cursect['__name__'] = sectname
self._sections[sectname] = cursect
# So sections can't start with a continuation line
optname = None
# no section header in the file?
elif cursect is None:
raise MissingSectionHeaderError(fpname, lineno, line)
# an option line?
else:
mo = self._optcre.match(line)
if mo:
optname, vi, optval = mo.group('option', 'vi', 'value')
optname = self.optionxform(optname.rstrip())
# This check is fine because the OPTCRE cannot
# match if it would set optval to None
if optval is not None:
if vi in ('=', ':') and ';' in optval:
# ';' is a comment delimiter only if it follows
# a spacing character
pos = optval.find(';')
if pos != -1 and optval[pos-1].isspace():
optval = optval[:pos]
optval = optval.strip()
# allow empty values
if optval == '""':
optval = ''
cursect[optname] = [optval]
else:
# valueless option handling
cursect[optname] = optval
else:
# a non-fatal parsing error occurred. set up the
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
if not e:
e = ParsingError(fpname)
e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
if e:
raise e
# join the multi-line values collected while reading
all_sections = [self._defaults]
all_sections.extend(self._sections.values())
for options in all_sections:
for name, val in options.items():
if isinstance(val, list):
options[name] = '\n'.join(val) | [
"def",
"_read",
"(",
"self",
",",
"fp",
",",
"fpname",
")",
":",
"cursect",
"=",
"None",
"# None, or a dictionary",
"optname",
"=",
"None",
"lineno",
"=",
"0",
"e",
"=",
"None",
"# None, or an exception",
"while",
"True",
":",
"line",
"=",
"fp",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"lineno",
"=",
"lineno",
"+",
"1",
"# comment or blank line?",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"''",
"or",
"line",
"[",
"0",
"]",
"in",
"'#;'",
":",
"continue",
"if",
"line",
".",
"split",
"(",
"None",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"'rem'",
"and",
"line",
"[",
"0",
"]",
"in",
"\"rR\"",
":",
"# no leading whitespace",
"continue",
"# continuation line?",
"if",
"line",
"[",
"0",
"]",
".",
"isspace",
"(",
")",
"and",
"cursect",
"is",
"not",
"None",
"and",
"optname",
":",
"value",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"value",
":",
"cursect",
"[",
"optname",
"]",
".",
"append",
"(",
"value",
")",
"# a section header or option header?",
"else",
":",
"# is it a section header?",
"mo",
"=",
"self",
".",
"SECTCRE",
".",
"match",
"(",
"line",
")",
"if",
"mo",
":",
"sectname",
"=",
"mo",
".",
"group",
"(",
"'header'",
")",
"if",
"sectname",
"in",
"self",
".",
"_sections",
":",
"cursect",
"=",
"self",
".",
"_sections",
"[",
"sectname",
"]",
"elif",
"sectname",
"==",
"DEFAULTSECT",
":",
"cursect",
"=",
"self",
".",
"_defaults",
"else",
":",
"cursect",
"=",
"self",
".",
"_dict",
"(",
")",
"cursect",
"[",
"'__name__'",
"]",
"=",
"sectname",
"self",
".",
"_sections",
"[",
"sectname",
"]",
"=",
"cursect",
"# So sections can't start with a continuation line",
"optname",
"=",
"None",
"# no section header in the file?",
"elif",
"cursect",
"is",
"None",
":",
"raise",
"MissingSectionHeaderError",
"(",
"fpname",
",",
"lineno",
",",
"line",
")",
"# an option line?",
"else",
":",
"mo",
"=",
"self",
".",
"_optcre",
".",
"match",
"(",
"line",
")",
"if",
"mo",
":",
"optname",
",",
"vi",
",",
"optval",
"=",
"mo",
".",
"group",
"(",
"'option'",
",",
"'vi'",
",",
"'value'",
")",
"optname",
"=",
"self",
".",
"optionxform",
"(",
"optname",
".",
"rstrip",
"(",
")",
")",
"# This check is fine because the OPTCRE cannot",
"# match if it would set optval to None",
"if",
"optval",
"is",
"not",
"None",
":",
"if",
"vi",
"in",
"(",
"'='",
",",
"':'",
")",
"and",
"';'",
"in",
"optval",
":",
"# ';' is a comment delimiter only if it follows",
"# a spacing character",
"pos",
"=",
"optval",
".",
"find",
"(",
"';'",
")",
"if",
"pos",
"!=",
"-",
"1",
"and",
"optval",
"[",
"pos",
"-",
"1",
"]",
".",
"isspace",
"(",
")",
":",
"optval",
"=",
"optval",
"[",
":",
"pos",
"]",
"optval",
"=",
"optval",
".",
"strip",
"(",
")",
"# allow empty values",
"if",
"optval",
"==",
"'\"\"'",
":",
"optval",
"=",
"''",
"cursect",
"[",
"optname",
"]",
"=",
"[",
"optval",
"]",
"else",
":",
"# valueless option handling",
"cursect",
"[",
"optname",
"]",
"=",
"optval",
"else",
":",
"# a non-fatal parsing error occurred. set up the",
"# exception but keep going. the exception will be",
"# raised at the end of the file and will contain a",
"# list of all bogus lines",
"if",
"not",
"e",
":",
"e",
"=",
"ParsingError",
"(",
"fpname",
")",
"e",
".",
"append",
"(",
"lineno",
",",
"repr",
"(",
"line",
")",
")",
"# if any parsing errors occurred, raise an exception",
"if",
"e",
":",
"raise",
"e",
"# join the multi-line values collected while reading",
"all_sections",
"=",
"[",
"self",
".",
"_defaults",
"]",
"all_sections",
".",
"extend",
"(",
"self",
".",
"_sections",
".",
"values",
"(",
")",
")",
"for",
"options",
"in",
"all_sections",
":",
"for",
"name",
",",
"val",
"in",
"options",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"options",
"[",
"name",
"]",
"=",
"'\\n'",
".",
"join",
"(",
"val",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/ConfigParser.py#L464-L554 |
||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/message.py | python | Message.SetInParent | (self) | Mark this as present in the parent.
This normally happens automatically when you assign a field of a
sub-message, but sometimes you want to make the sub-message
present while keeping it empty. If you find yourself using this,
you may want to reconsider your design. | Mark this as present in the parent. | [
"Mark",
"this",
"as",
"present",
"in",
"the",
"parent",
"."
] | def SetInParent(self):
"""Mark this as present in the parent.
This normally happens automatically when you assign a field of a
sub-message, but sometimes you want to make the sub-message
present while keeping it empty. If you find yourself using this,
you may want to reconsider your design."""
raise NotImplementedError | [
"def",
"SetInParent",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/message.py#L121-L128 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ogl/_basic.py | python | Shape.GetAttachmentPositionEdge | (self, attachment, nth = 0, no_arcs = 1, line = None) | return res | Only get the attachment position at the _edge_ of the shape,
ignoring branching mode. This is used e.g. to indicate the edge of
interest, not the point on the attachment branch. | Only get the attachment position at the _edge_ of the shape,
ignoring branching mode. This is used e.g. to indicate the edge of
interest, not the point on the attachment branch. | [
"Only",
"get",
"the",
"attachment",
"position",
"at",
"the",
"_edge_",
"of",
"the",
"shape",
"ignoring",
"branching",
"mode",
".",
"This",
"is",
"used",
"e",
".",
"g",
".",
"to",
"indicate",
"the",
"edge",
"of",
"interest",
"not",
"the",
"point",
"on",
"the",
"attachment",
"branch",
"."
] | def GetAttachmentPositionEdge(self, attachment, nth = 0, no_arcs = 1, line = None):
""" Only get the attachment position at the _edge_ of the shape,
ignoring branching mode. This is used e.g. to indicate the edge of
interest, not the point on the attachment branch.
"""
oldMode = self._attachmentMode
# Calculate as if to edge, not branch
if self._attachmentMode == ATTACHMENT_MODE_BRANCHING:
self._attachmentMode = ATTACHMENT_MODE_EDGE
res = self.GetAttachmentPosition(attachment, nth, no_arcs, line)
self._attachmentMode = oldMode
return res | [
"def",
"GetAttachmentPositionEdge",
"(",
"self",
",",
"attachment",
",",
"nth",
"=",
"0",
",",
"no_arcs",
"=",
"1",
",",
"line",
"=",
"None",
")",
":",
"oldMode",
"=",
"self",
".",
"_attachmentMode",
"# Calculate as if to edge, not branch",
"if",
"self",
".",
"_attachmentMode",
"==",
"ATTACHMENT_MODE_BRANCHING",
":",
"self",
".",
"_attachmentMode",
"=",
"ATTACHMENT_MODE_EDGE",
"res",
"=",
"self",
".",
"GetAttachmentPosition",
"(",
"attachment",
",",
"nth",
",",
"no_arcs",
",",
"line",
")",
"self",
".",
"_attachmentMode",
"=",
"oldMode",
"return",
"res"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L1831-L1844 |
|
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/mavlink_px4.py | python | MAVLink.global_position_int_send | (self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg) | return self.send(self.global_position_int_encode(time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg)) | The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It
is designed as scaled integer message since the
resolution of float is not sufficient.
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
lat : Latitude, expressed as * 1E7 (int32_t)
lon : Longitude, expressed as * 1E7 (int32_t)
alt : Altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t)
relative_alt : Altitude above ground in meters, expressed as * 1000 (millimeters) (int32_t)
vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t)
vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t)
vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t)
hdg : Compass heading in degrees * 100, 0.0..359.99 degrees. If unknown, set to: 65535 (uint16_t) | The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It
is designed as scaled integer message since the
resolution of float is not sufficient. | [
"The",
"filtered",
"global",
"position",
"(",
"e",
".",
"g",
".",
"fused",
"GPS",
"and",
"accelerometers",
")",
".",
"The",
"position",
"is",
"in",
"GPS",
"-",
"frame",
"(",
"right",
"-",
"handed",
"Z",
"-",
"up",
")",
".",
"It",
"is",
"designed",
"as",
"scaled",
"integer",
"message",
"since",
"the",
"resolution",
"of",
"float",
"is",
"not",
"sufficient",
"."
] | def global_position_int_send(self, time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg):
'''
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It
is designed as scaled integer message since the
resolution of float is not sufficient.
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
lat : Latitude, expressed as * 1E7 (int32_t)
lon : Longitude, expressed as * 1E7 (int32_t)
alt : Altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t)
relative_alt : Altitude above ground in meters, expressed as * 1000 (millimeters) (int32_t)
vx : Ground X Speed (Latitude), expressed as m/s * 100 (int16_t)
vy : Ground Y Speed (Longitude), expressed as m/s * 100 (int16_t)
vz : Ground Z Speed (Altitude), expressed as m/s * 100 (int16_t)
hdg : Compass heading in degrees * 100, 0.0..359.99 degrees. If unknown, set to: 65535 (uint16_t)
'''
return self.send(self.global_position_int_encode(time_boot_ms, lat, lon, alt, relative_alt, vx, vy, vz, hdg)) | [
"def",
"global_position_int_send",
"(",
"self",
",",
"time_boot_ms",
",",
"lat",
",",
"lon",
",",
"alt",
",",
"relative_alt",
",",
"vx",
",",
"vy",
",",
"vz",
",",
"hdg",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"global_position_int_encode",
"(",
"time_boot_ms",
",",
"lat",
",",
"lon",
",",
"alt",
",",
"relative_alt",
",",
"vx",
",",
"vy",
",",
"vz",
",",
"hdg",
")",
")"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L3173-L3191 |
|
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | example/python-howto/data.py | python | mnist_iterator | (batch_size, input_shape) | return (train_dataiter, val_dataiter) | return train and val iterators for mnist | return train and val iterators for mnist | [
"return",
"train",
"and",
"val",
"iterators",
"for",
"mnist"
] | def mnist_iterator(batch_size, input_shape):
"""return train and val iterators for mnist"""
# download data
get_data.GetMNIST_ubyte()
flat = False if len(input_shape) == 3 else True
train_dataiter = mx.io.MNISTIter(
image="data/train-images-idx3-ubyte",
label="data/train-labels-idx1-ubyte",
input_shape=input_shape,
batch_size=batch_size,
shuffle=True,
flat=flat)
val_dataiter = mx.io.MNISTIter(
image="data/t10k-images-idx3-ubyte",
label="data/t10k-labels-idx1-ubyte",
input_shape=input_shape,
batch_size=batch_size,
flat=flat)
return (train_dataiter, val_dataiter) | [
"def",
"mnist_iterator",
"(",
"batch_size",
",",
"input_shape",
")",
":",
"# download data",
"get_data",
".",
"GetMNIST_ubyte",
"(",
")",
"flat",
"=",
"False",
"if",
"len",
"(",
"input_shape",
")",
"==",
"3",
"else",
"True",
"train_dataiter",
"=",
"mx",
".",
"io",
".",
"MNISTIter",
"(",
"image",
"=",
"\"data/train-images-idx3-ubyte\"",
",",
"label",
"=",
"\"data/train-labels-idx1-ubyte\"",
",",
"input_shape",
"=",
"input_shape",
",",
"batch_size",
"=",
"batch_size",
",",
"shuffle",
"=",
"True",
",",
"flat",
"=",
"flat",
")",
"val_dataiter",
"=",
"mx",
".",
"io",
".",
"MNISTIter",
"(",
"image",
"=",
"\"data/t10k-images-idx3-ubyte\"",
",",
"label",
"=",
"\"data/t10k-labels-idx1-ubyte\"",
",",
"input_shape",
"=",
"input_shape",
",",
"batch_size",
"=",
"batch_size",
",",
"flat",
"=",
"flat",
")",
"return",
"(",
"train_dataiter",
",",
"val_dataiter",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/example/python-howto/data.py#L11-L32 |
|
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/io.py | python | IOBase.truncate | (self, pos = None) | Truncate file to size bytes.
Size defaults to the current IO position as reported by tell(). Return
the new size. | Truncate file to size bytes. | [
"Truncate",
"file",
"to",
"size",
"bytes",
"."
] | def truncate(self, pos = None):
"""Truncate file to size bytes.
Size defaults to the current IO position as reported by tell(). Return
the new size.
"""
self._unsupported("truncate") | [
"def",
"truncate",
"(",
"self",
",",
"pos",
"=",
"None",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"truncate\"",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/io.py#L356-L362 |
||
danmar/cppcheck | 78228599da0dfce3763a90a130b14fa2d614ab9f | addons/cppcheckdata.py | python | _load_location | (location, element) | Load location from element/dict | Load location from element/dict | [
"Load",
"location",
"from",
"element",
"/",
"dict"
] | def _load_location(location, element):
"""Load location from element/dict"""
location.file = element.get('file')
line = element.get('line')
if line is None:
line = element.get('linenr')
if line is None:
line = '0'
location.linenr = int(line)
location.column = int(element.get('column', '0')) | [
"def",
"_load_location",
"(",
"location",
",",
"element",
")",
":",
"location",
".",
"file",
"=",
"element",
".",
"get",
"(",
"'file'",
")",
"line",
"=",
"element",
".",
"get",
"(",
"'line'",
")",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"element",
".",
"get",
"(",
"'linenr'",
")",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"'0'",
"location",
".",
"linenr",
"=",
"int",
"(",
"line",
")",
"location",
".",
"column",
"=",
"int",
"(",
"element",
".",
"get",
"(",
"'column'",
",",
"'0'",
")",
")"
] | https://github.com/danmar/cppcheck/blob/78228599da0dfce3763a90a130b14fa2d614ab9f/addons/cppcheckdata.py#L20-L29 |
||
ucb-bar/esp-llvm | 8aec2ae754fd66d4e73b9b777a9f20c4583a0f03 | examples/Kaleidoscope/MCJIT/cached/genk-timing.py | python | TimingScriptGenerator.writeTimingCall | (self, filename, numFuncs, funcsCalled, totalCalls) | Echo some comments and invoke both versions of toy | Echo some comments and invoke both versions of toy | [
"Echo",
"some",
"comments",
"and",
"invoke",
"both",
"versions",
"of",
"toy"
] | def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls):
"""Echo some comments and invoke both versions of toy"""
rootname = filename
if '.' in filename:
rootname = filename[:filename.rfind('.')]
self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-jit < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile) | [
"def",
"writeTimingCall",
"(",
"self",
",",
"filename",
",",
"numFuncs",
",",
"funcsCalled",
",",
"totalCalls",
")",
":",
"rootname",
"=",
"filename",
"if",
"'.'",
"in",
"filename",
":",
"rootname",
"=",
"filename",
"[",
":",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"]",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"%s: Calls %d of %d functions, %d total\\\" >> %s\\n\"",
"%",
"(",
"filename",
",",
"funcsCalled",
",",
"numFuncs",
",",
"totalCalls",
",",
"self",
".",
"timeFile",
")",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"With MCJIT\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\" -o %s -a \"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"./toy-mcjit < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"",
"%",
"(",
"filename",
",",
"rootname",
",",
"rootname",
")",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"With JIT\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\" -o %s -a \"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"./toy-jit < %s > %s-jit.out 2> %s-jit.err\\n\"",
"%",
"(",
"filename",
",",
"rootname",
",",
"rootname",
")",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")"
] | https://github.com/ucb-bar/esp-llvm/blob/8aec2ae754fd66d4e73b9b777a9f20c4583a0f03/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L13-L30 |
||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/summary/event_multiplexer.py | python | EventMultiplexer.CompressedHistograms | (self, run, tag) | return accumulator.CompressedHistograms(tag) | Retrieve the compressed histogram events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.
Returns:
An array of `event_accumulator.CompressedHistogramEvents`. | Retrieve the compressed histogram events associated with a run and tag. | [
"Retrieve",
"the",
"compressed",
"histogram",
"events",
"associated",
"with",
"a",
"run",
"and",
"tag",
"."
] | def CompressedHistograms(self, run, tag):
"""Retrieve the compressed histogram events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.
Returns:
An array of `event_accumulator.CompressedHistogramEvents`.
"""
accumulator = self._GetAccumulator(run)
return accumulator.CompressedHistograms(tag) | [
"def",
"CompressedHistograms",
"(",
"self",
",",
"run",
",",
"tag",
")",
":",
"accumulator",
"=",
"self",
".",
"_GetAccumulator",
"(",
"run",
")",
"return",
"accumulator",
".",
"CompressedHistograms",
"(",
"tag",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/summary/event_multiplexer.py#L293-L308 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py | python | is_complex_dtype | (arr_or_dtype) | return _is_dtype_type(arr_or_dtype, classes(np.complexfloating)) | Check whether the provided array or dtype is of a complex dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a complex dtype.
Examples
--------
>>> is_complex_dtype(str)
False
>>> is_complex_dtype(int)
False
>>> is_complex_dtype(np.complex)
True
>>> is_complex_dtype(np.array(['a', 'b']))
False
>>> is_complex_dtype(pd.Series([1, 2]))
False
>>> is_complex_dtype(np.array([1 + 1j, 5]))
True | Check whether the provided array or dtype is of a complex dtype. | [
"Check",
"whether",
"the",
"provided",
"array",
"or",
"dtype",
"is",
"of",
"a",
"complex",
"dtype",
"."
] | def is_complex_dtype(arr_or_dtype) -> bool:
"""
Check whether the provided array or dtype is of a complex dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a complex dtype.
Examples
--------
>>> is_complex_dtype(str)
False
>>> is_complex_dtype(int)
False
>>> is_complex_dtype(np.complex)
True
>>> is_complex_dtype(np.array(['a', 'b']))
False
>>> is_complex_dtype(pd.Series([1, 2]))
False
>>> is_complex_dtype(np.array([1 + 1j, 5]))
True
"""
return _is_dtype_type(arr_or_dtype, classes(np.complexfloating)) | [
"def",
"is_complex_dtype",
"(",
"arr_or_dtype",
")",
"->",
"bool",
":",
"return",
"_is_dtype_type",
"(",
"arr_or_dtype",
",",
"classes",
"(",
"np",
".",
"complexfloating",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py#L1614-L1644 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/tensorboard/scripts/serialize_tensorboard.py | python | TensorBoardStaticSerializer.GetAndSave | (self, url, save_suffix, unzip=False) | return content | GET the given url. Serialize the result at clean path version of url. | GET the given url. Serialize the result at clean path version of url. | [
"GET",
"the",
"given",
"url",
".",
"Serialize",
"the",
"result",
"at",
"clean",
"path",
"version",
"of",
"url",
"."
] | def GetAndSave(self, url, save_suffix, unzip=False):
"""GET the given url. Serialize the result at clean path version of url."""
self.connection.request('GET',
'/data/' + url,
headers={'content-type': 'text/plain'})
response = self.connection.getresponse()
file_name = Clean(url) + save_suffix
destination = os.path.join(self.path, file_name)
if response.status != 200:
raise IOError(url)
if unzip:
s = StringIO.StringIO(response.read())
content = gzip.GzipFile(fileobj=s).read()
else:
content = response.read()
with open(destination, 'w') as f:
f.write(content)
return content | [
"def",
"GetAndSave",
"(",
"self",
",",
"url",
",",
"save_suffix",
",",
"unzip",
"=",
"False",
")",
":",
"self",
".",
"connection",
".",
"request",
"(",
"'GET'",
",",
"'/data/'",
"+",
"url",
",",
"headers",
"=",
"{",
"'content-type'",
":",
"'text/plain'",
"}",
")",
"response",
"=",
"self",
".",
"connection",
".",
"getresponse",
"(",
")",
"file_name",
"=",
"Clean",
"(",
"url",
")",
"+",
"save_suffix",
"destination",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"file_name",
")",
"if",
"response",
".",
"status",
"!=",
"200",
":",
"raise",
"IOError",
"(",
"url",
")",
"if",
"unzip",
":",
"s",
"=",
"StringIO",
".",
"StringIO",
"(",
"response",
".",
"read",
"(",
")",
")",
"content",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"s",
")",
".",
"read",
"(",
")",
"else",
":",
"content",
"=",
"response",
".",
"read",
"(",
")",
"with",
"open",
"(",
"destination",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")",
"return",
"content"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/tensorboard/scripts/serialize_tensorboard.py#L92-L112 |
|
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/writers/ComponentWriterBase.py | python | ComponentWriterBase.initPreMessageHooks | (self, c) | Init Pre-message hooks | Init Pre-message hooks | [
"Init",
"Pre",
"-",
"message",
"hooks"
] | def initPreMessageHooks(self, c):
"""
Init Pre-message hooks
"""
# Pre-message hooks for async input ports
c.pre_message_hooks = [
(instance, type, sync, priority, role, max_num)
for (instance, type, sync, priority, full, role, max_num) in c.input_ports
if role != "Cmd" and sync == "async"
]
# Pre-message hooks for typed async input ports
c.pre_message_hooks_typed = [
(instance, type, sync, priority, full, role, max_num)
for (
instance,
type,
sync,
priority,
full,
role,
max_num,
) in c.typed_input_ports
if role != "Cmd" and sync == "async"
]
# Pre-message hooks for serial async input ports
c.pre_message_hooks_serial = c.serial_input_ports | [
"def",
"initPreMessageHooks",
"(",
"self",
",",
"c",
")",
":",
"# Pre-message hooks for async input ports",
"c",
".",
"pre_message_hooks",
"=",
"[",
"(",
"instance",
",",
"type",
",",
"sync",
",",
"priority",
",",
"role",
",",
"max_num",
")",
"for",
"(",
"instance",
",",
"type",
",",
"sync",
",",
"priority",
",",
"full",
",",
"role",
",",
"max_num",
")",
"in",
"c",
".",
"input_ports",
"if",
"role",
"!=",
"\"Cmd\"",
"and",
"sync",
"==",
"\"async\"",
"]",
"# Pre-message hooks for typed async input ports",
"c",
".",
"pre_message_hooks_typed",
"=",
"[",
"(",
"instance",
",",
"type",
",",
"sync",
",",
"priority",
",",
"full",
",",
"role",
",",
"max_num",
")",
"for",
"(",
"instance",
",",
"type",
",",
"sync",
",",
"priority",
",",
"full",
",",
"role",
",",
"max_num",
",",
")",
"in",
"c",
".",
"typed_input_ports",
"if",
"role",
"!=",
"\"Cmd\"",
"and",
"sync",
"==",
"\"async\"",
"]",
"# Pre-message hooks for serial async input ports",
"c",
".",
"pre_message_hooks_serial",
"=",
"c",
".",
"serial_input_ports"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/ComponentWriterBase.py#L629-L654 |
||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/moving_averages.py | python | assign_moving_average | (variable, value, decay, zero_debias=True, name=None) | Compute the moving average of a variable.
The moving average of 'variable' updated with 'value' is:
variable * decay + value * (1 - decay)
The returned Operation sets 'variable' to the newly computed moving average,
by performing this subtraction:
variable -= (1 - decay) * (variable - value)
Since variables that are initialized to a `0` value will be `0` biased,
`zero_debias` optionally enables scaling by the mathematically correct
debiasing factor of
1 - decay ** num_updates
See Section 3 of (Kingma et al., 2015) for more details.
The names of the debias shadow variables, by default, include both the scope
they were created in and the scope of the variables they debias. They are also
given a uniquifying-suffix.
E.g.:
```
with tf.compat.v1.variable_scope('scope1'):
with tf.compat.v1.variable_scope('scope2'):
var = tf.compat.v1.get_variable('foo')
update_1 = tf.assign_moving_average(var, 0.0, 1.0)
update_2 = tf.assign_moving_average(var, 0.0, 0.9)
# var.name: 'scope1/scope2/foo'
# shadow var names: 'scope1/scope2/scope1/scope2/foo/biased'
# 'scope1/scope2/scope1/scope2/foo/biased_1'
```
Args:
variable: A Variable.
value: A tensor with the same shape as 'variable'.
decay: A float Tensor or float value. The moving average decay.
zero_debias: A python bool. If true, assume the variable is 0-initialized
and unbias it, as in (Kingma et al., 2015). See docstring in
`_zero_debias` for more details.
name: Optional name of the returned operation.
Returns:
A tensor which if evaluated will compute and return the new moving average.
References:
Adam - A Method for Stochastic Optimization:
[Kingma et al., 2015](https://arxiv.org/abs/1412.6980)
([pdf](https://arxiv.org/pdf/1412.6980.pdf)) | Compute the moving average of a variable. | [
"Compute",
"the",
"moving",
"average",
"of",
"a",
"variable",
"."
] | def assign_moving_average(variable, value, decay, zero_debias=True, name=None):
"""Compute the moving average of a variable.
The moving average of 'variable' updated with 'value' is:
variable * decay + value * (1 - decay)
The returned Operation sets 'variable' to the newly computed moving average,
by performing this subtraction:
variable -= (1 - decay) * (variable - value)
Since variables that are initialized to a `0` value will be `0` biased,
`zero_debias` optionally enables scaling by the mathematically correct
debiasing factor of
1 - decay ** num_updates
See Section 3 of (Kingma et al., 2015) for more details.
The names of the debias shadow variables, by default, include both the scope
they were created in and the scope of the variables they debias. They are also
given a uniquifying-suffix.
E.g.:
```
with tf.compat.v1.variable_scope('scope1'):
with tf.compat.v1.variable_scope('scope2'):
var = tf.compat.v1.get_variable('foo')
update_1 = tf.assign_moving_average(var, 0.0, 1.0)
update_2 = tf.assign_moving_average(var, 0.0, 0.9)
# var.name: 'scope1/scope2/foo'
# shadow var names: 'scope1/scope2/scope1/scope2/foo/biased'
# 'scope1/scope2/scope1/scope2/foo/biased_1'
```
Args:
variable: A Variable.
value: A tensor with the same shape as 'variable'.
decay: A float Tensor or float value. The moving average decay.
zero_debias: A python bool. If true, assume the variable is 0-initialized
and unbias it, as in (Kingma et al., 2015). See docstring in
`_zero_debias` for more details.
name: Optional name of the returned operation.
Returns:
A tensor which if evaluated will compute and return the new moving average.
References:
Adam - A Method for Stochastic Optimization:
[Kingma et al., 2015](https://arxiv.org/abs/1412.6980)
([pdf](https://arxiv.org/pdf/1412.6980.pdf))
"""
with ops.name_scope(name, "AssignMovingAvg",
[variable, value, decay]) as scope:
decay = ops.convert_to_tensor(1.0 - decay, name="decay")
if decay.dtype != variable.dtype.base_dtype:
decay = math_ops.cast(decay, variable.dtype.base_dtype)
def update_fn(v, value):
return state_ops.assign_sub(v, (v - value) * decay, name=scope)
def update(strategy, v, value):
if zero_debias:
return _zero_debias(strategy, v, value, decay)
else:
return _update(strategy, v, update_fn, args=(value,))
replica_context = distribution_strategy_context.get_replica_context()
if replica_context:
# In a replica context, we update variable using the mean of value across
# replicas.
def merge_fn(strategy, v, value):
value = strategy.extended.reduce_to(ds_reduce_util.ReduceOp.MEAN, value,
v)
return update(strategy, v, value)
return replica_context.merge_call(merge_fn, args=(variable, value))
else:
strategy = distribution_strategy_context.get_cross_replica_context()
return update(strategy, variable, value) | [
"def",
"assign_moving_average",
"(",
"variable",
",",
"value",
",",
"decay",
",",
"zero_debias",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"AssignMovingAvg\"",
",",
"[",
"variable",
",",
"value",
",",
"decay",
"]",
")",
"as",
"scope",
":",
"decay",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"1.0",
"-",
"decay",
",",
"name",
"=",
"\"decay\"",
")",
"if",
"decay",
".",
"dtype",
"!=",
"variable",
".",
"dtype",
".",
"base_dtype",
":",
"decay",
"=",
"math_ops",
".",
"cast",
"(",
"decay",
",",
"variable",
".",
"dtype",
".",
"base_dtype",
")",
"def",
"update_fn",
"(",
"v",
",",
"value",
")",
":",
"return",
"state_ops",
".",
"assign_sub",
"(",
"v",
",",
"(",
"v",
"-",
"value",
")",
"*",
"decay",
",",
"name",
"=",
"scope",
")",
"def",
"update",
"(",
"strategy",
",",
"v",
",",
"value",
")",
":",
"if",
"zero_debias",
":",
"return",
"_zero_debias",
"(",
"strategy",
",",
"v",
",",
"value",
",",
"decay",
")",
"else",
":",
"return",
"_update",
"(",
"strategy",
",",
"v",
",",
"update_fn",
",",
"args",
"=",
"(",
"value",
",",
")",
")",
"replica_context",
"=",
"distribution_strategy_context",
".",
"get_replica_context",
"(",
")",
"if",
"replica_context",
":",
"# In a replica context, we update variable using the mean of value across",
"# replicas.",
"def",
"merge_fn",
"(",
"strategy",
",",
"v",
",",
"value",
")",
":",
"value",
"=",
"strategy",
".",
"extended",
".",
"reduce_to",
"(",
"ds_reduce_util",
".",
"ReduceOp",
".",
"MEAN",
",",
"value",
",",
"v",
")",
"return",
"update",
"(",
"strategy",
",",
"v",
",",
"value",
")",
"return",
"replica_context",
".",
"merge_call",
"(",
"merge_fn",
",",
"args",
"=",
"(",
"variable",
",",
"value",
")",
")",
"else",
":",
"strategy",
"=",
"distribution_strategy_context",
".",
"get_cross_replica_context",
"(",
")",
"return",
"update",
"(",
"strategy",
",",
"variable",
",",
"value",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/moving_averages.py#L33-L111 |
||
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | armoryengine/PyBtcAddress.py | python | PyBtcAddress.createFromPublicKeyHash160 | (self, pubkeyHash160, netbyte=ADDRBYTE) | return self | Creates an address from just the 20-byte binary hash of a public key.
In binary form without a chksum, there is no protection against byte
errors, since there's no way to distinguish an invalid address from
a valid one (they both look like random data).
If you are creating an address using 20 bytes you obtained in an
unreliable manner (such as manually typing them in), you should
double-check the input before sending money using the address created
here -- the tx will appear valid and be accepted by the network,
but will be permanently tied up in the network | Creates an address from just the 20-byte binary hash of a public key. | [
"Creates",
"an",
"address",
"from",
"just",
"the",
"20",
"-",
"byte",
"binary",
"hash",
"of",
"a",
"public",
"key",
"."
] | def createFromPublicKeyHash160(self, pubkeyHash160, netbyte=ADDRBYTE):
"""
Creates an address from just the 20-byte binary hash of a public key.
In binary form without a chksum, there is no protection against byte
errors, since there's no way to distinguish an invalid address from
a valid one (they both look like random data).
If you are creating an address using 20 bytes you obtained in an
unreliable manner (such as manually typing them in), you should
double-check the input before sending money using the address created
here -- the tx will appear valid and be accepted by the network,
but will be permanently tied up in the network
"""
self.__init__()
self.addrStr20 = pubkeyHash160
self.isInitialized = True
return self | [
"def",
"createFromPublicKeyHash160",
"(",
"self",
",",
"pubkeyHash160",
",",
"netbyte",
"=",
"ADDRBYTE",
")",
":",
"self",
".",
"__init__",
"(",
")",
"self",
".",
"addrStr20",
"=",
"pubkeyHash160",
"self",
".",
"isInitialized",
"=",
"True",
"return",
"self"
] | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/PyBtcAddress.py#L1175-L1192 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | PlatformInformation.SetOperatingSystemId | (*args, **kwargs) | return _misc_.PlatformInformation_SetOperatingSystemId(*args, **kwargs) | SetOperatingSystemId(self, int n) | SetOperatingSystemId(self, int n) | [
"SetOperatingSystemId",
"(",
"self",
"int",
"n",
")"
] | def SetOperatingSystemId(*args, **kwargs):
"""SetOperatingSystemId(self, int n)"""
return _misc_.PlatformInformation_SetOperatingSystemId(*args, **kwargs) | [
"def",
"SetOperatingSystemId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"PlatformInformation_SetOperatingSystemId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L1154-L1156 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridTableBase.SetAttr | (*args, **kwargs) | return _grid.GridTableBase_SetAttr(*args, **kwargs) | SetAttr(self, GridCellAttr attr, int row, int col) | SetAttr(self, GridCellAttr attr, int row, int col) | [
"SetAttr",
"(",
"self",
"GridCellAttr",
"attr",
"int",
"row",
"int",
"col",
")"
] | def SetAttr(*args, **kwargs):
"""SetAttr(self, GridCellAttr attr, int row, int col)"""
return _grid.GridTableBase_SetAttr(*args, **kwargs) | [
"def",
"SetAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_SetAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L910-L912 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/functools.py | python | _make_key | (args, kwds, typed,
kwd_mark = (object(),),
fasttypes = {int, str},
tuple=tuple, type=type, len=len) | return _HashedSeq(key) | Make a cache key from optionally typed positional and keyword arguments
The key is constructed in a way that is flat as possible rather than
as a nested structure that would take more memory.
If there is only a single argument and its data type is known to cache
its hash value, then that argument is returned without a wrapper. This
saves space and improves lookup speed. | Make a cache key from optionally typed positional and keyword arguments | [
"Make",
"a",
"cache",
"key",
"from",
"optionally",
"typed",
"positional",
"and",
"keyword",
"arguments"
] | def _make_key(args, kwds, typed,
kwd_mark = (object(),),
fasttypes = {int, str},
tuple=tuple, type=type, len=len):
"""Make a cache key from optionally typed positional and keyword arguments
The key is constructed in a way that is flat as possible rather than
as a nested structure that would take more memory.
If there is only a single argument and its data type is known to cache
its hash value, then that argument is returned without a wrapper. This
saves space and improves lookup speed.
"""
# All of code below relies on kwds preserving the order input by the user.
# Formerly, we sorted() the kwds before looping. The new way is *much*
# faster; however, it means that f(x=1, y=2) will now be treated as a
# distinct call from f(y=2, x=1) which will be cached separately.
key = args
if kwds:
key += kwd_mark
for item in kwds.items():
key += item
if typed:
key += tuple(type(v) for v in args)
if kwds:
key += tuple(type(v) for v in kwds.values())
elif len(key) == 1 and type(key[0]) in fasttypes:
return key[0]
return _HashedSeq(key) | [
"def",
"_make_key",
"(",
"args",
",",
"kwds",
",",
"typed",
",",
"kwd_mark",
"=",
"(",
"object",
"(",
")",
",",
")",
",",
"fasttypes",
"=",
"{",
"int",
",",
"str",
"}",
",",
"tuple",
"=",
"tuple",
",",
"type",
"=",
"type",
",",
"len",
"=",
"len",
")",
":",
"# All of code below relies on kwds preserving the order input by the user.",
"# Formerly, we sorted() the kwds before looping. The new way is *much*",
"# faster; however, it means that f(x=1, y=2) will now be treated as a",
"# distinct call from f(y=2, x=1) which will be cached separately.",
"key",
"=",
"args",
"if",
"kwds",
":",
"key",
"+=",
"kwd_mark",
"for",
"item",
"in",
"kwds",
".",
"items",
"(",
")",
":",
"key",
"+=",
"item",
"if",
"typed",
":",
"key",
"+=",
"tuple",
"(",
"type",
"(",
"v",
")",
"for",
"v",
"in",
"args",
")",
"if",
"kwds",
":",
"key",
"+=",
"tuple",
"(",
"type",
"(",
"v",
")",
"for",
"v",
"in",
"kwds",
".",
"values",
"(",
")",
")",
"elif",
"len",
"(",
"key",
")",
"==",
"1",
"and",
"type",
"(",
"key",
"[",
"0",
"]",
")",
"in",
"fasttypes",
":",
"return",
"key",
"[",
"0",
"]",
"return",
"_HashedSeq",
"(",
"key",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/functools.py#L427-L456 |
|
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py | python | Bits.all | (self, value, pos=None) | return True | Return True if one or many bits are all set to value.
value -- If value is True then checks for bits set to 1, otherwise
checks for bits set to 0.
pos -- An iterable of bit positions. Negative numbers are treated in
the same way as slice indices. Defaults to the whole bitstring. | Return True if one or many bits are all set to value. | [
"Return",
"True",
"if",
"one",
"or",
"many",
"bits",
"are",
"all",
"set",
"to",
"value",
"."
] | def all(self, value, pos=None):
"""Return True if one or many bits are all set to value.
value -- If value is True then checks for bits set to 1, otherwise
checks for bits set to 0.
pos -- An iterable of bit positions. Negative numbers are treated in
the same way as slice indices. Defaults to the whole bitstring.
"""
value = bool(value)
length = self.len
if pos is None:
pos = xrange(self.len)
for p in pos:
if p < 0:
p += length
if not 0 <= p < length:
raise IndexError("Bit position {0} out of range.".format(p))
if not self._datastore.getbit(p) is value:
return False
return True | [
"def",
"all",
"(",
"self",
",",
"value",
",",
"pos",
"=",
"None",
")",
":",
"value",
"=",
"bool",
"(",
"value",
")",
"length",
"=",
"self",
".",
"len",
"if",
"pos",
"is",
"None",
":",
"pos",
"=",
"xrange",
"(",
"self",
".",
"len",
")",
"for",
"p",
"in",
"pos",
":",
"if",
"p",
"<",
"0",
":",
"p",
"+=",
"length",
"if",
"not",
"0",
"<=",
"p",
"<",
"length",
":",
"raise",
"IndexError",
"(",
"\"Bit position {0} out of range.\"",
".",
"format",
"(",
"p",
")",
")",
"if",
"not",
"self",
".",
"_datastore",
".",
"getbit",
"(",
"p",
")",
"is",
"value",
":",
"return",
"False",
"return",
"True"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L2711-L2731 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/encodings/__init__.py | python | normalize_encoding | (encoding) | return '_'.join(encoding.translate(_norm_encoding_map).split()) | Normalize an encoding name.
Normalization works as follows: all non-alphanumeric
characters except the dot used for Python package names are
collapsed and replaced with a single underscore, e.g. ' -;#'
becomes '_'. Leading and trailing underscores are removed.
Note that encoding names should be ASCII only; if they do use
non-ASCII characters, these must be Latin-1 compatible. | Normalize an encoding name. | [
"Normalize",
"an",
"encoding",
"name",
"."
] | def normalize_encoding(encoding):
""" Normalize an encoding name.
Normalization works as follows: all non-alphanumeric
characters except the dot used for Python package names are
collapsed and replaced with a single underscore, e.g. ' -;#'
becomes '_'. Leading and trailing underscores are removed.
Note that encoding names should be ASCII only; if they do use
non-ASCII characters, these must be Latin-1 compatible.
"""
# Make sure we have an 8-bit string, because .translate() works
# differently for Unicode strings.
if hasattr(__builtin__, "unicode") and isinstance(encoding, unicode):
# Note that .encode('latin-1') does *not* use the codec
# registry, so this call doesn't recurse. (See unicodeobject.c
# PyUnicode_AsEncodedString() for details)
encoding = encoding.encode('latin-1')
return '_'.join(encoding.translate(_norm_encoding_map).split()) | [
"def",
"normalize_encoding",
"(",
"encoding",
")",
":",
"# Make sure we have an 8-bit string, because .translate() works",
"# differently for Unicode strings.",
"if",
"hasattr",
"(",
"__builtin__",
",",
"\"unicode\"",
")",
"and",
"isinstance",
"(",
"encoding",
",",
"unicode",
")",
":",
"# Note that .encode('latin-1') does *not* use the codec",
"# registry, so this call doesn't recurse. (See unicodeobject.c",
"# PyUnicode_AsEncodedString() for details)",
"encoding",
"=",
"encoding",
".",
"encode",
"(",
"'latin-1'",
")",
"return",
"'_'",
".",
"join",
"(",
"encoding",
".",
"translate",
"(",
"_norm_encoding_map",
")",
".",
"split",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/encodings/__init__.py#L49-L69 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/mox.py | python | MockMethod._PopNextMethod | (self) | Pop the next method from our call queue. | Pop the next method from our call queue. | [
"Pop",
"the",
"next",
"method",
"from",
"our",
"call",
"queue",
"."
] | def _PopNextMethod(self):
"""Pop the next method from our call queue."""
try:
return self._call_queue.popleft()
except IndexError:
raise UnexpectedMethodCallError(self, None) | [
"def",
"_PopNextMethod",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_call_queue",
".",
"popleft",
"(",
")",
"except",
"IndexError",
":",
"raise",
"UnexpectedMethodCallError",
"(",
"self",
",",
"None",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/mox.py#L581-L586 |
||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/profiler.py | python | dump_profile | () | Dump profile and stop profiler. Use this to save profile
in advance in case your program cannot exit normally. | Dump profile and stop profiler. Use this to save profile
in advance in case your program cannot exit normally. | [
"Dump",
"profile",
"and",
"stop",
"profiler",
".",
"Use",
"this",
"to",
"save",
"profile",
"in",
"advance",
"in",
"case",
"your",
"program",
"cannot",
"exit",
"normally",
"."
] | def dump_profile():
"""Dump profile and stop profiler. Use this to save profile
in advance in case your program cannot exit normally."""
warnings.warn('profiler.dump_profile() is deprecated. '
'Please use profiler.dump() instead')
dump(True) | [
"def",
"dump_profile",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"'profiler.dump_profile() is deprecated. '",
"'Please use profiler.dump() instead'",
")",
"dump",
"(",
"True",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/profiler.py#L146-L151 |
||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/examples/image_retraining/retrain.py | python | get_random_distorted_bottlenecks | (
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor) | return bottlenecks, ground_truths | Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
recalculate the full model for every image, and so we can't use cached
bottleneck values. Instead we find random images for the requested category,
run them through the distortion graph, and then the full graph to get the
bottleneck results for each.
Args:
sess: Current TensorFlow Session.
image_lists: Dictionary of training images for each label.
how_many: The integer number of bottleneck values to return.
category: Name string of which set of images to fetch - training, testing,
or validation.
image_dir: Root folder string of the subfolders containing the training
images.
input_jpeg_tensor: The input layer we feed the image data to.
distorted_image: The output node of the distortion graph.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths. | Retrieves bottleneck values for training images, after distortions. | [
"Retrieves",
"bottleneck",
"values",
"for",
"training",
"images",
"after",
"distortions",
"."
] | def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
recalculate the full model for every image, and so we can't use cached
bottleneck values. Instead we find random images for the requested category,
run them through the distortion graph, and then the full graph to get the
bottleneck results for each.
Args:
sess: Current TensorFlow Session.
image_lists: Dictionary of training images for each label.
how_many: The integer number of bottleneck values to return.
category: Name string of which set of images to fetch - training, testing,
or validation.
image_dir: Root folder string of the subfolders containing the training
images.
input_jpeg_tensor: The input layer we feed the image data to.
distorted_image: The output node of the distortion graph.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(65536)
image_path = get_image_path(image_lists, label_name, image_index, image_dir,
category)
if not gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
jpeg_data = gfile.FastGFile(image_path, 'rb').read()
# Note that we materialize the distorted_image_data as a numpy array before
# sending running inference on the image. This involves 2 memory copies and
# might be optimized in other implementations.
distorted_image_data = sess.run(distorted_image,
{input_jpeg_tensor: jpeg_data})
bottleneck = run_bottleneck_on_image(sess, distorted_image_data,
resized_input_tensor,
bottleneck_tensor)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth)
return bottlenecks, ground_truths | [
"def",
"get_random_distorted_bottlenecks",
"(",
"sess",
",",
"image_lists",
",",
"how_many",
",",
"category",
",",
"image_dir",
",",
"input_jpeg_tensor",
",",
"distorted_image",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
":",
"class_count",
"=",
"len",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"bottlenecks",
"=",
"[",
"]",
"ground_truths",
"=",
"[",
"]",
"for",
"unused_i",
"in",
"range",
"(",
"how_many",
")",
":",
"label_index",
"=",
"random",
".",
"randrange",
"(",
"class_count",
")",
"label_name",
"=",
"list",
"(",
"image_lists",
".",
"keys",
"(",
")",
")",
"[",
"label_index",
"]",
"image_index",
"=",
"random",
".",
"randrange",
"(",
"65536",
")",
"image_path",
"=",
"get_image_path",
"(",
"image_lists",
",",
"label_name",
",",
"image_index",
",",
"image_dir",
",",
"category",
")",
"if",
"not",
"gfile",
".",
"Exists",
"(",
"image_path",
")",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'File does not exist %s'",
",",
"image_path",
")",
"jpeg_data",
"=",
"gfile",
".",
"FastGFile",
"(",
"image_path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
"# Note that we materialize the distorted_image_data as a numpy array before",
"# sending running inference on the image. This involves 2 memory copies and",
"# might be optimized in other implementations.",
"distorted_image_data",
"=",
"sess",
".",
"run",
"(",
"distorted_image",
",",
"{",
"input_jpeg_tensor",
":",
"jpeg_data",
"}",
")",
"bottleneck",
"=",
"run_bottleneck_on_image",
"(",
"sess",
",",
"distorted_image_data",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
"ground_truth",
"=",
"np",
".",
"zeros",
"(",
"class_count",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"ground_truth",
"[",
"label_index",
"]",
"=",
"1.0",
"bottlenecks",
".",
"append",
"(",
"bottleneck",
")",
"ground_truths",
".",
"append",
"(",
"ground_truth",
")",
"return",
"bottlenecks",
",",
"ground_truths"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/examples/image_retraining/retrain.py#L504-L555 |
|
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/environment.py | python | Template.from_module_dict | (cls, environment, module_dict, globals) | return cls._from_namespace(environment, module_dict, globals) | Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4 | Creates a template object from a module. This is used by the
module loader to create a template object. | [
"Creates",
"a",
"template",
"object",
"from",
"a",
"module",
".",
"This",
"is",
"used",
"by",
"the",
"module",
"loader",
"to",
"create",
"a",
"template",
"object",
"."
] | def from_module_dict(cls, environment, module_dict, globals):
"""Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4
"""
return cls._from_namespace(environment, module_dict, globals) | [
"def",
"from_module_dict",
"(",
"cls",
",",
"environment",
",",
"module_dict",
",",
"globals",
")",
":",
"return",
"cls",
".",
"_from_namespace",
"(",
"environment",
",",
"module_dict",
",",
"globals",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/environment.py#L962-L968 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | DateTime.IsStrictlyBetween | (*args, **kwargs) | return _misc_.DateTime_IsStrictlyBetween(*args, **kwargs) | IsStrictlyBetween(self, DateTime t1, DateTime t2) -> bool | IsStrictlyBetween(self, DateTime t1, DateTime t2) -> bool | [
"IsStrictlyBetween",
"(",
"self",
"DateTime",
"t1",
"DateTime",
"t2",
")",
"-",
">",
"bool"
] | def IsStrictlyBetween(*args, **kwargs):
"""IsStrictlyBetween(self, DateTime t1, DateTime t2) -> bool"""
return _misc_.DateTime_IsStrictlyBetween(*args, **kwargs) | [
"def",
"IsStrictlyBetween",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_IsStrictlyBetween",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L4037-L4039 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/python/ops/quantile_ops.py | python | QuantileAccumulator.add_summary | (self, stamp_token, column, example_weights) | return gen_quantile_ops.quantile_accumulator_add_summaries(
quantile_accumulator_handles=[self.resource_handle],
stamp_token=stamp_token,
summaries=[summary]) | Adds quantile summary to its stream in resource. | Adds quantile summary to its stream in resource. | [
"Adds",
"quantile",
"summary",
"to",
"its",
"stream",
"in",
"resource",
"."
] | def add_summary(self, stamp_token, column, example_weights):
"""Adds quantile summary to its stream in resource."""
summary = self._make_summary(column, example_weights)
return gen_quantile_ops.quantile_accumulator_add_summaries(
quantile_accumulator_handles=[self.resource_handle],
stamp_token=stamp_token,
summaries=[summary]) | [
"def",
"add_summary",
"(",
"self",
",",
"stamp_token",
",",
"column",
",",
"example_weights",
")",
":",
"summary",
"=",
"self",
".",
"_make_summary",
"(",
"column",
",",
"example_weights",
")",
"return",
"gen_quantile_ops",
".",
"quantile_accumulator_add_summaries",
"(",
"quantile_accumulator_handles",
"=",
"[",
"self",
".",
"resource_handle",
"]",
",",
"stamp_token",
"=",
"stamp_token",
",",
"summaries",
"=",
"[",
"summary",
"]",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/python/ops/quantile_ops.py#L190-L196 |
|
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32com/client/gencache.py | python | GetClassForCLSID | (clsid) | Get a Python class for a CLSID
Given a CLSID, return a Python class which wraps the COM object
Returns the Python class, or None if no module is available.
Params
clsid -- A COM CLSID (or string repr of one) | Get a Python class for a CLSID | [
"Get",
"a",
"Python",
"class",
"for",
"a",
"CLSID"
] | def GetClassForCLSID(clsid):
"""Get a Python class for a CLSID
Given a CLSID, return a Python class which wraps the COM object
Returns the Python class, or None if no module is available.
Params
clsid -- A COM CLSID (or string repr of one)
"""
# first, take a short-cut - we may already have generated support ready-to-roll.
clsid = str(clsid)
if CLSIDToClass.HasClass(clsid):
return CLSIDToClass.GetClass(clsid)
mod = GetModuleForCLSID(clsid)
if mod is None:
return None
try:
return CLSIDToClass.GetClass(clsid)
except KeyError:
return None | [
"def",
"GetClassForCLSID",
"(",
"clsid",
")",
":",
"# first, take a short-cut - we may already have generated support ready-to-roll.",
"clsid",
"=",
"str",
"(",
"clsid",
")",
"if",
"CLSIDToClass",
".",
"HasClass",
"(",
"clsid",
")",
":",
"return",
"CLSIDToClass",
".",
"GetClass",
"(",
"clsid",
")",
"mod",
"=",
"GetModuleForCLSID",
"(",
"clsid",
")",
"if",
"mod",
"is",
"None",
":",
"return",
"None",
"try",
":",
"return",
"CLSIDToClass",
".",
"GetClass",
"(",
"clsid",
")",
"except",
"KeyError",
":",
"return",
"None"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/client/gencache.py#L183-L203 |
||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/service_reflection.py | python | GeneratedServiceStubType.__init__ | (cls, name, bases, dictionary) | Creates a message service stub class.
Args:
name: Name of the class (ignored, here).
bases: Base classes of the class being constructed.
dictionary: The class dictionary of the class being constructed.
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
describing this protocol service type. | Creates a message service stub class. | [
"Creates",
"a",
"message",
"service",
"stub",
"class",
"."
] | def __init__(cls, name, bases, dictionary):
"""Creates a message service stub class.
Args:
name: Name of the class (ignored, here).
bases: Base classes of the class being constructed.
dictionary: The class dictionary of the class being constructed.
dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
describing this protocol service type.
"""
super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
# Don't do anything if this class doesn't have a descriptor. This happens
# when a service stub is subclassed.
if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
return
descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]
service_stub_builder = _ServiceStubBuilder(descriptor)
service_stub_builder.BuildServiceStub(cls) | [
"def",
"__init__",
"(",
"cls",
",",
"name",
",",
"bases",
",",
"dictionary",
")",
":",
"super",
"(",
"GeneratedServiceStubType",
",",
"cls",
")",
".",
"__init__",
"(",
"name",
",",
"bases",
",",
"dictionary",
")",
"# Don't do anything if this class doesn't have a descriptor. This happens",
"# when a service stub is subclassed.",
"if",
"GeneratedServiceStubType",
".",
"_DESCRIPTOR_KEY",
"not",
"in",
"dictionary",
":",
"return",
"descriptor",
"=",
"dictionary",
"[",
"GeneratedServiceStubType",
".",
"_DESCRIPTOR_KEY",
"]",
"service_stub_builder",
"=",
"_ServiceStubBuilder",
"(",
"descriptor",
")",
"service_stub_builder",
".",
"BuildServiceStub",
"(",
"cls",
")"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/service_reflection.py#L94-L111 |
||
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/input.py | python | BuildTargetsDict | (data) | return targets | Builds a dict mapping fully-qualified target names to their target dicts.
|data| is a dict mapping loaded build files by pathname relative to the
current directory. Values in |data| are build file contents. For each
|data| value with a "targets" key, the value of the "targets" key is taken
as a list containing target dicts. Each target's fully-qualified name is
constructed from the pathname of the build file (|data| key) and its
"target_name" property. These fully-qualified names are used as the keys
in the returned dict. These keys provide access to the target dicts,
the dicts in the "targets" lists. | Builds a dict mapping fully-qualified target names to their target dicts. | [
"Builds",
"a",
"dict",
"mapping",
"fully",
"-",
"qualified",
"target",
"names",
"to",
"their",
"target",
"dicts",
"."
] | def BuildTargetsDict(data):
"""Builds a dict mapping fully-qualified target names to their target dicts.
|data| is a dict mapping loaded build files by pathname relative to the
current directory. Values in |data| are build file contents. For each
|data| value with a "targets" key, the value of the "targets" key is taken
as a list containing target dicts. Each target's fully-qualified name is
constructed from the pathname of the build file (|data| key) and its
"target_name" property. These fully-qualified names are used as the keys
in the returned dict. These keys provide access to the target dicts,
the dicts in the "targets" lists.
"""
targets = {}
for build_file in data['target_build_files']:
for target in data[build_file].get('targets', []):
target_name = gyp.common.QualifiedTarget(build_file,
target['target_name'],
target['toolset'])
if target_name in targets:
raise GypError('Duplicate target definitions for ' + target_name)
targets[target_name] = target
return targets | [
"def",
"BuildTargetsDict",
"(",
"data",
")",
":",
"targets",
"=",
"{",
"}",
"for",
"build_file",
"in",
"data",
"[",
"'target_build_files'",
"]",
":",
"for",
"target",
"in",
"data",
"[",
"build_file",
"]",
".",
"get",
"(",
"'targets'",
",",
"[",
"]",
")",
":",
"target_name",
"=",
"gyp",
".",
"common",
".",
"QualifiedTarget",
"(",
"build_file",
",",
"target",
"[",
"'target_name'",
"]",
",",
"target",
"[",
"'toolset'",
"]",
")",
"if",
"target_name",
"in",
"targets",
":",
"raise",
"GypError",
"(",
"'Duplicate target definitions for '",
"+",
"target_name",
")",
"targets",
"[",
"target_name",
"]",
"=",
"target",
"return",
"targets"
] | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/input.py#L1277-L1300 |
|
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | ctpn_crnn_ocr/CTPN/caffe/python/caffe/io.py | python | array_to_blobproto | (arr, diff=None) | return blob | Converts a 4-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | Converts a 4-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | [
"Converts",
"a",
"4",
"-",
"dimensional",
"array",
"to",
"blob",
"proto",
".",
"If",
"diff",
"is",
"given",
"also",
"convert",
"the",
"diff",
".",
"You",
"need",
"to",
"make",
"sure",
"that",
"arr",
"and",
"diff",
"have",
"the",
"same",
"shape",
"and",
"this",
"function",
"does",
"not",
"do",
"sanity",
"check",
"."
] | def array_to_blobproto(arr, diff=None):
"""Converts a 4-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check.
"""
if arr.ndim != 4:
raise ValueError('Incorrect array shape.')
blob = caffe_pb2.BlobProto()
blob.num, blob.channels, blob.height, blob.width = arr.shape
blob.data.extend(arr.astype(float).flat)
if diff is not None:
blob.diff.extend(diff.astype(float).flat)
return blob | [
"def",
"array_to_blobproto",
"(",
"arr",
",",
"diff",
"=",
"None",
")",
":",
"if",
"arr",
".",
"ndim",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"'Incorrect array shape.'",
")",
"blob",
"=",
"caffe_pb2",
".",
"BlobProto",
"(",
")",
"blob",
".",
"num",
",",
"blob",
".",
"channels",
",",
"blob",
".",
"height",
",",
"blob",
".",
"width",
"=",
"arr",
".",
"shape",
"blob",
".",
"data",
".",
"extend",
"(",
"arr",
".",
"astype",
"(",
"float",
")",
".",
"flat",
")",
"if",
"diff",
"is",
"not",
"None",
":",
"blob",
".",
"diff",
".",
"extend",
"(",
"diff",
".",
"astype",
"(",
"float",
")",
".",
"flat",
")",
"return",
"blob"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/ctpn_crnn_ocr/CTPN/caffe/python/caffe/io.py#L31-L43 |
|
unitusdev/unitus | 4cd523cb5b46cf224bbed7a653618d2b9e832455 | contrib/devtools/security-check.py | python | get_PE_dll_characteristics | (executable) | return (arch,bits) | Get PE DllCharacteristics bits.
Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386'
and bits is the DllCharacteristics value. | Get PE DllCharacteristics bits.
Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386'
and bits is the DllCharacteristics value. | [
"Get",
"PE",
"DllCharacteristics",
"bits",
".",
"Returns",
"a",
"tuple",
"(",
"arch",
"bits",
")",
"where",
"arch",
"is",
"i386",
":",
"x86",
"-",
"64",
"or",
"i386",
"and",
"bits",
"is",
"the",
"DllCharacteristics",
"value",
"."
] | def get_PE_dll_characteristics(executable):
'''
Get PE DllCharacteristics bits.
Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386'
and bits is the DllCharacteristics value.
'''
p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
arch = ''
bits = 0
for line in stdout.split('\n'):
tokens = line.split()
if len(tokens)>=2 and tokens[0] == 'architecture:':
arch = tokens[1].rstrip(',')
if len(tokens)>=2 and tokens[0] == 'DllCharacteristics':
bits = int(tokens[1],16)
return (arch,bits) | [
"def",
"get_PE_dll_characteristics",
"(",
"executable",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"OBJDUMP_CMD",
",",
"'-x'",
",",
"executable",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
")",
"(",
"stdout",
",",
"stderr",
")",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
":",
"raise",
"IOError",
"(",
"'Error opening file'",
")",
"arch",
"=",
"''",
"bits",
"=",
"0",
"for",
"line",
"in",
"stdout",
".",
"split",
"(",
"'\\n'",
")",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">=",
"2",
"and",
"tokens",
"[",
"0",
"]",
"==",
"'architecture:'",
":",
"arch",
"=",
"tokens",
"[",
"1",
"]",
".",
"rstrip",
"(",
"','",
")",
"if",
"len",
"(",
"tokens",
")",
">=",
"2",
"and",
"tokens",
"[",
"0",
"]",
"==",
"'DllCharacteristics'",
":",
"bits",
"=",
"int",
"(",
"tokens",
"[",
"1",
"]",
",",
"16",
")",
"return",
"(",
"arch",
",",
"bits",
")"
] | https://github.com/unitusdev/unitus/blob/4cd523cb5b46cf224bbed7a653618d2b9e832455/contrib/devtools/security-check.py#L119-L137 |
|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/message.py | python | Message.get_charset | (self) | return self._charset | Return the Charset instance associated with the message's payload. | Return the Charset instance associated with the message's payload. | [
"Return",
"the",
"Charset",
"instance",
"associated",
"with",
"the",
"message",
"s",
"payload",
"."
] | def get_charset(self):
"""Return the Charset instance associated with the message's payload.
"""
return self._charset | [
"def",
"get_charset",
"(",
"self",
")",
":",
"return",
"self",
".",
"_charset"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/message.py#L273-L276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.