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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/http/server.py
python
BaseHTTPRequestHandler.send_error
(self, code, message=None, explain=None)
Send and log an error reply. Arguments are * code: an HTTP error code 3 digits * message: a simple optional 1 line reason phrase. *( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code * explain: a detailed message defaults to the long entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user.
Send and log an error reply.
[ "Send", "and", "log", "an", "error", "reply", "." ]
def send_error(self, code, message=None, explain=None): """Send and log an error reply. Arguments are * code: an HTTP error code 3 digits * message: a simple optional 1 line reason phrase. *( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code * explain: a detailed message defaults to the long entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user. """ try: shortmsg, longmsg = self.responses[code] except KeyError: shortmsg, longmsg = '???', '???' if message is None: message = shortmsg if explain is None: explain = longmsg self.log_error("code %d, message %s", code, message) self.send_response(code, message) self.send_header('Connection', 'close') # Message body is omitted for cases described in: # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified) # - RFC7231: 6.3.6. 205(Reset Content) body = None if (code >= 200 and code not in (HTTPStatus.NO_CONTENT, HTTPStatus.RESET_CONTENT, HTTPStatus.NOT_MODIFIED)): # HTML encode to prevent Cross Site Scripting attacks # (see bug #1100201) content = (self.error_message_format % { 'code': code, 'message': html.escape(message, quote=False), 'explain': html.escape(explain, quote=False) }) body = content.encode('UTF-8', 'replace') self.send_header("Content-Type", self.error_content_type) self.send_header('Content-Length', str(len(body))) self.end_headers() if self.command != 'HEAD' and body: self.wfile.write(body)
[ "def", "send_error", "(", "self", ",", "code", ",", "message", "=", "None", ",", "explain", "=", "None", ")", ":", "try", ":", "shortmsg", ",", "longmsg", "=", "self", ".", "responses", "[", "code", "]", "except", "KeyError", ":", "shortmsg", ",", "longmsg", "=", "'???'", ",", "'???'", "if", "message", "is", "None", ":", "message", "=", "shortmsg", "if", "explain", "is", "None", ":", "explain", "=", "longmsg", "self", ".", "log_error", "(", "\"code %d, message %s\"", ",", "code", ",", "message", ")", "self", ".", "send_response", "(", "code", ",", "message", ")", "self", ".", "send_header", "(", "'Connection'", ",", "'close'", ")", "# Message body is omitted for cases described in:", "# - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)", "# - RFC7231: 6.3.6. 205(Reset Content)", "body", "=", "None", "if", "(", "code", ">=", "200", "and", "code", "not", "in", "(", "HTTPStatus", ".", "NO_CONTENT", ",", "HTTPStatus", ".", "RESET_CONTENT", ",", "HTTPStatus", ".", "NOT_MODIFIED", ")", ")", ":", "# HTML encode to prevent Cross Site Scripting attacks", "# (see bug #1100201)", "content", "=", "(", "self", ".", "error_message_format", "%", "{", "'code'", ":", "code", ",", "'message'", ":", "html", ".", "escape", "(", "message", ",", "quote", "=", "False", ")", ",", "'explain'", ":", "html", ".", "escape", "(", "explain", ",", "quote", "=", "False", ")", "}", ")", "body", "=", "content", ".", "encode", "(", "'UTF-8'", ",", "'replace'", ")", "self", ".", "send_header", "(", "\"Content-Type\"", ",", "self", ".", "error_content_type", ")", "self", ".", "send_header", "(", "'Content-Length'", ",", "str", "(", "len", "(", "body", ")", ")", ")", "self", ".", "end_headers", "(", ")", "if", "self", ".", "command", "!=", "'HEAD'", "and", "body", ":", "self", ".", "wfile", ".", "write", "(", "body", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/http/server.py#L431-L482
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
doc/pydrake/build.py
python
_write_module
(name, f_name)
Writes an rst file for module `name` into `f_name`.
Writes an rst file for module `name` into `f_name`.
[ "Writes", "an", "rst", "file", "for", "module", "name", "into", "f_name", "." ]
def _write_module(name, f_name): """Writes an rst file for module `name` into `f_name`. """ if verbose(): print("Write: {}".format(name)) subs = _get_submodules(name) with open(f_name, 'w') as f: f.write("\n") rst_name = name.replace("_", "\\_") f.write("{}\n".format(rst_name)) f.write("=" * len(rst_name) + "\n") f.write("\n") if len(subs) > 0: f.write(".. toctree::\n") f.write(" :maxdepth: 1\n") f.write("\n") for sub in subs: f.write(" {}\n".format(sub)) f.write("\n\n") f.write(".. automodule:: {}\n".format(name)) f.write(" :members:\n") # See if there's a corresponding private CcPybind library. if _has_cc_imported_symbols(name): f.write(" :imported-members:\n") f.write(" :undoc-members:\n") f.write(" :show-inheritance:\n")
[ "def", "_write_module", "(", "name", ",", "f_name", ")", ":", "if", "verbose", "(", ")", ":", "print", "(", "\"Write: {}\"", ".", "format", "(", "name", ")", ")", "subs", "=", "_get_submodules", "(", "name", ")", "with", "open", "(", "f_name", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "\"\\n\"", ")", "rst_name", "=", "name", ".", "replace", "(", "\"_\"", ",", "\"\\\\_\"", ")", "f", ".", "write", "(", "\"{}\\n\"", ".", "format", "(", "rst_name", ")", ")", "f", ".", "write", "(", "\"=\"", "*", "len", "(", "rst_name", ")", "+", "\"\\n\"", ")", "f", ".", "write", "(", "\"\\n\"", ")", "if", "len", "(", "subs", ")", ">", "0", ":", "f", ".", "write", "(", "\".. toctree::\\n\"", ")", "f", ".", "write", "(", "\" :maxdepth: 1\\n\"", ")", "f", ".", "write", "(", "\"\\n\"", ")", "for", "sub", "in", "subs", ":", "f", ".", "write", "(", "\" {}\\n\"", ".", "format", "(", "sub", ")", ")", "f", ".", "write", "(", "\"\\n\\n\"", ")", "f", ".", "write", "(", "\".. automodule:: {}\\n\"", ".", "format", "(", "name", ")", ")", "f", ".", "write", "(", "\" :members:\\n\"", ")", "# See if there's a corresponding private CcPybind library.", "if", "_has_cc_imported_symbols", "(", "name", ")", ":", "f", ".", "write", "(", "\" :imported-members:\\n\"", ")", "f", ".", "write", "(", "\" :undoc-members:\\n\"", ")", "f", ".", "write", "(", "\" :show-inheritance:\\n\"", ")" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/doc/pydrake/build.py#L80-L105
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
bindings/python/htcondor/htchirp/htchirp.py
python
HTChirp.rmdir
(self, remote_path, recursive=False)
Delete a directory on the remote machine. The directory must be empty unless recursive is set to True. :param remote_path: Path to directory :param recursive: If set to True, recursively delete remote_path
Delete a directory on the remote machine.
[ "Delete", "a", "directory", "on", "the", "remote", "machine", "." ]
def rmdir(self, remote_path, recursive=False): """Delete a directory on the remote machine. The directory must be empty unless recursive is set to True. :param remote_path: Path to directory :param recursive: If set to True, recursively delete remote_path """ if recursive: self.rmall(remote_path) else: self._simple_command("rmdir {0}\n".format(quote(remote_path)))
[ "def", "rmdir", "(", "self", ",", "remote_path", ",", "recursive", "=", "False", ")", ":", "if", "recursive", ":", "self", ".", "rmall", "(", "remote_path", ")", "else", ":", "self", ".", "_simple_command", "(", "\"rmdir {0}\\n\"", ".", "format", "(", "quote", "(", "remote_path", ")", ")", ")" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/htchirp/htchirp.py#L842-L856
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/command.py
python
FbCmd.cmdloop
(self)
Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
[ "Repeatedly", "issue", "a", "prompt", "accept", "input", "parse", "an", "initial", "prefix", "off", "the", "received", "input", "and", "dispatch", "to", "action", "methods", "passing", "them", "the", "remainder", "of", "the", "line", "as", "argument", "." ]
def cmdloop(self): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ self.preloop() self.io.pre_input(self.complete) try: stop = None while not stop: if self.cmdqueue: # First, clear out anything we have in the command queue line = self.cmdqueue.pop(0) else: # Then, accept input line = self.io.get_input(self.prompt) stop = self.runcmd(line) self.postloop() finally: self.io.post_input()
[ "def", "cmdloop", "(", "self", ")", ":", "self", ".", "preloop", "(", ")", "self", ".", "io", ".", "pre_input", "(", "self", ".", "complete", ")", "try", ":", "stop", "=", "None", "while", "not", "stop", ":", "if", "self", ".", "cmdqueue", ":", "# First, clear out anything we have in the command queue", "line", "=", "self", ".", "cmdqueue", ".", "pop", "(", "0", ")", "else", ":", "# Then, accept input", "line", "=", "self", ".", "io", ".", "get_input", "(", "self", ".", "prompt", ")", "stop", "=", "self", ".", "runcmd", "(", "line", ")", "self", ".", "postloop", "(", ")", "finally", ":", "self", ".", "io", ".", "post_input", "(", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/command.py#L162-L182
google/ion
ef47f3b824050499ce5c6f774b366f6c4dbce0af
ion/build.py
python
BuildState.GetAdditionalGypGeneratorFlags
(self)
return self.GetCommandLineOptions().G
Returns list of additional gyp variables. These are directly passed on the command line as -G=foo=bar. Returns: A list of extra flags to pass through to the gyp as generator flags.
Returns list of additional gyp variables.
[ "Returns", "list", "of", "additional", "gyp", "variables", "." ]
def GetAdditionalGypGeneratorFlags(self): """Returns list of additional gyp variables. These are directly passed on the command line as -G=foo=bar. Returns: A list of extra flags to pass through to the gyp as generator flags. """ return self.GetCommandLineOptions().G
[ "def", "GetAdditionalGypGeneratorFlags", "(", "self", ")", ":", "return", "self", ".", "GetCommandLineOptions", "(", ")", ".", "G" ]
https://github.com/google/ion/blob/ef47f3b824050499ce5c6f774b366f6c4dbce0af/ion/build.py#L1605-L1613
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py
python
WinTool.ExecClCompile
(self, project_dir, selected_files)
return subprocess.call(cmd, shell=True, cwd=BASE_DIR)
Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.
Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.
[ "Executed", "by", "msvs", "-", "ninja", "projects", "when", "the", "ClCompile", "target", "is", "used", "to", "build", "selected", "C", "/", "C", "++", "files", "." ]
def ExecClCompile(self, project_dir, selected_files): """Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.""" project_dir = os.path.relpath(project_dir, BASE_DIR) selected_files = selected_files.split(";") ninja_targets = [ os.path.join(project_dir, filename) + "^^" for filename in selected_files ] cmd = ["ninja.exe"] cmd.extend(ninja_targets) return subprocess.call(cmd, shell=True, cwd=BASE_DIR)
[ "def", "ExecClCompile", "(", "self", ",", "project_dir", ",", "selected_files", ")", ":", "project_dir", "=", "os", ".", "path", ".", "relpath", "(", "project_dir", ",", "BASE_DIR", ")", "selected_files", "=", "selected_files", ".", "split", "(", "\";\"", ")", "ninja_targets", "=", "[", "os", ".", "path", ".", "join", "(", "project_dir", ",", "filename", ")", "+", "\"^^\"", "for", "filename", "in", "selected_files", "]", "cmd", "=", "[", "\"ninja.exe\"", "]", "cmd", ".", "extend", "(", "ninja_targets", ")", "return", "subprocess", ".", "call", "(", "cmd", ",", "shell", "=", "True", ",", "cwd", "=", "BASE_DIR", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py#L360-L370
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py
python
AutoScaleConnection.get_all_scaling_process_types
(self)
return self.get_list('DescribeScalingProcessTypes', {}, [('member', ProcessType)])
Returns scaling process types for use in the ResumeProcesses and SuspendProcesses actions.
Returns scaling process types for use in the ResumeProcesses and SuspendProcesses actions.
[ "Returns", "scaling", "process", "types", "for", "use", "in", "the", "ResumeProcesses", "and", "SuspendProcesses", "actions", "." ]
def get_all_scaling_process_types(self): """ Returns scaling process types for use in the ResumeProcesses and SuspendProcesses actions. """ return self.get_list('DescribeScalingProcessTypes', {}, [('member', ProcessType)])
[ "def", "get_all_scaling_process_types", "(", "self", ")", ":", "return", "self", ".", "get_list", "(", "'DescribeScalingProcessTypes'", ",", "{", "}", ",", "[", "(", "'member'", ",", "ProcessType", ")", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py#L576-L582
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/commands/defacl.py
python
DefAclCommand._ChDefAcl
(self)
Parses options and changes default object ACLs on specified buckets.
Parses options and changes default object ACLs on specified buckets.
[ "Parses", "options", "and", "changes", "default", "object", "ACLs", "on", "specified", "buckets", "." ]
def _ChDefAcl(self): """Parses options and changes default object ACLs on specified buckets.""" self.parse_versions = True self.changes = [] if self.sub_opts: for o, a in self.sub_opts: if o == '-g': self.changes.append( aclhelpers.AclChange(a, scope_type=aclhelpers.ChangeType.GROUP)) if o == '-u': self.changes.append( aclhelpers.AclChange(a, scope_type=aclhelpers.ChangeType.USER)) if o == '-p': self.changes.append( aclhelpers.AclChange(a, scope_type=aclhelpers.ChangeType.PROJECT)) if o == '-d': self.changes.append(aclhelpers.AclDel(a)) if not self.changes: raise CommandException( 'Please specify at least one access change ' 'with the -g, -u, or -d flags') if (not UrlsAreForSingleProvider(self.args) or StorageUrlFromString(self.args[0]).scheme != 'gs'): raise CommandException( 'The "{0}" command can only be used with gs:// URLs'.format( self.command_name)) bucket_urls = set() for url_arg in self.args: for result in self.WildcardIterator(url_arg): if not result.storage_url.IsBucket(): raise CommandException( 'The defacl ch command can only be applied to buckets.') bucket_urls.add(result.storage_url) for storage_url in bucket_urls: self.ApplyAclChanges(storage_url)
[ "def", "_ChDefAcl", "(", "self", ")", ":", "self", ".", "parse_versions", "=", "True", "self", ".", "changes", "=", "[", "]", "if", "self", ".", "sub_opts", ":", "for", "o", ",", "a", "in", "self", ".", "sub_opts", ":", "if", "o", "==", "'-g'", ":", "self", ".", "changes", ".", "append", "(", "aclhelpers", ".", "AclChange", "(", "a", ",", "scope_type", "=", "aclhelpers", ".", "ChangeType", ".", "GROUP", ")", ")", "if", "o", "==", "'-u'", ":", "self", ".", "changes", ".", "append", "(", "aclhelpers", ".", "AclChange", "(", "a", ",", "scope_type", "=", "aclhelpers", ".", "ChangeType", ".", "USER", ")", ")", "if", "o", "==", "'-p'", ":", "self", ".", "changes", ".", "append", "(", "aclhelpers", ".", "AclChange", "(", "a", ",", "scope_type", "=", "aclhelpers", ".", "ChangeType", ".", "PROJECT", ")", ")", "if", "o", "==", "'-d'", ":", "self", ".", "changes", ".", "append", "(", "aclhelpers", ".", "AclDel", "(", "a", ")", ")", "if", "not", "self", ".", "changes", ":", "raise", "CommandException", "(", "'Please specify at least one access change '", "'with the -g, -u, or -d flags'", ")", "if", "(", "not", "UrlsAreForSingleProvider", "(", "self", ".", "args", ")", "or", "StorageUrlFromString", "(", "self", ".", "args", "[", "0", "]", ")", ".", "scheme", "!=", "'gs'", ")", ":", "raise", "CommandException", "(", "'The \"{0}\" command can only be used with gs:// URLs'", ".", "format", "(", "self", ".", "command_name", ")", ")", "bucket_urls", "=", "set", "(", ")", "for", "url_arg", "in", "self", ".", "args", ":", "for", "result", "in", "self", ".", "WildcardIterator", "(", "url_arg", ")", ":", "if", "not", "result", ".", "storage_url", ".", "IsBucket", "(", ")", ":", "raise", "CommandException", "(", "'The defacl ch command can only be applied to buckets.'", ")", "bucket_urls", ".", "add", "(", "result", ".", "storage_url", ")", "for", "storage_url", "in", "bucket_urls", ":", "self", ".", "ApplyAclChanges", "(", "storage_url", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/commands/defacl.py#L215-L254
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/compiler.py
python
CodeGenerator.return_buffer_contents
( self, frame: Frame, force_unescaped: bool = False )
Return the buffer contents of the frame.
Return the buffer contents of the frame.
[ "Return", "the", "buffer", "contents", "of", "the", "frame", "." ]
def return_buffer_contents( self, frame: Frame, force_unescaped: bool = False ) -> None: """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline("if context.eval_ctx.autoescape:") self.indent() self.writeline(f"return Markup(concat({frame.buffer}))") self.outdent() self.writeline("else:") self.indent() self.writeline(f"return concat({frame.buffer})") self.outdent() return elif frame.eval_ctx.autoescape: self.writeline(f"return Markup(concat({frame.buffer}))") return self.writeline(f"return concat({frame.buffer})")
[ "def", "return_buffer_contents", "(", "self", ",", "frame", ":", "Frame", ",", "force_unescaped", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "not", "force_unescaped", ":", "if", "frame", ".", "eval_ctx", ".", "volatile", ":", "self", ".", "writeline", "(", "\"if context.eval_ctx.autoescape:\"", ")", "self", ".", "indent", "(", ")", "self", ".", "writeline", "(", "f\"return Markup(concat({frame.buffer}))\"", ")", "self", ".", "outdent", "(", ")", "self", ".", "writeline", "(", "\"else:\"", ")", "self", ".", "indent", "(", ")", "self", ".", "writeline", "(", "f\"return concat({frame.buffer})\"", ")", "self", ".", "outdent", "(", ")", "return", "elif", "frame", ".", "eval_ctx", ".", "autoescape", ":", "self", ".", "writeline", "(", "f\"return Markup(concat({frame.buffer}))\"", ")", "return", "self", ".", "writeline", "(", "f\"return concat({frame.buffer})\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/compiler.py#L394-L412
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
AlphaPixelData_Accessor.MoveTo
(*args, **kwargs)
return _gdi_.AlphaPixelData_Accessor_MoveTo(*args, **kwargs)
MoveTo(self, AlphaPixelData data, int x, int y)
MoveTo(self, AlphaPixelData data, int x, int y)
[ "MoveTo", "(", "self", "AlphaPixelData", "data", "int", "x", "int", "y", ")" ]
def MoveTo(*args, **kwargs): """MoveTo(self, AlphaPixelData data, int x, int y)""" return _gdi_.AlphaPixelData_Accessor_MoveTo(*args, **kwargs)
[ "def", "MoveTo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "AlphaPixelData_Accessor_MoveTo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1254-L1256
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/remote/kernel_build_server.py
python
AkgBuilder.create
(self, process_num, waitime)
Create akg processor
Create akg processor
[ "Create", "akg", "processor" ]
def create(self, process_num, waitime): """ Create akg processor""" self.akg_processor = create_akg_parallel_process(process_num, waitime, self.platform)
[ "def", "create", "(", "self", ",", "process_num", ",", "waitime", ")", ":", "self", ".", "akg_processor", "=", "create_akg_parallel_process", "(", "process_num", ",", "waitime", ",", "self", ".", "platform", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/remote/kernel_build_server.py#L134-L136
0ad/0ad
f58db82e0e925016d83f4e3fa7ca599e3866e2af
source/tools/lobbybots/xpartamupp/echelon.py
python
EcheLOn._muc_online
(self, presence)
Add joining players to the list of players. Arguments: presence (sleekxmpp.stanza.presence.Presence): Received presence stanza.
Add joining players to the list of players.
[ "Add", "joining", "players", "to", "the", "list", "of", "players", "." ]
def _muc_online(self, presence): """Add joining players to the list of players. Arguments: presence (sleekxmpp.stanza.presence.Presence): Received presence stanza. """ nick = str(presence['muc']['nick']) jid = sleekxmpp.jid.JID(presence['muc']['jid']) if nick == self.nick: return if jid.resource != '0ad': return self.leaderboard.get_or_create_player(jid) self._broadcast_rating_list() logging.debug("Client '%s' connected with a nick of '%s'.", jid, nick)
[ "def", "_muc_online", "(", "self", ",", "presence", ")", ":", "nick", "=", "str", "(", "presence", "[", "'muc'", "]", "[", "'nick'", "]", ")", "jid", "=", "sleekxmpp", ".", "jid", ".", "JID", "(", "presence", "[", "'muc'", "]", "[", "'jid'", "]", ")", "if", "nick", "==", "self", ".", "nick", ":", "return", "if", "jid", ".", "resource", "!=", "'0ad'", ":", "return", "self", ".", "leaderboard", ".", "get_or_create_player", "(", "jid", ")", "self", ".", "_broadcast_rating_list", "(", ")", "logging", ".", "debug", "(", "\"Client '%s' connected with a nick of '%s'.\"", ",", "jid", ",", "nick", ")" ]
https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/lobbybots/xpartamupp/echelon.py#L511-L532
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/Editor/Scripts/external/pyassimp/helper.py
python
hasattr_silent
(object, name)
Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2) functionality of silently catching exceptions. Returns the result of hasatter() or False if an exception was raised.
Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2) functionality of silently catching exceptions.
[ "Calls", "hasttr", "()", "with", "the", "given", "parameters", "and", "preserves", "the", "legacy", "(", "pre", "-", "Python", "3", ".", "2", ")", "functionality", "of", "silently", "catching", "exceptions", "." ]
def hasattr_silent(object, name): """ Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2) functionality of silently catching exceptions. Returns the result of hasatter() or False if an exception was raised. """ try: if not object: return False return hasattr(object, name) except AttributeError: return False
[ "def", "hasattr_silent", "(", "object", ",", "name", ")", ":", "try", ":", "if", "not", "object", ":", "return", "False", "return", "hasattr", "(", "object", ",", "name", ")", "except", "AttributeError", ":", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/Editor/Scripts/external/pyassimp/helper.py#L268-L281
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/libdeps/libdeps/analyzer.py
python
CommonDependents.run
(self)
return sorted(list(set.intersection(*neighbor_sets)))
For a given set of nodes, report what nodes depend on all nodes from that set.
For a given set of nodes, report what nodes depend on all nodes from that set.
[ "For", "a", "given", "set", "of", "nodes", "report", "what", "nodes", "depend", "on", "all", "nodes", "from", "that", "set", "." ]
def run(self): """For a given set of nodes, report what nodes depend on all nodes from that set.""" neighbor_sets = [set(self._dependents_graph[node]) for node in self._nodes] return sorted(list(set.intersection(*neighbor_sets)))
[ "def", "run", "(", "self", ")", ":", "neighbor_sets", "=", "[", "set", "(", "self", ".", "_dependents_graph", "[", "node", "]", ")", "for", "node", "in", "self", ".", "_nodes", "]", "return", "sorted", "(", "list", "(", "set", ".", "intersection", "(", "*", "neighbor_sets", ")", ")", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/libdeps/libdeps/analyzer.py#L392-L396
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py
python
is_svn_page
(html)
return (re.search(r'<title>[^<]*Revision \d+:', html) and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I))
Returns true if the page appears to be the index page of an svn repository
Returns true if the page appears to be the index page of an svn repository
[ "Returns", "true", "if", "the", "page", "appears", "to", "be", "the", "index", "page", "of", "an", "svn", "repository" ]
def is_svn_page(html): # type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]] """ Returns true if the page appears to be the index page of an svn repository """ return (re.search(r'<title>[^<]*Revision \d+:', html) and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I))
[ "def", "is_svn_page", "(", "html", ")", ":", "# type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]]", "return", "(", "re", ".", "search", "(", "r'<title>[^<]*Revision \\d+:'", ",", "html", ")", "and", "re", ".", "search", "(", "r'Powered by (?:<a[^>]*?>)?Subversion'", ",", "html", ",", "re", ".", "I", ")", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py#L219-L225
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py
python
HighPage.on_new_color_set
(self)
Display sample of new color selection on the dialog.
Display sample of new color selection on the dialog.
[ "Display", "sample", "of", "new", "color", "selection", "on", "the", "dialog", "." ]
def on_new_color_set(self): "Display sample of new color selection on the dialog." new_color = self.color.get() self.style.configure('frame_color_set.TFrame', background=new_color) plane = 'foreground' if self.fg_bg_toggle.get() else 'background' sample_element = self.theme_elements[self.highlight_target.get()][0] self.highlight_sample.tag_config(sample_element, **{plane: new_color}) theme = self.custom_name.get() theme_element = sample_element + '-' + plane changes.add_option('highlight', theme, theme_element, new_color)
[ "def", "on_new_color_set", "(", "self", ")", ":", "new_color", "=", "self", ".", "color", ".", "get", "(", ")", "self", ".", "style", ".", "configure", "(", "'frame_color_set.TFrame'", ",", "background", "=", "new_color", ")", "plane", "=", "'foreground'", "if", "self", ".", "fg_bg_toggle", ".", "get", "(", ")", "else", "'background'", "sample_element", "=", "self", ".", "theme_elements", "[", "self", ".", "highlight_target", ".", "get", "(", ")", "]", "[", "0", "]", "self", ".", "highlight_sample", ".", "tag_config", "(", "sample_element", ",", "*", "*", "{", "plane", ":", "new_color", "}", ")", "theme", "=", "self", ".", "custom_name", ".", "get", "(", ")", "theme_element", "=", "sample_element", "+", "'-'", "+", "plane", "changes", ".", "add_option", "(", "'highlight'", ",", "theme", ",", "theme_element", ",", "new_color", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py#L1118-L1127
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/ExodusViewer/plugins/CameraPlugin.py
python
CameraPlugin._callbackResetButton
(self)
Recomputes the original view.
Recomputes the original view.
[ "Recomputes", "the", "original", "view", "." ]
def _callbackResetButton(self): """ Recomputes the original view. """ if self._result: renderer = self._result.getVTKRenderer() renderer.ResetCamera() camera = renderer.GetActiveCamera() fp = camera.GetFocalPoint() p = camera.GetPosition() dist = math.sqrt( (p[0]-fp[0])**2 + (p[1]-fp[1])**2 + (p[2]-fp[2])**2 ) camera.SetPosition(fp[0], fp[1], fp[2]+dist) camera.SetViewUp(0.0, 1.0, 0.0) self._result.setNeedsUpdate(True) self.windowRequiresUpdate.emit()
[ "def", "_callbackResetButton", "(", "self", ")", ":", "if", "self", ".", "_result", ":", "renderer", "=", "self", ".", "_result", ".", "getVTKRenderer", "(", ")", "renderer", ".", "ResetCamera", "(", ")", "camera", "=", "renderer", ".", "GetActiveCamera", "(", ")", "fp", "=", "camera", ".", "GetFocalPoint", "(", ")", "p", "=", "camera", ".", "GetPosition", "(", ")", "dist", "=", "math", ".", "sqrt", "(", "(", "p", "[", "0", "]", "-", "fp", "[", "0", "]", ")", "**", "2", "+", "(", "p", "[", "1", "]", "-", "fp", "[", "1", "]", ")", "**", "2", "+", "(", "p", "[", "2", "]", "-", "fp", "[", "2", "]", ")", "**", "2", ")", "camera", ".", "SetPosition", "(", "fp", "[", "0", "]", ",", "fp", "[", "1", "]", ",", "fp", "[", "2", "]", "+", "dist", ")", "camera", ".", "SetViewUp", "(", "0.0", ",", "1.0", ",", "0.0", ")", "self", ".", "_result", ".", "setNeedsUpdate", "(", "True", ")", "self", ".", "windowRequiresUpdate", ".", "emit", "(", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/CameraPlugin.py#L71-L85
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/wubi/backends/common/tasklist.py
python
Task._get_weight
(self)
return float(self.size*self.weight) + sum(subtasks_weight)
get total weight for this task and all the subtasks
get total weight for this task and all the subtasks
[ "get", "total", "weight", "for", "this", "task", "and", "all", "the", "subtasks" ]
def _get_weight(self): ''' get total weight for this task and all the subtasks ''' subtasks_weight = [s._get_weight() for s in self.subtasks] return float(self.size*self.weight) + sum(subtasks_weight)
[ "def", "_get_weight", "(", "self", ")", ":", "subtasks_weight", "=", "[", "s", ".", "_get_weight", "(", ")", "for", "s", "in", "self", ".", "subtasks", "]", "return", "float", "(", "self", ".", "size", "*", "self", ".", "weight", ")", "+", "sum", "(", "subtasks_weight", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/wubi/backends/common/tasklist.py#L348-L353
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/findertools.py
python
emptytrash
()
empty the trash
empty the trash
[ "empty", "the", "trash" ]
def emptytrash(): """empty the trash""" finder = _getfinder() args = {} attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('trsh'), fr=None) _reply, args, attrs = finder.send("fndr", "empt", args, attrs) if 'errn' in args: raise aetools.Error, aetools.decodeerror(args)
[ "def", "emptytrash", "(", ")", ":", "finder", "=", "_getfinder", "(", ")", "args", "=", "{", "}", "attrs", "=", "{", "}", "args", "[", "'----'", "]", "=", "aetypes", ".", "ObjectSpecifier", "(", "want", "=", "aetypes", ".", "Type", "(", "'prop'", ")", ",", "form", "=", "\"prop\"", ",", "seld", "=", "aetypes", ".", "Type", "(", "'trsh'", ")", ",", "fr", "=", "None", ")", "_reply", ",", "args", ",", "attrs", "=", "finder", ".", "send", "(", "\"fndr\"", ",", "\"empt\"", ",", "args", ",", "attrs", ")", "if", "'errn'", "in", "args", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "args", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/findertools.py#L689-L697
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py
python
filename_match
(filename, patterns, default=True)
return any(fnmatch(filename, pattern) for pattern in patterns)
Check if patterns contains a pattern that matches filename. If patterns is unspecified, this always returns True.
Check if patterns contains a pattern that matches filename.
[ "Check", "if", "patterns", "contains", "a", "pattern", "that", "matches", "filename", "." ]
def filename_match(filename, patterns, default=True): """Check if patterns contains a pattern that matches filename. If patterns is unspecified, this always returns True. """ if not patterns: return default return any(fnmatch(filename, pattern) for pattern in patterns)
[ "def", "filename_match", "(", "filename", ",", "patterns", ",", "default", "=", "True", ")", ":", "if", "not", "patterns", ":", "return", "default", "return", "any", "(", "fnmatch", "(", "filename", ",", "pattern", ")", "for", "pattern", "in", "patterns", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py#L1151-L1158
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/learn/python/learn/monitors.py
python
BaseMonitor.step_begin
(self, step)
return []
Callback before training step begins. You may use this callback to request evaluation of additional tensors in the graph. Args: step: `int`, the current value of the global step. Returns: List of `Tensor` objects or string tensor names to be run. Raises: ValueError: if we've already begun a step, or `step` < 0, or `step` > `max_steps`.
Callback before training step begins.
[ "Callback", "before", "training", "step", "begins", "." ]
def step_begin(self, step): """Callback before training step begins. You may use this callback to request evaluation of additional tensors in the graph. Args: step: `int`, the current value of the global step. Returns: List of `Tensor` objects or string tensor names to be run. Raises: ValueError: if we've already begun a step, or `step` < 0, or `step` > `max_steps`. """ if (step < 0) or ( (self._max_steps is not None) and (step > self._max_steps)): raise ValueError("Invalid step %s." % step) self._current_step = step return []
[ "def", "step_begin", "(", "self", ",", "step", ")", ":", "if", "(", "step", "<", "0", ")", "or", "(", "(", "self", ".", "_max_steps", "is", "not", "None", ")", "and", "(", "step", ">", "self", ".", "_max_steps", ")", ")", ":", "raise", "ValueError", "(", "\"Invalid step %s.\"", "%", "step", ")", "self", ".", "_current_step", "=", "step", "return", "[", "]" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/monitors.py#L218-L238
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_trafficlight.py
python
TrafficLightDomain.setProgram
(self, tlsID, programID)
setProgram(string, string) -> None Switches to the program with the given programID. The program must have been loaded earlier. The special value 'off' can always be used to switch off the traffic light.
setProgram(string, string) -> None
[ "setProgram", "(", "string", "string", ")", "-", ">", "None" ]
def setProgram(self, tlsID, programID): """setProgram(string, string) -> None Switches to the program with the given programID. The program must have been loaded earlier. The special value 'off' can always be used to switch off the traffic light. """ self._setCmd(tc.TL_PROGRAM, tlsID, "s", programID)
[ "def", "setProgram", "(", "self", ",", "tlsID", ",", "programID", ")", ":", "self", ".", "_setCmd", "(", "tc", ".", "TL_PROGRAM", ",", "tlsID", ",", "\"s\"", ",", "programID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_trafficlight.py#L321-L328
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
toolkit/crashreporter/tools/symbolstore.py
python
Dumper_Mac.ShouldSkipDir
(self, dir)
return False
We create .dSYM bundles on the fly, but if someone runs buildsymbols twice, we should skip any bundles we created previously, otherwise we'll recurse into them and try to dump the inner bits again.
We create .dSYM bundles on the fly, but if someone runs buildsymbols twice, we should skip any bundles we created previously, otherwise we'll recurse into them and try to dump the inner bits again.
[ "We", "create", ".", "dSYM", "bundles", "on", "the", "fly", "but", "if", "someone", "runs", "buildsymbols", "twice", "we", "should", "skip", "any", "bundles", "we", "created", "previously", "otherwise", "we", "ll", "recurse", "into", "them", "and", "try", "to", "dump", "the", "inner", "bits", "again", "." ]
def ShouldSkipDir(self, dir): """We create .dSYM bundles on the fly, but if someone runs buildsymbols twice, we should skip any bundles we created previously, otherwise we'll recurse into them and try to dump the inner bits again.""" if dir.endswith(".dSYM"): return True return False
[ "def", "ShouldSkipDir", "(", "self", ",", "dir", ")", ":", "if", "dir", ".", "endswith", "(", "\".dSYM\"", ")", ":", "return", "True", "return", "False" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/toolkit/crashreporter/tools/symbolstore.py#L832-L839
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/masked/textctrl.py
python
BaseMaskedTextCtrl._CalcSize
(self, size=None)
return self._calcSize(size)
Calculate automatic size if allowed; use base mixin function.
Calculate automatic size if allowed; use base mixin function.
[ "Calculate", "automatic", "size", "if", "allowed", ";", "use", "base", "mixin", "function", "." ]
def _CalcSize(self, size=None): """ Calculate automatic size if allowed; use base mixin function. """ return self._calcSize(size)
[ "def", "_CalcSize", "(", "self", ",", "size", "=", "None", ")", ":", "return", "self", ".", "_calcSize", "(", "size", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/textctrl.py#L366-L370
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_RSA_Decrypt_REQUEST.__init__
(self, keyHandle = TPM_HANDLE(), cipherText = None, inScheme = None, label = None)
This command performs RSA decryption using the indicated padding scheme according to IETF RFC 8017 ((PKCS#1). Attributes: keyHandle (TPM_HANDLE): RSA key to use for decryption Auth Index: 1 Auth Role: USER cipherText (bytes): Cipher text to be decrypted NOTE An encrypted RSA data block is the size of the public modulus. inScheme (TPMU_ASYM_SCHEME): The padding scheme to use if scheme associated with keyHandle is TPM_ALG_NULL One of: TPMS_KEY_SCHEME_ECDH, TPMS_KEY_SCHEME_ECMQV, TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, TPMS_ENC_SCHEME_RSAES, TPMS_ENC_SCHEME_OAEP, TPMS_SCHEME_HASH, TPMS_NULL_ASYM_SCHEME. label (bytes): Label whose association with the message is to be verified
This command performs RSA decryption using the indicated padding scheme according to IETF RFC 8017 ((PKCS#1).
[ "This", "command", "performs", "RSA", "decryption", "using", "the", "indicated", "padding", "scheme", "according", "to", "IETF", "RFC", "8017", "((", "PKCS#1", ")", "." ]
def __init__(self, keyHandle = TPM_HANDLE(), cipherText = None, inScheme = None, label = None): """ This command performs RSA decryption using the indicated padding scheme according to IETF RFC 8017 ((PKCS#1). Attributes: keyHandle (TPM_HANDLE): RSA key to use for decryption Auth Index: 1 Auth Role: USER cipherText (bytes): Cipher text to be decrypted NOTE An encrypted RSA data block is the size of the public modulus. inScheme (TPMU_ASYM_SCHEME): The padding scheme to use if scheme associated with keyHandle is TPM_ALG_NULL One of: TPMS_KEY_SCHEME_ECDH, TPMS_KEY_SCHEME_ECMQV, TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, TPMS_ENC_SCHEME_RSAES, TPMS_ENC_SCHEME_OAEP, TPMS_SCHEME_HASH, TPMS_NULL_ASYM_SCHEME. label (bytes): Label whose association with the message is to be verified """ self.keyHandle = keyHandle self.cipherText = cipherText self.inScheme = inScheme self.label = label
[ "def", "__init__", "(", "self", ",", "keyHandle", "=", "TPM_HANDLE", "(", ")", ",", "cipherText", "=", "None", ",", "inScheme", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "keyHandle", "=", "keyHandle", "self", ".", "cipherText", "=", "cipherText", "self", ".", "inScheme", "=", "inScheme", "self", ".", "label", "=", "label" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L10714-L10737
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/mox.py
python
MoxMetaTestBase.CleanUpTest
(cls, func)
return new_method
Adds Mox cleanup code to any MoxTestBase method. Always unsets stubs after a test. Will verify all mocks for tests that otherwise pass. Args: cls: MoxTestBase or subclass; the class whose test method we are altering. func: method; the method of the MoxTestBase test class we wish to alter. Returns: The modified method.
Adds Mox cleanup code to any MoxTestBase method.
[ "Adds", "Mox", "cleanup", "code", "to", "any", "MoxTestBase", "method", "." ]
def CleanUpTest(cls, func): """Adds Mox cleanup code to any MoxTestBase method. Always unsets stubs after a test. Will verify all mocks for tests that otherwise pass. Args: cls: MoxTestBase or subclass; the class whose test method we are altering. func: method; the method of the MoxTestBase test class we wish to alter. Returns: The modified method. """ def new_method(self, *args, **kwargs): mox_obj = getattr(self, 'mox', None) cleanup_mox = False if mox_obj and isinstance(mox_obj, Mox): cleanup_mox = True try: func(self, *args, **kwargs) finally: if cleanup_mox: mox_obj.UnsetStubs() if cleanup_mox: mox_obj.VerifyAll() new_method.__name__ = func.__name__ new_method.__doc__ = func.__doc__ new_method.__module__ = func.__module__ return new_method
[ "def", "CleanUpTest", "(", "cls", ",", "func", ")", ":", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "mox_obj", "=", "getattr", "(", "self", ",", "'mox'", ",", "None", ")", "cleanup_mox", "=", "False", "if", "mox_obj", "and", "isinstance", "(", "mox_obj", ",", "Mox", ")", ":", "cleanup_mox", "=", "True", "try", ":", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "if", "cleanup_mox", ":", "mox_obj", ".", "UnsetStubs", "(", ")", "if", "cleanup_mox", ":", "mox_obj", ".", "VerifyAll", "(", ")", "new_method", ".", "__name__", "=", "func", ".", "__name__", "new_method", ".", "__doc__", "=", "func", ".", "__doc__", "new_method", ".", "__module__", "=", "func", ".", "__module__", "return", "new_method" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/mox.py#L1358-L1386
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
clang/bindings/python/clang/cindex.py
python
Cursor.walk_preorder
(self)
Depth-first preorder walk over the cursor and its descendants. Yields cursors.
Depth-first preorder walk over the cursor and its descendants.
[ "Depth", "-", "first", "preorder", "walk", "over", "the", "cursor", "and", "its", "descendants", "." ]
def walk_preorder(self): """Depth-first preorder walk over the cursor and its descendants. Yields cursors. """ yield self for child in self.get_children(): for descendant in child.walk_preorder(): yield descendant
[ "def", "walk_preorder", "(", "self", ")", ":", "yield", "self", "for", "child", "in", "self", ".", "get_children", "(", ")", ":", "for", "descendant", "in", "child", ".", "walk_preorder", "(", ")", ":", "yield", "descendant" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/bindings/python/clang/cindex.py#L1845-L1853
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column/column.py
python
nullmask
(self)
return self.mask_array_view
The gpu buffer for the null-mask
The gpu buffer for the null-mask
[ "The", "gpu", "buffer", "for", "the", "null", "-", "mask" ]
def nullmask(self) -> Buffer: """The gpu buffer for the null-mask""" if not self.nullable: raise ValueError("Column has no null mask") return self.mask_array_view
[ "def", "nullmask", "(", "self", ")", "->", "Buffer", ":", "if", "not", "self", ".", "nullable", ":", "raise", "ValueError", "(", "\"Column has no null mask\"", ")", "return", "self", ".", "mask_array_view" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/column.py#L352-L356
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/maya/scripts/walterPanel/walterMayaTraverser.py
python
WalterMayaImplementation.expressionGroups
(self, origin)
return sorted(groupSet)
Get all available expression groups.
Get all available expression groups.
[ "Get", "all", "available", "expression", "groups", "." ]
def expressionGroups(self, origin): """Get all available expression groups.""" alembicGroups = pm.walterStandin(alembicAllGroups=origin) if alembicGroups: groupSet = set(alembicGroups) else: groupSet = set() for exp, grp, _ in self.iterateExpressionGroups(origin): if exp and grp: groupSet.add(grp) return sorted(groupSet)
[ "def", "expressionGroups", "(", "self", ",", "origin", ")", ":", "alembicGroups", "=", "pm", ".", "walterStandin", "(", "alembicAllGroups", "=", "origin", ")", "if", "alembicGroups", ":", "groupSet", "=", "set", "(", "alembicGroups", ")", "else", ":", "groupSet", "=", "set", "(", ")", "for", "exp", ",", "grp", ",", "_", "in", "self", ".", "iterateExpressionGroups", "(", "origin", ")", ":", "if", "exp", "and", "grp", ":", "groupSet", ".", "add", "(", "grp", ")", "return", "sorted", "(", "groupSet", ")" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterPanel/walterMayaTraverser.py#L698-L710
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py
python
raw_memcpy
(builder, dst, src, count, itemsize, align=1)
return _raw_memcpy(builder, 'llvm.memcpy', dst, src, count, itemsize, align)
Emit a raw memcpy() call for `count` items of size `itemsize` from `src` to `dest`.
Emit a raw memcpy() call for `count` items of size `itemsize` from `src` to `dest`.
[ "Emit", "a", "raw", "memcpy", "()", "call", "for", "count", "items", "of", "size", "itemsize", "from", "src", "to", "dest", "." ]
def raw_memcpy(builder, dst, src, count, itemsize, align=1): """ Emit a raw memcpy() call for `count` items of size `itemsize` from `src` to `dest`. """ return _raw_memcpy(builder, 'llvm.memcpy', dst, src, count, itemsize, align)
[ "def", "raw_memcpy", "(", "builder", ",", "dst", ",", "src", ",", "count", ",", "itemsize", ",", "align", "=", "1", ")", ":", "return", "_raw_memcpy", "(", "builder", ",", "'llvm.memcpy'", ",", "dst", ",", "src", ",", "count", ",", "itemsize", ",", "align", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py#L1005-L1010
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/build_swift/build_swift/shell.py
python
_flatmap
(func, *iterables)
return itertools.chain.from_iterable(map(func, *iterables))
Helper function that maps the given func over the iterables and then creates a single flat iterable from the results.
Helper function that maps the given func over the iterables and then creates a single flat iterable from the results.
[ "Helper", "function", "that", "maps", "the", "given", "func", "over", "the", "iterables", "and", "then", "creates", "a", "single", "flat", "iterable", "from", "the", "results", "." ]
def _flatmap(func, *iterables): """Helper function that maps the given func over the iterables and then creates a single flat iterable from the results. """ return itertools.chain.from_iterable(map(func, *iterables))
[ "def", "_flatmap", "(", "func", ",", "*", "iterables", ")", ":", "return", "itertools", ".", "chain", ".", "from_iterable", "(", "map", "(", "func", ",", "*", "iterables", ")", ")" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/build_swift/build_swift/shell.py#L97-L102
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py
python
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
[ "Calculate", "the", "generator", "specific", "info", "that", "gets", "fed", "to", "input", "(", "called", "by", "gyp", ")", "." ]
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "if", "generator_flags", ".", "get", "(", "'adjust_static_libraries'", ",", "False", ")", ":", "global", "generator_wants_static_library_dependencies_adjusted", "generator_wants_static_library_dependencies_adjusted", "=", "True" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L71-L77
lukasmonk/lucaschess
13e2e5cb13b38a720ccf897af649054a64bcb914
Code/QT/Columnas.py
python
Columna.QTcolorTexto
(self, rgb)
Convierte un parametro de color del texto para que sea usable por QT
Convierte un parametro de color del texto para que sea usable por QT
[ "Convierte", "un", "parametro", "de", "color", "del", "texto", "para", "que", "sea", "usable", "por", "QT" ]
def QTcolorTexto(self, rgb): """ Convierte un parametro de color del texto para que sea usable por QT """ if rgb == -1: return None else: return QtGui.QColor(rgb)
[ "def", "QTcolorTexto", "(", "self", ",", "rgb", ")", ":", "if", "rgb", "==", "-", "1", ":", "return", "None", "else", ":", "return", "QtGui", ".", "QColor", "(", "rgb", ")" ]
https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/QT/Columnas.py#L101-L108
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/session_bundle/gc.py
python
negation
(f)
return keep
Negate a filter. Args: f: filter function to invert Returns: A filter function that returns the negation of f.
Negate a filter.
[ "Negate", "a", "filter", "." ]
def negation(f): """Negate a filter. Args: f: filter function to invert Returns: A filter function that returns the negation of f. """ def keep(paths): l = set(paths) r = set(f(paths)) return sorted(list(l-r)) return keep
[ "def", "negation", "(", "f", ")", ":", "def", "keep", "(", "paths", ")", ":", "l", "=", "set", "(", "paths", ")", "r", "=", "set", "(", "f", "(", "paths", ")", ")", "return", "sorted", "(", "list", "(", "l", "-", "r", ")", ")", "return", "keep" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/session_bundle/gc.py#L174-L187
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Node/Python.py
python
ValueWithMemo
(value, built_value=None, name=None)
Memoized Value() node factory.
Memoized Value() node factory.
[ "Memoized", "Value", "()", "node", "factory", "." ]
def ValueWithMemo(value, built_value=None, name=None): """ Memoized Value() node factory. """ global _memo_lookup_map # No current support for memoizing a value that needs to be built. if built_value: return Value(value, built_value, name=name) try: memo_lookup_key = hash((value, name)) except TypeError: # Non-primitive types will hit this codepath. return Value(value, name=name) try: return _memo_lookup_map[memo_lookup_key] except KeyError: v = Value(value, built_value, name) _memo_lookup_map[memo_lookup_key] = v return v
[ "def", "ValueWithMemo", "(", "value", ",", "built_value", "=", "None", ",", "name", "=", "None", ")", ":", "global", "_memo_lookup_map", "# No current support for memoizing a value that needs to be built.", "if", "built_value", ":", "return", "Value", "(", "value", ",", "built_value", ",", "name", "=", "name", ")", "try", ":", "memo_lookup_key", "=", "hash", "(", "(", "value", ",", "name", ")", ")", "except", "TypeError", ":", "# Non-primitive types will hit this codepath.", "return", "Value", "(", "value", ",", "name", "=", "name", ")", "try", ":", "return", "_memo_lookup_map", "[", "memo_lookup_key", "]", "except", "KeyError", ":", "v", "=", "Value", "(", "value", ",", "built_value", ",", "name", ")", "_memo_lookup_map", "[", "memo_lookup_key", "]", "=", "v", "return", "v" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/Python.py#L174-L195
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/generator/ninja.py
python
QuoteShellArgument
(arg, flavor)
return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
Quote a string such that it will be interpreted as a single argument by the shell.
Quote a string such that it will be interpreted as a single argument by the shell.
[ "Quote", "a", "string", "such", "that", "it", "will", "be", "interpreted", "as", "a", "single", "argument", "by", "the", "shell", "." ]
def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
[ "def", "QuoteShellArgument", "(", "arg", ",", "flavor", ")", ":", "# Rather than attempting to enumerate the bad shell characters, just", "# whitelist common OK ones and quote anything else.", "if", "re", ".", "match", "(", "r'^[a-zA-Z0-9_=.\\\\/-]+$'", ",", "arg", ")", ":", "return", "arg", "# No quoting necessary.", "if", "flavor", "==", "'win'", ":", "return", "gyp", ".", "msvs_emulation", ".", "QuoteForRspFile", "(", "arg", ")", "return", "\"'\"", "+", "arg", ".", "replace", "(", "\"'\"", ",", "\"'\"", "+", "'\"\\'\"'", "+", "\"'\"", ")", "+", "\"'\"" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/generator/ninja.py#L77-L86
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py
python
StateSpaceModel._imputation_step
(self, current_times, state)
return (estimated_state, estimated_state_var, previous_times + catchup_times)
Add state transition noise to catch `state` up to `current_times`. State space models are inherently sequential, so we need to "predict through" any missing time steps to catch up each element of the batch to its next observation/prediction time. Args: current_times: A [batch size] Tensor of times to impute up to, not inclusive. state: A tuple of (mean, covariance, previous_times) having shapes mean; [batch size x state dimension] covariance; [batch size x state dimension x state dimension] previous_times; [batch size] Returns: Imputed model state corresponding to the `state` argument.
Add state transition noise to catch `state` up to `current_times`.
[ "Add", "state", "transition", "noise", "to", "catch", "state", "up", "to", "current_times", "." ]
def _imputation_step(self, current_times, state): """Add state transition noise to catch `state` up to `current_times`. State space models are inherently sequential, so we need to "predict through" any missing time steps to catch up each element of the batch to its next observation/prediction time. Args: current_times: A [batch size] Tensor of times to impute up to, not inclusive. state: A tuple of (mean, covariance, previous_times) having shapes mean; [batch size x state dimension] covariance; [batch size x state dimension x state dimension] previous_times; [batch size] Returns: Imputed model state corresponding to the `state` argument. """ estimated_state, estimated_state_var, previous_times = state catchup_times = current_times - previous_times non_negative_assertion = control_flow_ops.Assert( math_ops.reduce_all(catchup_times >= 0), [ "Negative imputation interval", catchup_times, current_times, previous_times ], summarize=100) with ops.control_dependencies([non_negative_assertion]): transition_matrices, transition_noise_sums = ( # pylint: disable=unbalanced-tuple-unpacking self._cached_transition_powers_and_sums(catchup_times)) estimated_state = self._kalman_filter.predict_state_mean( estimated_state, transition_matrices) estimated_state_var = self._kalman_filter.predict_state_var( estimated_state_var, transition_matrices, transition_noise_sums) return (estimated_state, estimated_state_var, previous_times + catchup_times)
[ "def", "_imputation_step", "(", "self", ",", "current_times", ",", "state", ")", ":", "estimated_state", ",", "estimated_state_var", ",", "previous_times", "=", "state", "catchup_times", "=", "current_times", "-", "previous_times", "non_negative_assertion", "=", "control_flow_ops", ".", "Assert", "(", "math_ops", ".", "reduce_all", "(", "catchup_times", ">=", "0", ")", ",", "[", "\"Negative imputation interval\"", ",", "catchup_times", ",", "current_times", ",", "previous_times", "]", ",", "summarize", "=", "100", ")", "with", "ops", ".", "control_dependencies", "(", "[", "non_negative_assertion", "]", ")", ":", "transition_matrices", ",", "transition_noise_sums", "=", "(", "# pylint: disable=unbalanced-tuple-unpacking", "self", ".", "_cached_transition_powers_and_sums", "(", "catchup_times", ")", ")", "estimated_state", "=", "self", ".", "_kalman_filter", ".", "predict_state_mean", "(", "estimated_state", ",", "transition_matrices", ")", "estimated_state_var", "=", "self", ".", "_kalman_filter", ".", "predict_state_var", "(", "estimated_state_var", ",", "transition_matrices", ",", "transition_noise_sums", ")", "return", "(", "estimated_state", ",", "estimated_state_var", ",", "previous_times", "+", "catchup_times", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py#L354-L387
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/copy_graph/python/util/copy_elements.py
python
copy_op_to_graph
(org_instance, to_graph, variables, scope="")
Given an `Operation` 'org_instance` from one `Graph`, initializes and returns a copy of it from another `Graph`, under the specified scope (default `""`). The copying is done recursively, so any `Operation` whose output is required to evaluate the `org_instance`, is also copied (unless already done). Since `Variable` instances are copied separately, those required to evaluate `org_instance` must be provided as input. Args: org_instance: An `Operation` from some `Graph`. Could be a `Placeholder` as well. to_graph: The `Graph` to copy `org_instance` to. variables: An iterable of `Variable` instances to copy `org_instance` to. scope: A scope for the new `Variable` (default `""`). Returns: The copied `Operation` from `to_graph`. Raises: TypeError: If `org_instance` is not an `Operation` or `Tensor`.
Given an `Operation` 'org_instance` from one `Graph`, initializes and returns a copy of it from another `Graph`, under the specified scope (default `""`).
[ "Given", "an", "Operation", "org_instance", "from", "one", "Graph", "initializes", "and", "returns", "a", "copy", "of", "it", "from", "another", "Graph", "under", "the", "specified", "scope", "(", "default", ")", "." ]
def copy_op_to_graph(org_instance, to_graph, variables, scope=""): """Given an `Operation` 'org_instance` from one `Graph`, initializes and returns a copy of it from another `Graph`, under the specified scope (default `""`). The copying is done recursively, so any `Operation` whose output is required to evaluate the `org_instance`, is also copied (unless already done). Since `Variable` instances are copied separately, those required to evaluate `org_instance` must be provided as input. Args: org_instance: An `Operation` from some `Graph`. Could be a `Placeholder` as well. to_graph: The `Graph` to copy `org_instance` to. variables: An iterable of `Variable` instances to copy `org_instance` to. scope: A scope for the new `Variable` (default `""`). Returns: The copied `Operation` from `to_graph`. Raises: TypeError: If `org_instance` is not an `Operation` or `Tensor`. """ #The name of the new instance if scope != '': new_name = scope + '/' + org_instance.name else: new_name = org_instance.name #Extract names of variables copied_variables = dict((x.name, x) for x in variables) #If a variable by the new name already exists, return the #correspondng tensor that will act as an input if new_name in copied_variables: return to_graph.get_tensor_by_name( copied_variables[new_name].name) #If an instance of the same name exists, return appropriately try: already_present = to_graph.as_graph_element(new_name, allow_tensor=True, allow_operation=True) return already_present except: pass #Get the collections that the new instance needs to be added to. #The new collections will also be a part of the given scope. collections = [] for name, collection in org_instance.graph._collections.items(): if org_instance in collection: if scope == '': collections.append(name) else: collections.append(scope + '/' + name) #Take action based on the class of the instance if isinstance(org_instance, ops.Tensor): #If its a Tensor, it is one of the outputs of the underlying #op. Therefore, copy the op itself and return the appropriate #output. op = org_instance.op new_op = copy_op_to_graph(op, to_graph, variables, scope) output_index = op.outputs.index(org_instance) new_tensor = new_op.outputs[output_index] #Add to collections if any for collection in collections: to_graph.add_to_collection(collection, new_tensor) return new_tensor elif isinstance(org_instance, ops.Operation): op = org_instance #If it has an original_op parameter, copy it if op._original_op is not None: new_original_op = copy_op_to_graph(op._original_op, to_graph, variables, scope) else: new_original_op = None #If it has control inputs, call this function recursively on each. new_control_inputs = [copy_op_to_graph(x, to_graph, variables, scope) for x in op.control_inputs] #If it has inputs, call this function recursively on each. new_inputs = [copy_op_to_graph(x, to_graph, variables, scope) for x in op.inputs] #Make a new node_def based on that of the original. #An instance of tensorflow.core.framework.graph_pb2.NodeDef, it #stores String-based info such as name, device and type of the op. #Unique to every Operation instance. new_node_def = deepcopy(op._node_def) #Change the name new_node_def.name = new_name #Copy the other inputs needed for initialization output_types = op._output_types[:] input_types = op._input_types[:] #Make a copy of the op_def too. #Its unique to every _type_ of Operation. op_def = deepcopy(op._op_def) #Initialize a new Operation instance new_op = ops.Operation(new_node_def, to_graph, new_inputs, output_types, new_control_inputs, input_types, new_original_op, op_def) #Use Graph's hidden methods to add the op to_graph._add_op(new_op) to_graph._record_op_seen_by_control_dependencies(new_op) for device_function in reversed(to_graph._device_function_stack): new_op._set_device(device_function(new_op)) return new_op else: raise TypeError("Could not copy instance: " + str(org_instance))
[ "def", "copy_op_to_graph", "(", "org_instance", ",", "to_graph", ",", "variables", ",", "scope", "=", "\"\"", ")", ":", "#The name of the new instance", "if", "scope", "!=", "''", ":", "new_name", "=", "scope", "+", "'/'", "+", "org_instance", ".", "name", "else", ":", "new_name", "=", "org_instance", ".", "name", "#Extract names of variables", "copied_variables", "=", "dict", "(", "(", "x", ".", "name", ",", "x", ")", "for", "x", "in", "variables", ")", "#If a variable by the new name already exists, return the", "#correspondng tensor that will act as an input", "if", "new_name", "in", "copied_variables", ":", "return", "to_graph", ".", "get_tensor_by_name", "(", "copied_variables", "[", "new_name", "]", ".", "name", ")", "#If an instance of the same name exists, return appropriately", "try", ":", "already_present", "=", "to_graph", ".", "as_graph_element", "(", "new_name", ",", "allow_tensor", "=", "True", ",", "allow_operation", "=", "True", ")", "return", "already_present", "except", ":", "pass", "#Get the collections that the new instance needs to be added to.", "#The new collections will also be a part of the given scope.", "collections", "=", "[", "]", "for", "name", ",", "collection", "in", "org_instance", ".", "graph", ".", "_collections", ".", "items", "(", ")", ":", "if", "org_instance", "in", "collection", ":", "if", "scope", "==", "''", ":", "collections", ".", "append", "(", "name", ")", "else", ":", "collections", ".", "append", "(", "scope", "+", "'/'", "+", "name", ")", "#Take action based on the class of the instance", "if", "isinstance", "(", "org_instance", ",", "ops", ".", "Tensor", ")", ":", "#If its a Tensor, it is one of the outputs of the underlying", "#op. Therefore, copy the op itself and return the appropriate", "#output.", "op", "=", "org_instance", ".", "op", "new_op", "=", "copy_op_to_graph", "(", "op", ",", "to_graph", ",", "variables", ",", "scope", ")", "output_index", "=", "op", ".", "outputs", ".", "index", "(", "org_instance", ")", "new_tensor", "=", "new_op", ".", "outputs", "[", "output_index", "]", "#Add to collections if any", "for", "collection", "in", "collections", ":", "to_graph", ".", "add_to_collection", "(", "collection", ",", "new_tensor", ")", "return", "new_tensor", "elif", "isinstance", "(", "org_instance", ",", "ops", ".", "Operation", ")", ":", "op", "=", "org_instance", "#If it has an original_op parameter, copy it", "if", "op", ".", "_original_op", "is", "not", "None", ":", "new_original_op", "=", "copy_op_to_graph", "(", "op", ".", "_original_op", ",", "to_graph", ",", "variables", ",", "scope", ")", "else", ":", "new_original_op", "=", "None", "#If it has control inputs, call this function recursively on each.", "new_control_inputs", "=", "[", "copy_op_to_graph", "(", "x", ",", "to_graph", ",", "variables", ",", "scope", ")", "for", "x", "in", "op", ".", "control_inputs", "]", "#If it has inputs, call this function recursively on each.", "new_inputs", "=", "[", "copy_op_to_graph", "(", "x", ",", "to_graph", ",", "variables", ",", "scope", ")", "for", "x", "in", "op", ".", "inputs", "]", "#Make a new node_def based on that of the original.", "#An instance of tensorflow.core.framework.graph_pb2.NodeDef, it", "#stores String-based info such as name, device and type of the op.", "#Unique to every Operation instance.", "new_node_def", "=", "deepcopy", "(", "op", ".", "_node_def", ")", "#Change the name", "new_node_def", ".", "name", "=", "new_name", "#Copy the other inputs needed for initialization", "output_types", "=", "op", ".", "_output_types", "[", ":", "]", "input_types", "=", "op", ".", "_input_types", "[", ":", "]", "#Make a copy of the op_def too.", "#Its unique to every _type_ of Operation.", "op_def", "=", "deepcopy", "(", "op", ".", "_op_def", ")", "#Initialize a new Operation instance", "new_op", "=", "ops", ".", "Operation", "(", "new_node_def", ",", "to_graph", ",", "new_inputs", ",", "output_types", ",", "new_control_inputs", ",", "input_types", ",", "new_original_op", ",", "op_def", ")", "#Use Graph's hidden methods to add the op", "to_graph", ".", "_add_op", "(", "new_op", ")", "to_graph", ".", "_record_op_seen_by_control_dependencies", "(", "new_op", ")", "for", "device_function", "in", "reversed", "(", "to_graph", ".", "_device_function_stack", ")", ":", "new_op", ".", "_set_device", "(", "device_function", "(", "new_op", ")", ")", "return", "new_op", "else", ":", "raise", "TypeError", "(", "\"Could not copy instance: \"", "+", "str", "(", "org_instance", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/copy_graph/python/util/copy_elements.py#L101-L234
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimes.py
python
DatetimeArray.month_name
(self, locale=None)
return result
Return the month names of the DateTimeIndex with specified locale. .. versionadded:: 0.23.0 Parameters ---------- locale : str, optional Locale determining the language in which to return the month name. Default is English locale. Returns ------- Index Index of month names. Examples -------- >>> idx = pd.date_range(start='2018-01', freq='M', periods=3) >>> idx DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31'], dtype='datetime64[ns]', freq='M') >>> idx.month_name() Index(['January', 'February', 'March'], dtype='object')
Return the month names of the DateTimeIndex with specified locale.
[ "Return", "the", "month", "names", "of", "the", "DateTimeIndex", "with", "specified", "locale", "." ]
def month_name(self, locale=None): """ Return the month names of the DateTimeIndex with specified locale. .. versionadded:: 0.23.0 Parameters ---------- locale : str, optional Locale determining the language in which to return the month name. Default is English locale. Returns ------- Index Index of month names. Examples -------- >>> idx = pd.date_range(start='2018-01', freq='M', periods=3) >>> idx DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31'], dtype='datetime64[ns]', freq='M') >>> idx.month_name() Index(['January', 'February', 'March'], dtype='object') """ if self.tz is not None and not timezones.is_utc(self.tz): values = self._local_timestamps() else: values = self.asi8 result = fields.get_date_name_field(values, "month_name", locale=locale) result = self._maybe_mask_results(result, fill_value=None) return result
[ "def", "month_name", "(", "self", ",", "locale", "=", "None", ")", ":", "if", "self", ".", "tz", "is", "not", "None", "and", "not", "timezones", ".", "is_utc", "(", "self", ".", "tz", ")", ":", "values", "=", "self", ".", "_local_timestamps", "(", ")", "else", ":", "values", "=", "self", ".", "asi8", "result", "=", "fields", ".", "get_date_name_field", "(", "values", ",", "\"month_name\"", ",", "locale", "=", "locale", ")", "result", "=", "self", ".", "_maybe_mask_results", "(", "result", ",", "fill_value", "=", "None", ")", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimes.py#L1143-L1176
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/lite/tools/dataset/cropper/cropper_configure.py
python
extract_classname_source_node
(header_content)
return re.findall(r"(?<=class )[\w\d_]+(?=Node : )", header_content)
Use regex to find class names in header files of source nodes :param header_content: string containing header of a source node IR file :return: list of source node classes found
Use regex to find class names in header files of source nodes
[ "Use", "regex", "to", "find", "class", "names", "in", "header", "files", "of", "source", "nodes" ]
def extract_classname_source_node(header_content): """ Use regex to find class names in header files of source nodes :param header_content: string containing header of a source node IR file :return: list of source node classes found """ return re.findall(r"(?<=class )[\w\d_]+(?=Node : )", header_content)
[ "def", "extract_classname_source_node", "(", "header_content", ")", ":", "return", "re", ".", "findall", "(", "r\"(?<=class )[\\w\\d_]+(?=Node : )\"", ",", "header_content", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/lite/tools/dataset/cropper/cropper_configure.py#L105-L112
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/installers.py
python
InstallerContext.get_os_installer_keys
(self, os_key)
Get list of installer keys registered for the specified OS. These keys can be resolved by calling :meth:`InstallerContext.get_installer`. :param os_key: Key for OS :raises: :exc:`KeyError`: if no information for OS *os_key* is registered.
Get list of installer keys registered for the specified OS. These keys can be resolved by calling :meth:`InstallerContext.get_installer`. :param os_key: Key for OS :raises: :exc:`KeyError`: if no information for OS *os_key* is registered.
[ "Get", "list", "of", "installer", "keys", "registered", "for", "the", "specified", "OS", ".", "These", "keys", "can", "be", "resolved", "by", "calling", ":", "meth", ":", "InstallerContext", ".", "get_installer", ".", ":", "param", "os_key", ":", "Key", "for", "OS", ":", "raises", ":", ":", "exc", ":", "KeyError", ":", "if", "no", "information", "for", "OS", "*", "os_key", "*", "is", "registered", "." ]
def get_os_installer_keys(self, os_key): """ Get list of installer keys registered for the specified OS. These keys can be resolved by calling :meth:`InstallerContext.get_installer`. :param os_key: Key for OS :raises: :exc:`KeyError`: if no information for OS *os_key* is registered. """ if os_key in self.os_installers: return self.os_installers[os_key][:] else: raise KeyError(os_key)
[ "def", "get_os_installer_keys", "(", "self", ",", "os_key", ")", ":", "if", "os_key", "in", "self", ".", "os_installers", ":", "return", "self", ".", "os_installers", "[", "os_key", "]", "[", ":", "]", "else", ":", "raise", "KeyError", "(", "os_key", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/installers.py#L187-L199
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/tools/quantization/calibrate.py
python
CalibraterBase.select_tensors_to_calibrate
(self, model)
return tensors_to_calibrate, value_infos
select all quantization_candidates op type nodes' input/output tensors. returns: tensors (set): set of tensor name. value_infos (dict): tensor name to value info.
select all quantization_candidates op type nodes' input/output tensors. returns: tensors (set): set of tensor name. value_infos (dict): tensor name to value info.
[ "select", "all", "quantization_candidates", "op", "type", "nodes", "input", "/", "output", "tensors", ".", "returns", ":", "tensors", "(", "set", ")", ":", "set", "of", "tensor", "name", ".", "value_infos", "(", "dict", ")", ":", "tensor", "name", "to", "value", "info", "." ]
def select_tensors_to_calibrate(self, model): ''' select all quantization_candidates op type nodes' input/output tensors. returns: tensors (set): set of tensor name. value_infos (dict): tensor name to value info. ''' value_infos = {vi.name: vi for vi in model.graph.value_info} value_infos.update({ot.name: ot for ot in model.graph.output}) value_infos.update({it.name: it for it in model.graph.input}) initializer = set(init.name for init in model.graph.initializer) tensors_to_calibrate = set() tensor_type_to_calibrate = set([TensorProto.FLOAT, TensorProto.FLOAT16]) for node in model.graph.node: if len(self.op_types_to_calibrate) == 0 or node.op_type in self.op_types_to_calibrate: for tensor_name in itertools.chain(node.input, node.output): if tensor_name in value_infos.keys(): vi = value_infos[tensor_name] if vi.type.HasField('tensor_type') and ( vi.type.tensor_type.elem_type in tensor_type_to_calibrate) and ( tensor_name not in initializer): tensors_to_calibrate.add(tensor_name) return tensors_to_calibrate, value_infos
[ "def", "select_tensors_to_calibrate", "(", "self", ",", "model", ")", ":", "value_infos", "=", "{", "vi", ".", "name", ":", "vi", "for", "vi", "in", "model", ".", "graph", ".", "value_info", "}", "value_infos", ".", "update", "(", "{", "ot", ".", "name", ":", "ot", "for", "ot", "in", "model", ".", "graph", ".", "output", "}", ")", "value_infos", ".", "update", "(", "{", "it", ".", "name", ":", "it", "for", "it", "in", "model", ".", "graph", ".", "input", "}", ")", "initializer", "=", "set", "(", "init", ".", "name", "for", "init", "in", "model", ".", "graph", ".", "initializer", ")", "tensors_to_calibrate", "=", "set", "(", ")", "tensor_type_to_calibrate", "=", "set", "(", "[", "TensorProto", ".", "FLOAT", ",", "TensorProto", ".", "FLOAT16", "]", ")", "for", "node", "in", "model", ".", "graph", ".", "node", ":", "if", "len", "(", "self", ".", "op_types_to_calibrate", ")", "==", "0", "or", "node", ".", "op_type", "in", "self", ".", "op_types_to_calibrate", ":", "for", "tensor_name", "in", "itertools", ".", "chain", "(", "node", ".", "input", ",", "node", ".", "output", ")", ":", "if", "tensor_name", "in", "value_infos", ".", "keys", "(", ")", ":", "vi", "=", "value_infos", "[", "tensor_name", "]", "if", "vi", ".", "type", ".", "HasField", "(", "'tensor_type'", ")", "and", "(", "vi", ".", "type", ".", "tensor_type", ".", "elem_type", "in", "tensor_type_to_calibrate", ")", "and", "(", "tensor_name", "not", "in", "initializer", ")", ":", "tensors_to_calibrate", ".", "add", "(", "tensor_name", ")", "return", "tensors_to_calibrate", ",", "value_infos" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/quantization/calibrate.py#L84-L109
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py
python
Decimal.__divmod__
(self, other, context=None)
return quotient, remainder
Return (self // other, self % other)
Return (self // other, self % other)
[ "Return", "(", "self", "//", "other", "self", "%", "other", ")" ]
def __divmod__(self, other, context=None): """ Return (self // other, self % other) """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() ans = self._check_nans(other, context) if ans: return (ans, ans) sign = self._sign ^ other._sign if self._isinfinity(): if other._isinfinity(): ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') return ans, ans else: return (_SignedInfinity[sign], context._raise_error(InvalidOperation, 'INF % x')) if not other: if not self: ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') return ans, ans else: return (context._raise_error(DivisionByZero, 'x // 0', sign), context._raise_error(InvalidOperation, 'x % 0')) quotient, remainder = self._divide(other, context) remainder = remainder._fix(context) return quotient, remainder
[ "def", "__divmod__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "ans", "=", "self", ".", "_check_nans", "(", "other", ",", "context", ")", "if", "ans", ":", "return", "(", "ans", ",", "ans", ")", "sign", "=", "self", ".", "_sign", "^", "other", ".", "_sign", "if", "self", ".", "_isinfinity", "(", ")", ":", "if", "other", ".", "_isinfinity", "(", ")", ":", "ans", "=", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'divmod(INF, INF)'", ")", "return", "ans", ",", "ans", "else", ":", "return", "(", "_SignedInfinity", "[", "sign", "]", ",", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'INF % x'", ")", ")", "if", "not", "other", ":", "if", "not", "self", ":", "ans", "=", "context", ".", "_raise_error", "(", "DivisionUndefined", ",", "'divmod(0, 0)'", ")", "return", "ans", ",", "ans", "else", ":", "return", "(", "context", ".", "_raise_error", "(", "DivisionByZero", ",", "'x // 0'", ",", "sign", ")", ",", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'x % 0'", ")", ")", "quotient", ",", "remainder", "=", "self", ".", "_divide", "(", "other", ",", "context", ")", "remainder", "=", "remainder", ".", "_fix", "(", "context", ")", "return", "quotient", ",", "remainder" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L1423-L1457
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py
python
NeuralNetworkBuilder.add_max_broadcastable
(self, name, input_names, output_name)
return spec_layer
Add a max_broadcastable layer to the model that performs element-wise maximum operation with broadcast support. Refer to the **MaxBroadcastableLayerParams** message in specification (NeuralNetwork.proto) for more details. Parameters ---------- name: str The name of this layer. input_names: list of str The input blob names of this layer. output_name: str The output blob name of this layer.
Add a max_broadcastable layer to the model that performs element-wise maximum operation with broadcast support. Refer to the **MaxBroadcastableLayerParams** message in specification (NeuralNetwork.proto) for more details.
[ "Add", "a", "max_broadcastable", "layer", "to", "the", "model", "that", "performs", "element", "-", "wise", "maximum", "operation", "with", "broadcast", "support", ".", "Refer", "to", "the", "**", "MaxBroadcastableLayerParams", "**", "message", "in", "specification", "(", "NeuralNetwork", ".", "proto", ")", "for", "more", "details", "." ]
def add_max_broadcastable(self, name, input_names, output_name): """ Add a max_broadcastable layer to the model that performs element-wise maximum operation with broadcast support. Refer to the **MaxBroadcastableLayerParams** message in specification (NeuralNetwork.proto) for more details. Parameters ---------- name: str The name of this layer. input_names: list of str The input blob names of this layer. output_name: str The output blob name of this layer. """ spec_layer = self._add_generic_layer(name, input_names, [output_name]) spec_layer.maxBroadcastable.MergeFromString(b"") self._set_max_input_rank(input_names, output_name) return spec_layer
[ "def", "add_max_broadcastable", "(", "self", ",", "name", ",", "input_names", ",", "output_name", ")", ":", "spec_layer", "=", "self", ".", "_add_generic_layer", "(", "name", ",", "input_names", ",", "[", "output_name", "]", ")", "spec_layer", ".", "maxBroadcastable", ".", "MergeFromString", "(", "b\"\"", ")", "self", ".", "_set_max_input_rank", "(", "input_names", ",", "output_name", ")", "return", "spec_layer" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L5077-L5096
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py
python
AbstractFileSystem.ls
(self, path, detail=True, **kwargs)
List objects at path. This should include subdirectories and files at that location. The difference between a file and a directory must be clear when details are requested. The specific keys, or perhaps a FileInfo class, or similar, is TBD, but must be consistent across implementations. Must include: - full path to the entry (without protocol) - size of the entry, in bytes. If the value cannot be determined, will be ``None``. - type of entry, "file", "directory" or other Additional information may be present, aproriate to the file-system, e.g., generation, checksum, etc. May use refresh=True|False to allow use of self._ls_from_cache to check for a saved listing and avoid calling the backend. This would be common where listing may be expensive. Parameters ---------- path: str detail: bool if True, gives a list of dictionaries, where each is the same as the result of ``info(path)``. If False, gives a list of paths (str). kwargs: may have additional backend-specific options, such as version information Returns ------- List of strings if detail is False, or list of directory information dicts if detail is True.
List objects at path.
[ "List", "objects", "at", "path", "." ]
def ls(self, path, detail=True, **kwargs): """List objects at path. This should include subdirectories and files at that location. The difference between a file and a directory must be clear when details are requested. The specific keys, or perhaps a FileInfo class, or similar, is TBD, but must be consistent across implementations. Must include: - full path to the entry (without protocol) - size of the entry, in bytes. If the value cannot be determined, will be ``None``. - type of entry, "file", "directory" or other Additional information may be present, aproriate to the file-system, e.g., generation, checksum, etc. May use refresh=True|False to allow use of self._ls_from_cache to check for a saved listing and avoid calling the backend. This would be common where listing may be expensive. Parameters ---------- path: str detail: bool if True, gives a list of dictionaries, where each is the same as the result of ``info(path)``. If False, gives a list of paths (str). kwargs: may have additional backend-specific options, such as version information Returns ------- List of strings if detail is False, or list of directory information dicts if detail is True. """ raise NotImplementedError
[ "def", "ls", "(", "self", ",", "path", ",", "detail", "=", "True", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py#L258-L296
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
build_scripts/build_usd.py
python
GetXcodeDeveloperDirectory
()
return GetCommandOutput("xcode-select -p")
Returns the active developer directory as reported by 'xcode-select -p'. Returns None if none is set.
Returns the active developer directory as reported by 'xcode-select -p'. Returns None if none is set.
[ "Returns", "the", "active", "developer", "directory", "as", "reported", "by", "xcode", "-", "select", "-", "p", ".", "Returns", "None", "if", "none", "is", "set", "." ]
def GetXcodeDeveloperDirectory(): """Returns the active developer directory as reported by 'xcode-select -p'. Returns None if none is set.""" if not MacOS(): return None return GetCommandOutput("xcode-select -p")
[ "def", "GetXcodeDeveloperDirectory", "(", ")", ":", "if", "not", "MacOS", "(", ")", ":", "return", "None", "return", "GetCommandOutput", "(", "\"xcode-select -p\"", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/build_scripts/build_usd.py#L110-L116
dogecoin/dogecoin
31afd133119dd2e15862d46530cb99424cf564b0
contrib/seeds/makeseeds.py
python
filtermultiport
(ips)
return [value[0] for (key,value) in list(hist.items()) if len(value)==1]
Filter out hosts with more nodes per IP
Filter out hosts with more nodes per IP
[ "Filter", "out", "hosts", "with", "more", "nodes", "per", "IP" ]
def filtermultiport(ips): '''Filter out hosts with more nodes per IP''' hist = collections.defaultdict(list) for ip in ips: hist[ip['sortkey']].append(ip) return [value[0] for (key,value) in list(hist.items()) if len(value)==1]
[ "def", "filtermultiport", "(", "ips", ")", ":", "hist", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "ip", "in", "ips", ":", "hist", "[", "ip", "[", "'sortkey'", "]", "]", ".", "append", "(", "ip", ")", "return", "[", "value", "[", "0", "]", "for", "(", "key", ",", "value", ")", "in", "list", "(", "hist", ".", "items", "(", ")", ")", "if", "len", "(", "value", ")", "==", "1", "]" ]
https://github.com/dogecoin/dogecoin/blob/31afd133119dd2e15862d46530cb99424cf564b0/contrib/seeds/makeseeds.py#L102-L107
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_gui.py
python
GuiDomain.track
(self, objID, viewID=DEFAULT_VIEW)
track(string, string) -> None Start visually tracking the given vehicle or person on the given view.
track(string, string) -> None Start visually tracking the given vehicle or person on the given view.
[ "track", "(", "string", "string", ")", "-", ">", "None", "Start", "visually", "tracking", "the", "given", "vehicle", "or", "person", "on", "the", "given", "view", "." ]
def track(self, objID, viewID=DEFAULT_VIEW): """track(string, string) -> None Start visually tracking the given vehicle or person on the given view. """ self._setCmd(tc.VAR_TRACK_VEHICLE, viewID, "s", objID)
[ "def", "track", "(", "self", ",", "objID", ",", "viewID", "=", "DEFAULT_VIEW", ")", ":", "self", ".", "_setCmd", "(", "tc", ".", "VAR_TRACK_VEHICLE", ",", "viewID", ",", "\"s\"", ",", "objID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_gui.py#L126-L130
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/databases/grasping.py
python
GraspingModel.setPreshape
(self,grasp)
sets the preshape on the robot, assumes environment is locked
sets the preshape on the robot, assumes environment is locked
[ "sets", "the", "preshape", "on", "the", "robot", "assumes", "environment", "is", "locked" ]
def setPreshape(self,grasp): """sets the preshape on the robot, assumes environment is locked""" self.robot.SetDOFValues(grasp[self.graspindices['igrasppreshape']],self.manip.GetGripperIndices())
[ "def", "setPreshape", "(", "self", ",", "grasp", ")", ":", "self", ".", "robot", ".", "SetDOFValues", "(", "grasp", "[", "self", ".", "graspindices", "[", "'igrasppreshape'", "]", "]", ",", "self", ".", "manip", ".", "GetGripperIndices", "(", ")", ")" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/databases/grasping.py#L782-L784
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/wubi/backends/common/tasklist.py
python
Task._get_completed
(self)
return float(self.completed*self.weight) + sum(completed_subtasks)
get weighted sum of percent completed for this task and all the subtasks
get weighted sum of percent completed for this task and all the subtasks
[ "get", "weighted", "sum", "of", "percent", "completed", "for", "this", "task", "and", "all", "the", "subtasks" ]
def _get_completed(self): ''' get weighted sum of percent completed for this task and all the subtasks ''' completed_subtasks = [s._get_completed() for s in self.subtasks] return float(self.completed*self.weight) + sum(completed_subtasks)
[ "def", "_get_completed", "(", "self", ")", ":", "completed_subtasks", "=", "[", "s", ".", "_get_completed", "(", ")", "for", "s", "in", "self", ".", "subtasks", "]", "return", "float", "(", "self", ".", "completed", "*", "self", ".", "weight", ")", "+", "sum", "(", "completed_subtasks", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/wubi/backends/common/tasklist.py#L341-L346
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_osx_support.py
python
_find_appropriate_compiler
(_config_vars)
return _config_vars
Find appropriate C compiler for extension module builds
Find appropriate C compiler for extension module builds
[ "Find", "appropriate", "C", "compiler", "for", "extension", "module", "builds" ]
def _find_appropriate_compiler(_config_vars): """Find appropriate C compiler for extension module builds""" # Issue #13590: # The OSX location for the compiler varies between OSX # (or rather Xcode) releases. With older releases (up-to 10.5) # the compiler is in /usr/bin, with newer releases the compiler # can only be found inside Xcode.app if the "Command Line Tools" # are not installed. # # Furthermore, the compiler that can be used varies between # Xcode releases. Up to Xcode 4 it was possible to use 'gcc-4.2' # as the compiler, after that 'clang' should be used because # gcc-4.2 is either not present, or a copy of 'llvm-gcc' that # miscompiles Python. # skip checks if the compiler was overridden with a CC env variable if 'CC' in os.environ: return _config_vars # The CC config var might contain additional arguments. # Ignore them while searching. cc = oldcc = _config_vars['CC'].split()[0] if not _find_executable(cc): # Compiler is not found on the shell search PATH. # Now search for clang, first on PATH (if the Command LIne # Tools have been installed in / or if the user has provided # another location via CC). If not found, try using xcrun # to find an uninstalled clang (within a selected Xcode). # NOTE: Cannot use subprocess here because of bootstrap # issues when building Python itself (and os.popen is # implemented on top of subprocess and is therefore not # usable as well) cc = _find_build_tool('clang') elif os.path.basename(cc).startswith('gcc'): # Compiler is GCC, check if it is LLVM-GCC data = _read_output("'%s' --version" % (cc.replace("'", "'\"'\"'"),)) if data and 'llvm-gcc' in data: # Found LLVM-GCC, fall back to clang cc = _find_build_tool('clang') if not cc: raise SystemError( "Cannot locate working compiler") if cc != oldcc: # Found a replacement compiler. # Modify config vars using new compiler, if not already explicitly # overridden by an env variable, preserving additional arguments. for cv in _COMPILER_CONFIG_VARS: if cv in _config_vars and cv not in os.environ: cv_split = _config_vars[cv].split() cv_split[0] = cc if cv != 'CXX' else cc + '++' _save_modified_value(_config_vars, cv, ' '.join(cv_split)) return _config_vars
[ "def", "_find_appropriate_compiler", "(", "_config_vars", ")", ":", "# Issue #13590:", "# The OSX location for the compiler varies between OSX", "# (or rather Xcode) releases. With older releases (up-to 10.5)", "# the compiler is in /usr/bin, with newer releases the compiler", "# can only be found inside Xcode.app if the \"Command Line Tools\"", "# are not installed.", "#", "# Furthermore, the compiler that can be used varies between", "# Xcode releases. Up to Xcode 4 it was possible to use 'gcc-4.2'", "# as the compiler, after that 'clang' should be used because", "# gcc-4.2 is either not present, or a copy of 'llvm-gcc' that", "# miscompiles Python.", "# skip checks if the compiler was overridden with a CC env variable", "if", "'CC'", "in", "os", ".", "environ", ":", "return", "_config_vars", "# The CC config var might contain additional arguments.", "# Ignore them while searching.", "cc", "=", "oldcc", "=", "_config_vars", "[", "'CC'", "]", ".", "split", "(", ")", "[", "0", "]", "if", "not", "_find_executable", "(", "cc", ")", ":", "# Compiler is not found on the shell search PATH.", "# Now search for clang, first on PATH (if the Command LIne", "# Tools have been installed in / or if the user has provided", "# another location via CC). If not found, try using xcrun", "# to find an uninstalled clang (within a selected Xcode).", "# NOTE: Cannot use subprocess here because of bootstrap", "# issues when building Python itself (and os.popen is", "# implemented on top of subprocess and is therefore not", "# usable as well)", "cc", "=", "_find_build_tool", "(", "'clang'", ")", "elif", "os", ".", "path", ".", "basename", "(", "cc", ")", ".", "startswith", "(", "'gcc'", ")", ":", "# Compiler is GCC, check if it is LLVM-GCC", "data", "=", "_read_output", "(", "\"'%s' --version\"", "%", "(", "cc", ".", "replace", "(", "\"'\"", ",", "\"'\\\"'\\\"'\"", ")", ",", ")", ")", "if", "data", "and", "'llvm-gcc'", "in", "data", ":", "# Found LLVM-GCC, fall back to clang", "cc", "=", "_find_build_tool", "(", "'clang'", ")", "if", "not", "cc", ":", "raise", "SystemError", "(", "\"Cannot locate working compiler\"", ")", "if", "cc", "!=", "oldcc", ":", "# Found a replacement compiler.", "# Modify config vars using new compiler, if not already explicitly", "# overridden by an env variable, preserving additional arguments.", "for", "cv", "in", "_COMPILER_CONFIG_VARS", ":", "if", "cv", "in", "_config_vars", "and", "cv", "not", "in", "os", ".", "environ", ":", "cv_split", "=", "_config_vars", "[", "cv", "]", ".", "split", "(", ")", "cv_split", "[", "0", "]", "=", "cc", "if", "cv", "!=", "'CXX'", "else", "cc", "+", "'++'", "_save_modified_value", "(", "_config_vars", ",", "cv", ",", "' '", ".", "join", "(", "cv_split", ")", ")", "return", "_config_vars" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_osx_support.py#L198-L257
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/servermanager.py
python
FieldDataInformation.iteritems
(self)
return FieldDataInformationIterator(self, True)
Implementation of the PY2 dictionary API
Implementation of the PY2 dictionary API
[ "Implementation", "of", "the", "PY2", "dictionary", "API" ]
def iteritems(self): """Implementation of the PY2 dictionary API""" return FieldDataInformationIterator(self, True)
[ "def", "iteritems", "(", "self", ")", ":", "return", "FieldDataInformationIterator", "(", "self", ",", "True", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/servermanager.py#L1682-L1684
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/client/session.py
python
_DictFetchMapper.__init__
(self, fetches)
Creates a _DictFetchMapper. Args: fetches: Dict of fetches.
Creates a _DictFetchMapper.
[ "Creates", "a", "_DictFetchMapper", "." ]
def __init__(self, fetches): """Creates a _DictFetchMapper. Args: fetches: Dict of fetches. """ self._fetch_type = type(fetches) if isinstance(fetches, collections.defaultdict): self._type_ctor = functools.partial(collections.defaultdict, fetches.default_factory) else: self._type_ctor = self._fetch_type self._keys = fetches.keys() self._mappers = [ _FetchMapper.for_fetch(fetch) for fetch in fetches.values() ] self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
[ "def", "__init__", "(", "self", ",", "fetches", ")", ":", "self", ".", "_fetch_type", "=", "type", "(", "fetches", ")", "if", "isinstance", "(", "fetches", ",", "collections", ".", "defaultdict", ")", ":", "self", ".", "_type_ctor", "=", "functools", ".", "partial", "(", "collections", ".", "defaultdict", ",", "fetches", ".", "default_factory", ")", "else", ":", "self", ".", "_type_ctor", "=", "self", ".", "_fetch_type", "self", ".", "_keys", "=", "fetches", ".", "keys", "(", ")", "self", ".", "_mappers", "=", "[", "_FetchMapper", ".", "for_fetch", "(", "fetch", ")", "for", "fetch", "in", "fetches", ".", "values", "(", ")", "]", "self", ".", "_unique_fetches", ",", "self", ".", "_value_indices", "=", "_uniquify_fetches", "(", "self", ".", "_mappers", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/client/session.py#L402-L419
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/isis_reduction_steps.py
python
ConvertToQISIS.execute
(self, reducer, workspace)
Calculate the normalization workspaces and then call the chosen Q conversion algorithm.
Calculate the normalization workspaces and then call the chosen Q conversion algorithm.
[ "Calculate", "the", "normalization", "workspaces", "and", "then", "call", "the", "chosen", "Q", "conversion", "algorithm", "." ]
def execute(self, reducer, workspace): """ Calculate the normalization workspaces and then call the chosen Q conversion algorithm. """ wavepixeladj = "" if reducer.wide_angle_correction and reducer.transmission_calculator.output_wksp: # calculate the transmission wide angle correction _issueWarning("sans solid angle correction execution") SANSWideAngleCorrection(SampleData=workspace, TransmissionData=reducer.transmission_calculator.output_wksp, OutputWorkspace='transmissionWorkspace') wavepixeladj = 'transmissionWorkspace' # create normalization workspaces if self._norms: # the empty list at the end appears to be needed (the system test SANS2DWaveloops) is this a bug in Python? wave_adj, pixel_adj = self._norms.calculate(reducer, []) else: raise RuntimeError('Normalization workspaces must be created by CalculateNorm() and passed to this step') # Create the QResolution workspace, but only if it A) is requested by the user and does not exist # B) is requested by the user, exists, but does not # have the correct binning --> This is currently not implemented, # but should be addressed in an optimization step qResolution = self._get_q_resolution_workspace(det_bank_workspace=workspace) # Debug output if DEBUG: sanslog.warning("###############################################") sanslog.warning("File : %s" % str(self._q_resolution_moderator_file_name)) sanslog.warning("A1 : %s" % str(self._q_resolution_a1)) sanslog.warning("A2 : %s" % str(self._q_resolution_a2)) sanslog.warning("H1 : %s" % str(self._q_resolution_h1)) sanslog.warning("H2 : %s" % str(self._q_resolution_h1)) sanslog.warning("W1 : %s" % str(self._q_resolution_w1)) sanslog.warning("W2 : %s" % str(self._q_resolution_w2)) sanslog.warning("LCol: %s" % str(self._q_resolution_collimation_length)) sanslog.warning("DR : %s" % str(self._q_resolution_delta_r)) sanslog.warning("Exists: %s" % str(qResolution is not None)) try: if self._Q_alg == 'Q1D': Q1D(DetBankWorkspace=workspace, OutputWorkspace=workspace, OutputBinning=self.binning, WavelengthAdj=wave_adj, PixelAdj=pixel_adj, AccountForGravity=self._use_gravity, RadiusCut=self.r_cut * 1000.0, WaveCut=self.w_cut, OutputParts=self.outputParts, WavePixelAdj=wavepixeladj, ExtraLength=self._grav_extra_length, QResolution=qResolution) elif self._Q_alg == 'Qxy': Qxy(InputWorkspace=workspace, OutputWorkspace=workspace, MaxQxy=reducer.QXY2, DeltaQ=reducer.DQXY, WavelengthAdj=wave_adj, PixelAdj=pixel_adj, AccountForGravity=self._use_gravity, RadiusCut=self.r_cut * 1000.0, WaveCut=self.w_cut, OutputParts=self.outputParts, ExtraLength=self._grav_extra_length) ReplaceSpecialValues(InputWorkspace=workspace, OutputWorkspace=workspace, NaNValue="0", InfinityValue="0") # We need to correct for special values in the partial outputs. The # counts seem to have NANS. if self.outputParts: sum_of_counts = workspace + "_sumOfCounts" sum_of_norm = workspace + "_sumOfNormFactors" ReplaceSpecialValues(InputWorkspace=sum_of_counts, OutputWorkspace=sum_of_counts, NaNValue="0", InfinityValue="0") ReplaceSpecialValues(InputWorkspace=sum_of_norm, OutputWorkspace=sum_of_norm, NaNValue="0", InfinityValue="0") else: raise NotImplementedError('The type of Q reduction has not been set, e.g. 1D or 2D') except: # when we are all up to Python 2.5 replace the duplicated code below with one finally: reducer.deleteWorkspaces([wave_adj, pixel_adj, wavepixeladj]) raise reducer.deleteWorkspaces([wave_adj, pixel_adj, wavepixeladj])
[ "def", "execute", "(", "self", ",", "reducer", ",", "workspace", ")", ":", "wavepixeladj", "=", "\"\"", "if", "reducer", ".", "wide_angle_correction", "and", "reducer", ".", "transmission_calculator", ".", "output_wksp", ":", "# calculate the transmission wide angle correction", "_issueWarning", "(", "\"sans solid angle correction execution\"", ")", "SANSWideAngleCorrection", "(", "SampleData", "=", "workspace", ",", "TransmissionData", "=", "reducer", ".", "transmission_calculator", ".", "output_wksp", ",", "OutputWorkspace", "=", "'transmissionWorkspace'", ")", "wavepixeladj", "=", "'transmissionWorkspace'", "# create normalization workspaces", "if", "self", ".", "_norms", ":", "# the empty list at the end appears to be needed (the system test SANS2DWaveloops) is this a bug in Python?", "wave_adj", ",", "pixel_adj", "=", "self", ".", "_norms", ".", "calculate", "(", "reducer", ",", "[", "]", ")", "else", ":", "raise", "RuntimeError", "(", "'Normalization workspaces must be created by CalculateNorm() and passed to this step'", ")", "# Create the QResolution workspace, but only if it A) is requested by the user and does not exist", "# B) is requested by the user, exists, but does not", "# have the correct binning --> This is currently not implemented,", "# but should be addressed in an optimization step", "qResolution", "=", "self", ".", "_get_q_resolution_workspace", "(", "det_bank_workspace", "=", "workspace", ")", "# Debug output", "if", "DEBUG", ":", "sanslog", ".", "warning", "(", "\"###############################################\"", ")", "sanslog", ".", "warning", "(", "\"File : %s\"", "%", "str", "(", "self", ".", "_q_resolution_moderator_file_name", ")", ")", "sanslog", ".", "warning", "(", "\"A1 : %s\"", "%", "str", "(", "self", ".", "_q_resolution_a1", ")", ")", "sanslog", ".", "warning", "(", "\"A2 : %s\"", "%", "str", "(", "self", ".", "_q_resolution_a2", ")", ")", "sanslog", ".", "warning", "(", "\"H1 : %s\"", "%", "str", "(", "self", ".", "_q_resolution_h1", ")", ")", "sanslog", ".", "warning", "(", "\"H2 : %s\"", "%", "str", "(", "self", ".", "_q_resolution_h1", ")", ")", "sanslog", ".", "warning", "(", "\"W1 : %s\"", "%", "str", "(", "self", ".", "_q_resolution_w1", ")", ")", "sanslog", ".", "warning", "(", "\"W2 : %s\"", "%", "str", "(", "self", ".", "_q_resolution_w2", ")", ")", "sanslog", ".", "warning", "(", "\"LCol: %s\"", "%", "str", "(", "self", ".", "_q_resolution_collimation_length", ")", ")", "sanslog", ".", "warning", "(", "\"DR : %s\"", "%", "str", "(", "self", ".", "_q_resolution_delta_r", ")", ")", "sanslog", ".", "warning", "(", "\"Exists: %s\"", "%", "str", "(", "qResolution", "is", "not", "None", ")", ")", "try", ":", "if", "self", ".", "_Q_alg", "==", "'Q1D'", ":", "Q1D", "(", "DetBankWorkspace", "=", "workspace", ",", "OutputWorkspace", "=", "workspace", ",", "OutputBinning", "=", "self", ".", "binning", ",", "WavelengthAdj", "=", "wave_adj", ",", "PixelAdj", "=", "pixel_adj", ",", "AccountForGravity", "=", "self", ".", "_use_gravity", ",", "RadiusCut", "=", "self", ".", "r_cut", "*", "1000.0", ",", "WaveCut", "=", "self", ".", "w_cut", ",", "OutputParts", "=", "self", ".", "outputParts", ",", "WavePixelAdj", "=", "wavepixeladj", ",", "ExtraLength", "=", "self", ".", "_grav_extra_length", ",", "QResolution", "=", "qResolution", ")", "elif", "self", ".", "_Q_alg", "==", "'Qxy'", ":", "Qxy", "(", "InputWorkspace", "=", "workspace", ",", "OutputWorkspace", "=", "workspace", ",", "MaxQxy", "=", "reducer", ".", "QXY2", ",", "DeltaQ", "=", "reducer", ".", "DQXY", ",", "WavelengthAdj", "=", "wave_adj", ",", "PixelAdj", "=", "pixel_adj", ",", "AccountForGravity", "=", "self", ".", "_use_gravity", ",", "RadiusCut", "=", "self", ".", "r_cut", "*", "1000.0", ",", "WaveCut", "=", "self", ".", "w_cut", ",", "OutputParts", "=", "self", ".", "outputParts", ",", "ExtraLength", "=", "self", ".", "_grav_extra_length", ")", "ReplaceSpecialValues", "(", "InputWorkspace", "=", "workspace", ",", "OutputWorkspace", "=", "workspace", ",", "NaNValue", "=", "\"0\"", ",", "InfinityValue", "=", "\"0\"", ")", "# We need to correct for special values in the partial outputs. The", "# counts seem to have NANS.", "if", "self", ".", "outputParts", ":", "sum_of_counts", "=", "workspace", "+", "\"_sumOfCounts\"", "sum_of_norm", "=", "workspace", "+", "\"_sumOfNormFactors\"", "ReplaceSpecialValues", "(", "InputWorkspace", "=", "sum_of_counts", ",", "OutputWorkspace", "=", "sum_of_counts", ",", "NaNValue", "=", "\"0\"", ",", "InfinityValue", "=", "\"0\"", ")", "ReplaceSpecialValues", "(", "InputWorkspace", "=", "sum_of_norm", ",", "OutputWorkspace", "=", "sum_of_norm", ",", "NaNValue", "=", "\"0\"", ",", "InfinityValue", "=", "\"0\"", ")", "else", ":", "raise", "NotImplementedError", "(", "'The type of Q reduction has not been set, e.g. 1D or 2D'", ")", "except", ":", "# when we are all up to Python 2.5 replace the duplicated code below with one finally:", "reducer", ".", "deleteWorkspaces", "(", "[", "wave_adj", ",", "pixel_adj", ",", "wavepixeladj", "]", ")", "raise", "reducer", ".", "deleteWorkspaces", "(", "[", "wave_adj", ",", "pixel_adj", ",", "wavepixeladj", "]", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_reduction_steps.py#L2721-L2807
smartdevicelink/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py
python
CodeGenerator._gen_struct_impl
(self, struct, namespace, class_name)
return self._struct_impl_template.substitute( namespace=namespace, class_name=class_name, struct_name=struct.name, code=self._indent_code( self._struct_impl_code_tempate.substitute( struct_name=struct.name, schema_loc_decl=self._gen_schema_loc_decls( struct.members.values(), processed_enums), schema_items_decl=self._gen_schema_items_decls( struct.members.values()), schema_item_fill=self._gen_schema_items_fill( struct.members.values(), struct.since, struct.until, struct.deprecated, struct.removed)), 1))
Generate struct implementation for source file. Generates implementation code of method that provide schema item for struct. This code should be used in the source file. Keyword arguments: struct -- struct to generate method for. namespace -- name of destination namespace. class_name -- name of the parent class. Returns: String with structs implementation source code.
Generate struct implementation for source file.
[ "Generate", "struct", "implementation", "for", "source", "file", "." ]
def _gen_struct_impl(self, struct, namespace, class_name): """Generate struct implementation for source file. Generates implementation code of method that provide schema item for struct. This code should be used in the source file. Keyword arguments: struct -- struct to generate method for. namespace -- name of destination namespace. class_name -- name of the parent class. Returns: String with structs implementation source code. """ processed_enums = [] return self._struct_impl_template.substitute( namespace=namespace, class_name=class_name, struct_name=struct.name, code=self._indent_code( self._struct_impl_code_tempate.substitute( struct_name=struct.name, schema_loc_decl=self._gen_schema_loc_decls( struct.members.values(), processed_enums), schema_items_decl=self._gen_schema_items_decls( struct.members.values()), schema_item_fill=self._gen_schema_items_fill( struct.members.values(), struct.since, struct.until, struct.deprecated, struct.removed)), 1))
[ "def", "_gen_struct_impl", "(", "self", ",", "struct", ",", "namespace", ",", "class_name", ")", ":", "processed_enums", "=", "[", "]", "return", "self", ".", "_struct_impl_template", ".", "substitute", "(", "namespace", "=", "namespace", ",", "class_name", "=", "class_name", ",", "struct_name", "=", "struct", ".", "name", ",", "code", "=", "self", ".", "_indent_code", "(", "self", ".", "_struct_impl_code_tempate", ".", "substitute", "(", "struct_name", "=", "struct", ".", "name", ",", "schema_loc_decl", "=", "self", ".", "_gen_schema_loc_decls", "(", "struct", ".", "members", ".", "values", "(", ")", ",", "processed_enums", ")", ",", "schema_items_decl", "=", "self", ".", "_gen_schema_items_decls", "(", "struct", ".", "members", ".", "values", "(", ")", ")", ",", "schema_item_fill", "=", "self", ".", "_gen_schema_items_fill", "(", "struct", ".", "members", ".", "values", "(", ")", ",", "struct", ".", "since", ",", "struct", ".", "until", ",", "struct", ".", "deprecated", ",", "struct", ".", "removed", ")", ")", ",", "1", ")", ")" ]
https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py#L545-L574
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
LeetCode/python3/775.py
python
Solution.isIdealPermutation
(self, A)
return True
:type A: List[int] :rtype: bool
:type A: List[int] :rtype: bool
[ ":", "type", "A", ":", "List", "[", "int", "]", ":", "rtype", ":", "bool" ]
def isIdealPermutation(self, A): """ :type A: List[int] :rtype: bool """ size, m = len(A), 0 for i in range(size - 2): m = max(m, A[i]) if m > A[i + 2]: return False return True
[ "def", "isIdealPermutation", "(", "self", ",", "A", ")", ":", "size", ",", "m", "=", "len", "(", "A", ")", ",", "0", "for", "i", "in", "range", "(", "size", "-", "2", ")", ":", "m", "=", "max", "(", "m", ",", "A", "[", "i", "]", ")", "if", "m", ">", "A", "[", "i", "+", "2", "]", ":", "return", "False", "return", "True" ]
https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python3/775.py#L2-L12
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/vesuvio/profiles.py
python
GaussianMassProfile.create_fit_function_str
(self, param_vals=None, param_prefix="")
return fitting_str + ";"
Creates a string used by the Fit algorithm for this profile :param param_vals: A table of values for the parameters that override those set on the object already. Default=None :param param_prefix: A string prefix for the parameter as seen by the Mantid Fit algorithm
Creates a string used by the Fit algorithm for this profile
[ "Creates", "a", "string", "used", "by", "the", "Fit", "algorithm", "for", "this", "profile" ]
def create_fit_function_str(self, param_vals=None, param_prefix=""): """Creates a string used by the Fit algorithm for this profile :param param_vals: A table of values for the parameters that override those set on the object already. Default=None :param param_prefix: A string prefix for the parameter as seen by the Mantid Fit algorithm """ vals_provided = (param_vals is not None) if vals_provided: def_width = param_vals[param_prefix + "Width"] else: def_width = self.width if isinstance(def_width, list): def_width = def_width[1] fitting_str = "name={0},Mass={1:f},Width={2:f}".format(self.cfunction, self.mass, def_width) if vals_provided: param_name = "Intensity" intensity_str = "{0}={1:f}".format(param_name, param_vals[param_prefix + param_name]) fitting_str += "," + intensity_str elif self.intensity is not None: fitting_str += ",Intensity={0:f}".format(self.intensity) logger.debug("Gaussian profile fit function string: {0}".format(fitting_str)) return fitting_str + ";"
[ "def", "create_fit_function_str", "(", "self", ",", "param_vals", "=", "None", ",", "param_prefix", "=", "\"\"", ")", ":", "vals_provided", "=", "(", "param_vals", "is", "not", "None", ")", "if", "vals_provided", ":", "def_width", "=", "param_vals", "[", "param_prefix", "+", "\"Width\"", "]", "else", ":", "def_width", "=", "self", ".", "width", "if", "isinstance", "(", "def_width", ",", "list", ")", ":", "def_width", "=", "def_width", "[", "1", "]", "fitting_str", "=", "\"name={0},Mass={1:f},Width={2:f}\"", ".", "format", "(", "self", ".", "cfunction", ",", "self", ".", "mass", ",", "def_width", ")", "if", "vals_provided", ":", "param_name", "=", "\"Intensity\"", "intensity_str", "=", "\"{0}={1:f}\"", ".", "format", "(", "param_name", ",", "param_vals", "[", "param_prefix", "+", "param_name", "]", ")", "fitting_str", "+=", "\",\"", "+", "intensity_str", "elif", "self", ".", "intensity", "is", "not", "None", ":", "fitting_str", "+=", "\",Intensity={0:f}\"", ".", "format", "(", "self", ".", "intensity", ")", "logger", ".", "debug", "(", "\"Gaussian profile fit function string: {0}\"", ".", "format", "(", "fitting_str", ")", ")", "return", "fitting_str", "+", "\";\"" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/vesuvio/profiles.py#L145-L170
tkn-tub/ns3-gym
19bfe0a583e641142609939a090a09dfc63a095f
src/visualizer/visualizer/hud.py
python
Axes.__init__
(self, viz)
! Initializer function @param self: this object @param viz: visualization object @return none
! Initializer function
[ "!", "Initializer", "function" ]
def __init__(self, viz): """! Initializer function @param self: this object @param viz: visualization object @return none """ self.viz = viz self.color = 0x8080C0FF self.hlines = GooCanvas.CanvasPath(parent=viz.canvas.get_root_item(), stroke_color_rgba=self.color) self.hlines.lower(None) self.vlines = GooCanvas.CanvasPath(parent=viz.canvas.get_root_item(), stroke_color_rgba=self.color) self.vlines.lower(None) self.labels = [] hadj = self.viz.get_hadjustment() vadj = self.viz.get_vadjustment() def update(adj): if self.visible: self.update_view() hadj.connect("value-changed", update) vadj.connect("value-changed", update) hadj.connect("changed", update) vadj.connect("changed", update) self.visible = True self.update_view()
[ "def", "__init__", "(", "self", ",", "viz", ")", ":", "self", ".", "viz", "=", "viz", "self", ".", "color", "=", "0x8080C0FF", "self", ".", "hlines", "=", "GooCanvas", ".", "CanvasPath", "(", "parent", "=", "viz", ".", "canvas", ".", "get_root_item", "(", ")", ",", "stroke_color_rgba", "=", "self", ".", "color", ")", "self", ".", "hlines", ".", "lower", "(", "None", ")", "self", ".", "vlines", "=", "GooCanvas", ".", "CanvasPath", "(", "parent", "=", "viz", ".", "canvas", ".", "get_root_item", "(", ")", ",", "stroke_color_rgba", "=", "self", ".", "color", ")", "self", ".", "vlines", ".", "lower", "(", "None", ")", "self", ".", "labels", "=", "[", "]", "hadj", "=", "self", ".", "viz", ".", "get_hadjustment", "(", ")", "vadj", "=", "self", ".", "viz", ".", "get_vadjustment", "(", ")", "def", "update", "(", "adj", ")", ":", "if", "self", ".", "visible", ":", "self", ".", "update_view", "(", ")", "hadj", ".", "connect", "(", "\"value-changed\"", ",", "update", ")", "vadj", ".", "connect", "(", "\"value-changed\"", ",", "update", ")", "hadj", ".", "connect", "(", "\"changed\"", ",", "update", ")", "vadj", ".", "connect", "(", "\"changed\"", ",", "update", ")", "self", ".", "visible", "=", "True", "self", ".", "update_view", "(", ")" ]
https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/src/visualizer/visualizer/hud.py#L22-L47
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/errors_impl.py
python
UnimplementedError.__init__
(self, node_def, op, message)
Creates an `UnimplementedError`.
Creates an `UnimplementedError`.
[ "Creates", "an", "UnimplementedError", "." ]
def __init__(self, node_def, op, message): """Creates an `UnimplementedError`.""" super(UnimplementedError, self).__init__(node_def, op, message, UNIMPLEMENTED)
[ "def", "__init__", "(", "self", ",", "node_def", ",", "op", ",", "message", ")", ":", "super", "(", "UnimplementedError", ",", "self", ")", ".", "__init__", "(", "node_def", ",", "op", ",", "message", ",", "UNIMPLEMENTED", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/errors_impl.py#L368-L371
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HtmlCell.GetWidth
(*args, **kwargs)
return _html.HtmlCell_GetWidth(*args, **kwargs)
GetWidth(self) -> int
GetWidth(self) -> int
[ "GetWidth", "(", "self", ")", "-", ">", "int" ]
def GetWidth(*args, **kwargs): """GetWidth(self) -> int""" return _html.HtmlCell_GetWidth(*args, **kwargs)
[ "def", "GetWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlCell_GetWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L618-L620
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
tools/extra/parse_log.py
python
fix_initial_nan_learning_rate
(dict_list)
Correct initial value of learning rate Learning rate is normally not printed until after the initial test and training step, which means the initial testing and training rows have LearningRate = NaN. Fix this by copying over the LearningRate from the second row, if it exists.
Correct initial value of learning rate
[ "Correct", "initial", "value", "of", "learning", "rate" ]
def fix_initial_nan_learning_rate(dict_list): """Correct initial value of learning rate Learning rate is normally not printed until after the initial test and training step, which means the initial testing and training rows have LearningRate = NaN. Fix this by copying over the LearningRate from the second row, if it exists. """ if len(dict_list) > 1: dict_list[0]['LearningRate'] = dict_list[1]['LearningRate']
[ "def", "fix_initial_nan_learning_rate", "(", "dict_list", ")", ":", "if", "len", "(", "dict_list", ")", ">", "1", ":", "dict_list", "[", "0", "]", "[", "'LearningRate'", "]", "=", "dict_list", "[", "1", "]", "[", "'LearningRate'", "]" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/tools/extra/parse_log.py#L128-L138
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/function_cache.py
python
FunctionCache.lookup
(self, key: FunctionCacheKey, use_function_subtyping: bool)
return None
Looks up a concrete function based on the key.
Looks up a concrete function based on the key.
[ "Looks", "up", "a", "concrete", "function", "based", "on", "the", "key", "." ]
def lookup(self, key: FunctionCacheKey, use_function_subtyping: bool): """Looks up a concrete function based on the key.""" if not use_function_subtyping: return self._primary.get(key, None) dispatch_key = self._dispatch_table.dispatch(key) if dispatch_key is not None: return self._primary[dispatch_key] return None
[ "def", "lookup", "(", "self", ",", "key", ":", "FunctionCacheKey", ",", "use_function_subtyping", ":", "bool", ")", ":", "if", "not", "use_function_subtyping", ":", "return", "self", ".", "_primary", ".", "get", "(", "key", ",", "None", ")", "dispatch_key", "=", "self", ".", "_dispatch_table", ".", "dispatch", "(", "key", ")", "if", "dispatch_key", "is", "not", "None", ":", "return", "self", ".", "_primary", "[", "dispatch_key", "]", "return", "None" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/function_cache.py#L146-L155
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py
python
AbstractWriter.includes1Write
(self, obj)
Defined to generate includes within a file. Usually used for the base classes but also for Port types @param args: the instance of the concrete element to operation on.
Defined to generate includes within a file. Usually used for the base classes but also for Port types
[ "Defined", "to", "generate", "includes", "within", "a", "file", ".", "Usually", "used", "for", "the", "base", "classes", "but", "also", "for", "Port", "types" ]
def includes1Write(self, obj): """ Defined to generate includes within a file. Usually used for the base classes but also for Port types @param args: the instance of the concrete element to operation on. """ raise Exception( "# AbstractWriter.includesWrite1() - Implementation Error: you must supply your own concrete implementation." )
[ "def", "includes1Write", "(", "self", ",", "obj", ")", ":", "raise", "Exception", "(", "\"# AbstractWriter.includesWrite1() - Implementation Error: you must supply your own concrete implementation.\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py#L84-L92
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/copy_helper.py
python
FixWindowsNaming
(src_url, dst_url)
return dst_url
Translates Windows pathnames to cloud pathnames. Rewrites the destination URL built by ConstructDstUrl(). Args: src_url: Source StorageUrl to be copied. dst_url: The destination StorageUrl built by ConstructDstUrl(). Returns: StorageUrl to use for copy.
Translates Windows pathnames to cloud pathnames.
[ "Translates", "Windows", "pathnames", "to", "cloud", "pathnames", "." ]
def FixWindowsNaming(src_url, dst_url): """Translates Windows pathnames to cloud pathnames. Rewrites the destination URL built by ConstructDstUrl(). Args: src_url: Source StorageUrl to be copied. dst_url: The destination StorageUrl built by ConstructDstUrl(). Returns: StorageUrl to use for copy. """ if (src_url.IsFileUrl() and src_url.delim == '\\' and dst_url.IsCloudUrl()): trans_url_str = re.sub(r'\\', '/', dst_url.url_string) dst_url = StorageUrlFromString(trans_url_str) return dst_url
[ "def", "FixWindowsNaming", "(", "src_url", ",", "dst_url", ")", ":", "if", "(", "src_url", ".", "IsFileUrl", "(", ")", "and", "src_url", ".", "delim", "==", "'\\\\'", "and", "dst_url", ".", "IsCloudUrl", "(", ")", ")", ":", "trans_url_str", "=", "re", ".", "sub", "(", "r'\\\\'", ",", "'/'", ",", "dst_url", ".", "url_string", ")", "dst_url", "=", "StorageUrlFromString", "(", "trans_url_str", ")", "return", "dst_url" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/copy_helper.py#L1176-L1192
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
scripts/cpp_lint.py
python
ReplaceAll
(pattern, rep, s)
return _regexp_compile_cache[pattern].sub(rep, s)
Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements)
Replaces instances of pattern in a string with a replacement.
[ "Replaces", "instances", "of", "pattern", "in", "a", "string", "with", "a", "replacement", "." ]
def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s)
[ "def", "ReplaceAll", "(", "pattern", ",", "rep", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "sub", "(", "rep", ",", "s", ")" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L529-L544
p4lang/p4c
3272e79369f20813cc1a555a5eb26f44432f84a4
tools/cpplint.py
python
_NamespaceInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Check end of namespace comments.
Check end of namespace comments.
[ "Check", "end", "of", "namespace", "comments", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"')
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "# Check how many lines is enclosed in this namespace. Don't issue", "# warning for missing namespace comments if there aren't enough", "# lines. However, do apply checks if there is already an end of", "# namespace comment and it's incorrect.", "#", "# TODO(unknown): We always want to check end of namespace comments", "# if a namespace is large, but sometimes we also want to apply the", "# check if a short namespace contained nontrivial things (something", "# other than forward declarations). There is currently no logic on", "# deciding what these nontrivial things are, so this check is", "# triggered by namespace size only, which works most of the time.", "if", "(", "linenum", "-", "self", ".", "starting_linenum", "<", "10", "and", "not", "Match", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\b'", ",", "line", ")", ")", ":", "return", "# Look for matching comment at end of namespace.", "#", "# Note that we accept C style \"/* */\" comments for terminating", "# namespaces, so that code that terminate namespaces inside", "# preprocessor macros can be cpplint clean.", "#", "# We also accept stuff like \"// end of namespace <name>.\" with the", "# period at the end.", "#", "# Besides these, we don't accept anything else, otherwise we might", "# get false negatives when existing comment is a substring of the", "# expected namespace.", "if", "self", ".", "name", ":", "# Named namespace", "if", "not", "Match", "(", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace\\s+'", "+", "re", ".", "escape", "(", "self", ".", "name", ")", "+", "r'[\\*/\\.\\\\\\s]*$'", ")", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Namespace should be terminated with \"// namespace %s\"'", "%", "self", ".", "name", ")", "else", ":", "# Anonymous namespace", "if", "not", "Match", "(", "r'^\\s*};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$'", ",", "line", ")", ":", "# If \"// namespace anonymous\" or \"// anonymous namespace (more text)\",", "# mention \"// anonymous namespace\" as an acceptable form", "if", "Match", "(", "r'^\\s*}.*\\b(namespace anonymous|anonymous namespace)\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", "' or \"// anonymous namespace\"'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", ")" ]
https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/cpplint.py#L2838-L2888
yun-liu/RCF
91bfb054ad04187dbbe21e539e165ad9bd3ff00b
scripts/cpp_lint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Logs an error if we see /* ... */ or "..." that extend past one line.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/yun-liu/RCF/blob/91bfb054ad04187dbbe21e539e165ad9bd3ff00b/scripts/cpp_lint.py#L1526-L1561
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/shutil.py
python
copytree
(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
return dst
Recursively copy a directory tree. The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the file pointed by the symlink doesn't exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this has no effect on platforms that don't support os.symlink. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory being visited by copytree(), and `names` which is the list of `src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the `src` directory that should not be copied. The optional copy_function argument is a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used.
Recursively copy a directory tree.
[ "Recursively", "copy", "a", "directory", "tree", "." ]
def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False): """Recursively copy a directory tree. The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the file pointed by the symlink doesn't exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this has no effect on platforms that don't support os.symlink. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory being visited by copytree(), and `names` which is the list of `src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the `src` directory that should not be copied. The optional copy_function argument is a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.islink(srcname): linkto = os.readlink(srcname) if symlinks: # We can't just leave it to `copy_function` because legacy # code with a custom `copy_function` may rely on copytree # doing the right thing. os.symlink(linkto, dstname) copystat(srcname, dstname, follow_symlinks=not symlinks) else: # ignore dangling symlink if the flag is on if not os.path.exists(linkto) and ignore_dangling_symlinks: continue # otherwise let the copy occurs. copy2 will raise an error if os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore, copy_function) else: copy_function(srcname, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore, copy_function) else: # Will raise a SpecialFileError for unsupported file types copy_function(srcname, dstname) # catch the Error from the recursive copytree so that we can # continue with other files except Error as err: errors.extend(err.args[0]) except OSError as why: errors.append((srcname, dstname, str(why))) try: copystat(src, dst) except OSError as why: # Copying file access times may fail on Windows if getattr(why, 'winerror', None) is None: errors.append((src, dst, str(why))) if errors: raise Error(errors) return dst
[ "def", "copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ",", "ignore", "=", "None", ",", "copy_function", "=", "copy2", ",", "ignore_dangling_symlinks", "=", "False", ")", ":", "names", "=", "os", ".", "listdir", "(", "src", ")", "if", "ignore", "is", "not", "None", ":", "ignored_names", "=", "ignore", "(", "src", ",", "names", ")", "else", ":", "ignored_names", "=", "set", "(", ")", "os", ".", "makedirs", "(", "dst", ")", "errors", "=", "[", "]", "for", "name", "in", "names", ":", "if", "name", "in", "ignored_names", ":", "continue", "srcname", "=", "os", ".", "path", ".", "join", "(", "src", ",", "name", ")", "dstname", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "name", ")", "try", ":", "if", "os", ".", "path", ".", "islink", "(", "srcname", ")", ":", "linkto", "=", "os", ".", "readlink", "(", "srcname", ")", "if", "symlinks", ":", "# We can't just leave it to `copy_function` because legacy", "# code with a custom `copy_function` may rely on copytree", "# doing the right thing.", "os", ".", "symlink", "(", "linkto", ",", "dstname", ")", "copystat", "(", "srcname", ",", "dstname", ",", "follow_symlinks", "=", "not", "symlinks", ")", "else", ":", "# ignore dangling symlink if the flag is on", "if", "not", "os", ".", "path", ".", "exists", "(", "linkto", ")", "and", "ignore_dangling_symlinks", ":", "continue", "# otherwise let the copy occurs. copy2 will raise an error", "if", "os", ".", "path", ".", "isdir", "(", "srcname", ")", ":", "copytree", "(", "srcname", ",", "dstname", ",", "symlinks", ",", "ignore", ",", "copy_function", ")", "else", ":", "copy_function", "(", "srcname", ",", "dstname", ")", "elif", "os", ".", "path", ".", "isdir", "(", "srcname", ")", ":", "copytree", "(", "srcname", ",", "dstname", ",", "symlinks", ",", "ignore", ",", "copy_function", ")", "else", ":", "# Will raise a SpecialFileError for unsupported file types", "copy_function", "(", "srcname", ",", "dstname", ")", "# catch the Error from the recursive copytree so that we can", "# continue with other files", "except", "Error", "as", "err", ":", "errors", ".", "extend", "(", "err", ".", "args", "[", "0", "]", ")", "except", "OSError", "as", "why", ":", "errors", ".", "append", "(", "(", "srcname", ",", "dstname", ",", "str", "(", "why", ")", ")", ")", "try", ":", "copystat", "(", "src", ",", "dst", ")", "except", "OSError", "as", "why", ":", "# Copying file access times may fail on Windows", "if", "getattr", "(", "why", ",", "'winerror'", ",", "None", ")", "is", "None", ":", "errors", ".", "append", "(", "(", "src", ",", "dst", ",", "str", "(", "why", ")", ")", ")", "if", "errors", ":", "raise", "Error", "(", "errors", ")", "return", "dst" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/shutil.py#L282-L369
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/util/traceback_utils.py
python
is_traceback_filtering_enabled
()
return value
Check whether traceback filtering is currently enabled. See also `tf.debugging.enable_traceback_filtering()` and `tf.debugging.disable_traceback_filtering()`. Note that filtering out internal frames from the tracebacks of exceptions raised by TensorFlow code is the default behavior. Returns: True if traceback filtering is enabled (e.g. if `tf.debugging.enable_traceback_filtering()` was called), and False otherwise (e.g. if `tf.debugging.disable_traceback_filtering()` was called).
Check whether traceback filtering is currently enabled.
[ "Check", "whether", "traceback", "filtering", "is", "currently", "enabled", "." ]
def is_traceback_filtering_enabled(): """Check whether traceback filtering is currently enabled. See also `tf.debugging.enable_traceback_filtering()` and `tf.debugging.disable_traceback_filtering()`. Note that filtering out internal frames from the tracebacks of exceptions raised by TensorFlow code is the default behavior. Returns: True if traceback filtering is enabled (e.g. if `tf.debugging.enable_traceback_filtering()` was called), and False otherwise (e.g. if `tf.debugging.disable_traceback_filtering()` was called). """ value = getattr(_ENABLE_TRACEBACK_FILTERING, 'value', True) return value
[ "def", "is_traceback_filtering_enabled", "(", ")", ":", "value", "=", "getattr", "(", "_ENABLE_TRACEBACK_FILTERING", ",", "'value'", ",", "True", ")", "return", "value" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/traceback_utils.py#L33-L48
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/platform/proc_supporting_platform_backend.py
python
ProcSupportingPlatformBackend._GetProcJiffies
(self, timer_list)
Parse '/proc/timer_list' output and returns the first jiffies attribute. Multi-CPU machines will have multiple 'jiffies:' lines, all of which will be essentially the same. Return the first one.
Parse '/proc/timer_list' output and returns the first jiffies attribute.
[ "Parse", "/", "proc", "/", "timer_list", "output", "and", "returns", "the", "first", "jiffies", "attribute", "." ]
def _GetProcJiffies(self, timer_list): """Parse '/proc/timer_list' output and returns the first jiffies attribute. Multi-CPU machines will have multiple 'jiffies:' lines, all of which will be essentially the same. Return the first one.""" if isinstance(timer_list, str): timer_list = timer_list.splitlines() for line in timer_list: if line.startswith('jiffies:'): _, value = line.split(':') return value raise Exception('Unable to find jiffies from /proc/timer_list')
[ "def", "_GetProcJiffies", "(", "self", ",", "timer_list", ")", ":", "if", "isinstance", "(", "timer_list", ",", "str", ")", ":", "timer_list", "=", "timer_list", ".", "splitlines", "(", ")", "for", "line", "in", "timer_list", ":", "if", "line", ".", "startswith", "(", "'jiffies:'", ")", ":", "_", ",", "value", "=", "line", ".", "split", "(", "':'", ")", "return", "value", "raise", "Exception", "(", "'Unable to find jiffies from /proc/timer_list'", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/platform/proc_supporting_platform_backend.py#L103-L114
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py
python
AbstractFileSystem.start_transaction
(self)
return self.transaction
Begin write transaction for deferring files, non-context version
Begin write transaction for deferring files, non-context version
[ "Begin", "write", "transaction", "for", "deferring", "files", "non", "-", "context", "version" ]
def start_transaction(self): """Begin write transaction for deferring files, non-context version""" self._intrans = True self._transaction = Transaction(self) return self.transaction
[ "def", "start_transaction", "(", "self", ")", ":", "self", ".", "_intrans", "=", "True", "self", ".", "_transaction", "=", "Transaction", "(", "self", ")", "return", "self", ".", "transaction" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py#L197-L201
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py
python
KScriptGenerator.updateCalledFunctionList
(self, callee)
Maintains a list of functions that will actually be called
Maintains a list of functions that will actually be called
[ "Maintains", "a", "list", "of", "functions", "that", "will", "actually", "be", "called" ]
def updateCalledFunctionList(self, callee): """Maintains a list of functions that will actually be called""" # Update the total call count self.updateTotalCallCount(callee) # If this function is already in the list, don't do anything else if callee in self.calledFunctions: return # Add this function to the list of those that will be called. self.calledFunctions.append(callee) # If this function calls other functions, add them too if callee in self.calledFunctionTable: for subCallee in self.calledFunctionTable[callee]: self.updateCalledFunctionList(subCallee)
[ "def", "updateCalledFunctionList", "(", "self", ",", "callee", ")", ":", "# Update the total call count", "self", ".", "updateTotalCallCount", "(", "callee", ")", "# If this function is already in the list, don't do anything else", "if", "callee", "in", "self", ".", "calledFunctions", ":", "return", "# Add this function to the list of those that will be called.", "self", ".", "calledFunctions", ".", "append", "(", "callee", ")", "# If this function calls other functions, add them too", "if", "callee", "in", "self", ".", "calledFunctionTable", ":", "for", "subCallee", "in", "self", ".", "calledFunctionTable", "[", "callee", "]", ":", "self", ".", "updateCalledFunctionList", "(", "subCallee", ")" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L66-L78
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mhlib.py
python
Folder.parsesequence
(self, seq)
Parse an MH sequence specification into a message list. Attempt to mimic mh-sequence(5) as close as possible. Also attempt to mimic observed behavior regarding which conditions cause which error messages.
Parse an MH sequence specification into a message list. Attempt to mimic mh-sequence(5) as close as possible. Also attempt to mimic observed behavior regarding which conditions cause which error messages.
[ "Parse", "an", "MH", "sequence", "specification", "into", "a", "message", "list", ".", "Attempt", "to", "mimic", "mh", "-", "sequence", "(", "5", ")", "as", "close", "as", "possible", ".", "Also", "attempt", "to", "mimic", "observed", "behavior", "regarding", "which", "conditions", "cause", "which", "error", "messages", "." ]
def parsesequence(self, seq): """Parse an MH sequence specification into a message list. Attempt to mimic mh-sequence(5) as close as possible. Also attempt to mimic observed behavior regarding which conditions cause which error messages.""" # XXX Still not complete (see mh-format(5)). # Missing are: # - 'prev', 'next' as count # - Sequence-Negation option all = self.listmessages() # Observed behavior: test for empty folder is done first if not all: raise Error, "no messages in %s" % self.name # Common case first: all is frequently the default if seq == 'all': return all # Test for X:Y before X-Y because 'seq:-n' matches both i = seq.find(':') if i >= 0: head, dir, tail = seq[:i], '', seq[i+1:] if tail[:1] in '-+': dir, tail = tail[:1], tail[1:] if not isnumeric(tail): raise Error, "bad message list %s" % seq try: count = int(tail) except (ValueError, OverflowError): # Can't use sys.maxint because of i+count below count = len(all) try: anchor = self._parseindex(head, all) except Error, msg: seqs = self.getsequences() if not head in seqs: if not msg: msg = "bad message list %s" % seq raise Error, msg, sys.exc_info()[2] msgs = seqs[head] if not msgs: raise Error, "sequence %s empty" % head if dir == '-': return msgs[-count:] else: return msgs[:count] else: if not dir: if head in ('prev', 'last'): dir = '-' if dir == '-': i = bisect(all, anchor) return all[max(0, i-count):i] else: i = bisect(all, anchor-1) return all[i:i+count] # Test for X-Y next i = seq.find('-') if i >= 0: begin = self._parseindex(seq[:i], all) end = self._parseindex(seq[i+1:], all) i = bisect(all, begin-1) j = bisect(all, end) r = all[i:j] if not r: raise Error, "bad message list %s" % seq return r # Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence try: n = self._parseindex(seq, all) except Error, msg: seqs = self.getsequences() if not seq in seqs: if not msg: msg = "bad message list %s" % seq raise Error, msg return seqs[seq] else: if n not in all: if isnumeric(seq): raise Error, "message %d doesn't exist" % n else: raise Error, "no %s message" % seq else: return [n]
[ "def", "parsesequence", "(", "self", ",", "seq", ")", ":", "# XXX Still not complete (see mh-format(5)).", "# Missing are:", "# - 'prev', 'next' as count", "# - Sequence-Negation option", "all", "=", "self", ".", "listmessages", "(", ")", "# Observed behavior: test for empty folder is done first", "if", "not", "all", ":", "raise", "Error", ",", "\"no messages in %s\"", "%", "self", ".", "name", "# Common case first: all is frequently the default", "if", "seq", "==", "'all'", ":", "return", "all", "# Test for X:Y before X-Y because 'seq:-n' matches both", "i", "=", "seq", ".", "find", "(", "':'", ")", "if", "i", ">=", "0", ":", "head", ",", "dir", ",", "tail", "=", "seq", "[", ":", "i", "]", ",", "''", ",", "seq", "[", "i", "+", "1", ":", "]", "if", "tail", "[", ":", "1", "]", "in", "'-+'", ":", "dir", ",", "tail", "=", "tail", "[", ":", "1", "]", ",", "tail", "[", "1", ":", "]", "if", "not", "isnumeric", "(", "tail", ")", ":", "raise", "Error", ",", "\"bad message list %s\"", "%", "seq", "try", ":", "count", "=", "int", "(", "tail", ")", "except", "(", "ValueError", ",", "OverflowError", ")", ":", "# Can't use sys.maxint because of i+count below", "count", "=", "len", "(", "all", ")", "try", ":", "anchor", "=", "self", ".", "_parseindex", "(", "head", ",", "all", ")", "except", "Error", ",", "msg", ":", "seqs", "=", "self", ".", "getsequences", "(", ")", "if", "not", "head", "in", "seqs", ":", "if", "not", "msg", ":", "msg", "=", "\"bad message list %s\"", "%", "seq", "raise", "Error", ",", "msg", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "msgs", "=", "seqs", "[", "head", "]", "if", "not", "msgs", ":", "raise", "Error", ",", "\"sequence %s empty\"", "%", "head", "if", "dir", "==", "'-'", ":", "return", "msgs", "[", "-", "count", ":", "]", "else", ":", "return", "msgs", "[", ":", "count", "]", "else", ":", "if", "not", "dir", ":", "if", "head", "in", "(", "'prev'", ",", "'last'", ")", ":", "dir", "=", "'-'", "if", "dir", "==", "'-'", ":", "i", "=", "bisect", "(", "all", ",", "anchor", ")", "return", "all", "[", "max", "(", "0", ",", "i", "-", "count", ")", ":", "i", "]", "else", ":", "i", "=", "bisect", "(", "all", ",", "anchor", "-", "1", ")", "return", "all", "[", "i", ":", "i", "+", "count", "]", "# Test for X-Y next", "i", "=", "seq", ".", "find", "(", "'-'", ")", "if", "i", ">=", "0", ":", "begin", "=", "self", ".", "_parseindex", "(", "seq", "[", ":", "i", "]", ",", "all", ")", "end", "=", "self", ".", "_parseindex", "(", "seq", "[", "i", "+", "1", ":", "]", ",", "all", ")", "i", "=", "bisect", "(", "all", ",", "begin", "-", "1", ")", "j", "=", "bisect", "(", "all", ",", "end", ")", "r", "=", "all", "[", "i", ":", "j", "]", "if", "not", "r", ":", "raise", "Error", ",", "\"bad message list %s\"", "%", "seq", "return", "r", "# Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence", "try", ":", "n", "=", "self", ".", "_parseindex", "(", "seq", ",", "all", ")", "except", "Error", ",", "msg", ":", "seqs", "=", "self", ".", "getsequences", "(", ")", "if", "not", "seq", "in", "seqs", ":", "if", "not", "msg", ":", "msg", "=", "\"bad message list %s\"", "%", "seq", "raise", "Error", ",", "msg", "return", "seqs", "[", "seq", "]", "else", ":", "if", "n", "not", "in", "all", ":", "if", "isnumeric", "(", "seq", ")", ":", "raise", "Error", ",", "\"message %d doesn't exist\"", "%", "n", "else", ":", "raise", "Error", ",", "\"no %s message\"", "%", "seq", "else", ":", "return", "[", "n", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mhlib.py#L346-L428
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/applications/mobilenet.py
python
_depthwise_conv_block
(inputs, pointwise_conv_filters, alpha, depth_multiplier=1, strides=(1, 1), block_id=1)
return Activation(relu6, name='conv_pw_%d_relu' % block_id)(x)
Adds a depthwise convolution block. A depthwise convolution block consists of a depthwise conv, batch normalization, relu6, pointwise convolution, batch normalization and relu6 activation. Arguments: inputs: Input tensor of shape `(rows, cols, channels)` (with `channels_last` data format) or (channels, rows, cols) (with `channels_first` data format). pointwise_conv_filters: Integer, the dimensionality of the output space (i.e. the number output of filters in the pointwise convolution). alpha: controls the width of the network. - If `alpha` < 1.0, proportionally decreases the number of filters in each layer. - If `alpha` > 1.0, proportionally increases the number of filters in each layer. - If `alpha` = 1, default number of filters from the paper are used at each layer. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. block_id: Integer, a unique identification designating the block number. Input shape: 4D tensor with shape: `(batch, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(batch, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(batch, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(batch, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to stride. Returns: Output tensor of block.
Adds a depthwise convolution block.
[ "Adds", "a", "depthwise", "convolution", "block", "." ]
def _depthwise_conv_block(inputs, pointwise_conv_filters, alpha, depth_multiplier=1, strides=(1, 1), block_id=1): """Adds a depthwise convolution block. A depthwise convolution block consists of a depthwise conv, batch normalization, relu6, pointwise convolution, batch normalization and relu6 activation. Arguments: inputs: Input tensor of shape `(rows, cols, channels)` (with `channels_last` data format) or (channels, rows, cols) (with `channels_first` data format). pointwise_conv_filters: Integer, the dimensionality of the output space (i.e. the number output of filters in the pointwise convolution). alpha: controls the width of the network. - If `alpha` < 1.0, proportionally decreases the number of filters in each layer. - If `alpha` > 1.0, proportionally increases the number of filters in each layer. - If `alpha` = 1, default number of filters from the paper are used at each layer. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. block_id: Integer, a unique identification designating the block number. Input shape: 4D tensor with shape: `(batch, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(batch, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(batch, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(batch, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to stride. Returns: Output tensor of block. """ channel_axis = 1 if K.image_data_format() == 'channels_first' else -1 pointwise_conv_filters = int(pointwise_conv_filters * alpha) x = DepthwiseConv2D( # pylint: disable=not-callable (3, 3), padding='same', depth_multiplier=depth_multiplier, strides=strides, use_bias=False, name='conv_dw_%d' % block_id)(inputs) x = BatchNormalization(axis=channel_axis, name='conv_dw_%d_bn' % block_id)(x) x = Activation(relu6, name='conv_dw_%d_relu' % block_id)(x) x = Conv2D( pointwise_conv_filters, (1, 1), padding='same', use_bias=False, strides=(1, 1), name='conv_pw_%d' % block_id)(x) x = BatchNormalization(axis=channel_axis, name='conv_pw_%d_bn' % block_id)(x) return Activation(relu6, name='conv_pw_%d_relu' % block_id)(x)
[ "def", "_depthwise_conv_block", "(", "inputs", ",", "pointwise_conv_filters", ",", "alpha", ",", "depth_multiplier", "=", "1", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "block_id", "=", "1", ")", ":", "channel_axis", "=", "1", "if", "K", ".", "image_data_format", "(", ")", "==", "'channels_first'", "else", "-", "1", "pointwise_conv_filters", "=", "int", "(", "pointwise_conv_filters", "*", "alpha", ")", "x", "=", "DepthwiseConv2D", "(", "# pylint: disable=not-callable", "(", "3", ",", "3", ")", ",", "padding", "=", "'same'", ",", "depth_multiplier", "=", "depth_multiplier", ",", "strides", "=", "strides", ",", "use_bias", "=", "False", ",", "name", "=", "'conv_dw_%d'", "%", "block_id", ")", "(", "inputs", ")", "x", "=", "BatchNormalization", "(", "axis", "=", "channel_axis", ",", "name", "=", "'conv_dw_%d_bn'", "%", "block_id", ")", "(", "x", ")", "x", "=", "Activation", "(", "relu6", ",", "name", "=", "'conv_dw_%d_relu'", "%", "block_id", ")", "(", "x", ")", "x", "=", "Conv2D", "(", "pointwise_conv_filters", ",", "(", "1", ",", "1", ")", ",", "padding", "=", "'same'", ",", "use_bias", "=", "False", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "name", "=", "'conv_pw_%d'", "%", "block_id", ")", "(", "x", ")", "x", "=", "BatchNormalization", "(", "axis", "=", "channel_axis", ",", "name", "=", "'conv_pw_%d_bn'", "%", "block_id", ")", "(", "x", ")", "return", "Activation", "(", "relu6", ",", "name", "=", "'conv_pw_%d_relu'", "%", "block_id", ")", "(", "x", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/applications/mobilenet.py#L596-L669
cathywu/Sentiment-Analysis
eb501fd1375c0c3f3ab430f963255f1bb858e659
PyML-0.7.9/PyML/utils/misc.py
python
update
(x, **entries)
Update a dict or an object with according to entries. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20)
Update a dict or an object with according to entries. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20)
[ "Update", "a", "dict", "or", "an", "object", "with", "according", "to", "entries", ".", ">>>", "update", "(", "{", "a", ":", "1", "}", "a", "=", "10", "b", "=", "20", ")", "{", "a", ":", "10", "b", ":", "20", "}", ">>>", "update", "(", "Struct", "(", "a", "=", "1", ")", "a", "=", "10", "b", "=", "20", ")", "Struct", "(", "a", "=", "10", "b", "=", "20", ")" ]
def update(x, **entries): """Update a dict or an object with according to entries. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) """ if isinstance(x, dict): x.update(entries) else : for attribute in entries : setattr(x, attribute, entries[attribute])
[ "def", "update", "(", "x", ",", "*", "*", "entries", ")", ":", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "x", ".", "update", "(", "entries", ")", "else", ":", "for", "attribute", "in", "entries", ":", "setattr", "(", "x", ",", "attribute", ",", "entries", "[", "attribute", "]", ")" ]
https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/utils/misc.py#L676-L687
facebook/proxygen
a9ca025af207787815cb01eee1971cd572c7a81e
build/fbcode_builder/getdeps/manifest.py
python
ManifestParser.is_first_party_project
(self)
return self.shipit_project is not None
returns true if this is an FB first-party project
returns true if this is an FB first-party project
[ "returns", "true", "if", "this", "is", "an", "FB", "first", "-", "party", "project" ]
def is_first_party_project(self): """returns true if this is an FB first-party project""" return self.shipit_project is not None
[ "def", "is_first_party_project", "(", "self", ")", ":", "return", "self", ".", "shipit_project", "is", "not", "None" ]
https://github.com/facebook/proxygen/blob/a9ca025af207787815cb01eee1971cd572c7a81e/build/fbcode_builder/getdeps/manifest.py#L354-L356
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py
python
Minitaur._ResetPoseForLeg
(self, leg_id, add_constraint)
Reset the initial pose for the leg. Args: leg_id: It should be 0, 1, 2, or 3, which represents the leg at front_left, back_left, front_right and back_right. add_constraint: Whether to add a constraint at the joints of two feet.
Reset the initial pose for the leg.
[ "Reset", "the", "initial", "pose", "for", "the", "leg", "." ]
def _ResetPoseForLeg(self, leg_id, add_constraint): """Reset the initial pose for the leg. Args: leg_id: It should be 0, 1, 2, or 3, which represents the leg at front_left, back_left, front_right and back_right. add_constraint: Whether to add a constraint at the joints of two feet. """ knee_friction_force = 0 half_pi = math.pi / 2.0 knee_angle = -2.1834 leg_position = LEG_POSITION[leg_id] self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["motor_" + leg_position + "L_joint"], self._motor_direction[2 * leg_id] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_link"], self._motor_direction[2 * leg_id] * knee_angle, targetVelocity=0) self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["motor_" + leg_position + "R_joint"], self._motor_direction[2 * leg_id + 1] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_link"], self._motor_direction[2 * leg_id + 1] * knee_angle, targetVelocity=0) if add_constraint: self._pybullet_client.createConstraint( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_link"], self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_link"], self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0], KNEE_CONSTRAINT_POINT_RIGHT, KNEE_CONSTRAINT_POINT_LEFT) if self._accurate_motor_model_enabled or self._pd_control_enabled: # Disable the default motor in pybullet. self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "L_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "R_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) else: self._SetDesiredMotorAngleByName("motor_" + leg_position + "L_joint", self._motor_direction[2 * leg_id] * half_pi) self._SetDesiredMotorAngleByName("motor_" + leg_position + "R_joint", self._motor_direction[2 * leg_id + 1] * half_pi) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "L_link"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "R_link"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force)
[ "def", "_ResetPoseForLeg", "(", "self", ",", "leg_id", ",", "add_constraint", ")", ":", "knee_friction_force", "=", "0", "half_pi", "=", "math", ".", "pi", "/", "2.0", "knee_angle", "=", "-", "2.1834", "leg_position", "=", "LEG_POSITION", "[", "leg_id", "]", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "]", "*", "half_pi", ",", "targetVelocity", "=", "0", ")", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"L_link\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "]", "*", "knee_angle", ",", "targetVelocity", "=", "0", ")", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "+", "1", "]", "*", "half_pi", ",", "targetVelocity", "=", "0", ")", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"R_link\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "+", "1", "]", "*", "knee_angle", ",", "targetVelocity", "=", "0", ")", "if", "add_constraint", ":", "self", ".", "_pybullet_client", ".", "createConstraint", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"R_link\"", "]", ",", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"L_link\"", "]", ",", "self", ".", "_pybullet_client", ".", "JOINT_POINT2POINT", ",", "[", "0", ",", "0", ",", "0", "]", ",", "KNEE_CONSTRAINT_POINT_RIGHT", ",", "KNEE_CONSTRAINT_POINT_LEFT", ")", "if", "self", ".", "_accurate_motor_model_enabled", "or", "self", ".", "_pd_control_enabled", ":", "# Disable the default motor in pybullet.", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")", "else", ":", "self", ".", "_SetDesiredMotorAngleByName", "(", "\"motor_\"", "+", "leg_position", "+", "\"L_joint\"", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "]", "*", "half_pi", ")", "self", ".", "_SetDesiredMotorAngleByName", "(", "\"motor_\"", "+", "leg_position", "+", "\"R_joint\"", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "+", "1", "]", "*", "half_pi", ")", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"L_link\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"R_link\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py#L345-L417
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
imag
(input, name=None)
Returns the imaginary part of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of type `float32` or `float64` that is the imaginary part of each element in `input`. All elements in `input` must be complex numbers of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part returned by this operation. For example: ``` # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.imag(input) ==> [4.75, 5.75] ``` Args: input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32` or `float64`.
Returns the imaginary part of a complex number.
[ "Returns", "the", "imaginary", "part", "of", "a", "complex", "number", "." ]
def imag(input, name=None): """Returns the imaginary part of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of type `float32` or `float64` that is the imaginary part of each element in `input`. All elements in `input` must be complex numbers of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part returned by this operation. For example: ``` # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.imag(input) ==> [4.75, 5.75] ``` Args: input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32` or `float64`. """ with ops.op_scope([input], name, "Imag") as name: return gen_math_ops.imag(input, Tout=input.dtype.real_dtype, name=name)
[ "def", "imag", "(", "input", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "input", "]", ",", "name", ",", "\"Imag\"", ")", "as", "name", ":", "return", "gen_math_ops", ".", "imag", "(", "input", ",", "Tout", "=", "input", ".", "dtype", ".", "real_dtype", ",", "name", "=", "name", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L536-L560
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibar.py
python
AuiToolBar.OnIdle
(self, event)
Handles the ``wx.EVT_IDLE`` event for :class:`AuiToolBar`. :param `event`: a :class:`IdleEvent` event to be processed.
Handles the ``wx.EVT_IDLE`` event for :class:`AuiToolBar`.
[ "Handles", "the", "wx", ".", "EVT_IDLE", "event", "for", ":", "class", ":", "AuiToolBar", "." ]
def OnIdle(self, event): """ Handles the ``wx.EVT_IDLE`` event for :class:`AuiToolBar`. :param `event`: a :class:`IdleEvent` event to be processed. """ self.DoIdleUpdate() event.Skip()
[ "def", "OnIdle", "(", "self", ",", "event", ")", ":", "self", ".", "DoIdleUpdate", "(", ")", "event", ".", "Skip", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L3390-L3398
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/frameworks/methodManager.py
python
MethodManager.checkData
(self, data)
return data
Overwrite for special checks to return data values
Overwrite for special checks to return data values
[ "Overwrite", "for", "special", "checks", "to", "return", "data", "values" ]
def checkData(self, data): """Overwrite for special checks to return data values""" # if self._dataToken == 'nan': # pg.critical('self._dataToken nan, should be set in class', self) # return data(self._dataToken) return data
[ "def", "checkData", "(", "self", ",", "data", ")", ":", "# if self._dataToken == 'nan':", "# pg.critical('self._dataToken nan, should be set in class', self)", "# return data(self._dataToken)", "return", "data" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/frameworks/methodManager.py#L312-L317
FEniCS/dolfinx
3dfdf038cccdb70962865b58a63bf29c2e55ec6e
python/dolfinx/io.py
python
extract_gmsh_geometry
(gmsh_model, model_name=None)
return points[perm_sort]
For a given gmsh model, extract the mesh geometry as a numpy (N,3) array where the i-th row corresponds to the i-th node in the mesh.
For a given gmsh model, extract the mesh geometry as a numpy (N,3) array where the i-th row corresponds to the i-th node in the mesh.
[ "For", "a", "given", "gmsh", "model", "extract", "the", "mesh", "geometry", "as", "a", "numpy", "(", "N", "3", ")", "array", "where", "the", "i", "-", "th", "row", "corresponds", "to", "the", "i", "-", "th", "node", "in", "the", "mesh", "." ]
def extract_gmsh_geometry(gmsh_model, model_name=None): """For a given gmsh model, extract the mesh geometry as a numpy (N,3) array where the i-th row corresponds to the i-th node in the mesh. """ if model_name is not None: gmsh_model.setCurrent(model_name) # Get the unique tag and coordinates for nodes # in mesh indices, points, _ = gmsh_model.mesh.getNodes() points = points.reshape(-1, 3) # GMSH indices starts at 1 indices -= 1 # Sort nodes in geometry according to the unique index perm_sort = np.argsort(indices) assert np.all(indices[perm_sort] == np.arange(len(indices))) return points[perm_sort]
[ "def", "extract_gmsh_geometry", "(", "gmsh_model", ",", "model_name", "=", "None", ")", ":", "if", "model_name", "is", "not", "None", ":", "gmsh_model", ".", "setCurrent", "(", "model_name", ")", "# Get the unique tag and coordinates for nodes", "# in mesh", "indices", ",", "points", ",", "_", "=", "gmsh_model", ".", "mesh", ".", "getNodes", "(", ")", "points", "=", "points", ".", "reshape", "(", "-", "1", ",", "3", ")", "# GMSH indices starts at 1", "indices", "-=", "1", "# Sort nodes in geometry according to the unique index", "perm_sort", "=", "np", ".", "argsort", "(", "indices", ")", "assert", "np", ".", "all", "(", "indices", "[", "perm_sort", "]", "==", "np", ".", "arange", "(", "len", "(", "indices", ")", ")", ")", "return", "points", "[", "perm_sort", "]" ]
https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/io.py#L130-L150
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py
python
sconsign_dir
(node)
return node._sconsign
Return the .sconsign file info for this directory, creating it first if necessary.
Return the .sconsign file info for this directory, creating it first if necessary.
[ "Return", "the", ".", "sconsign", "file", "info", "for", "this", "directory", "creating", "it", "first", "if", "necessary", "." ]
def sconsign_dir(node): """Return the .sconsign file info for this directory, creating it first if necessary.""" if not node._sconsign: import SCons.SConsign node._sconsign = SCons.SConsign.ForDirectory(node) return node._sconsign
[ "def", "sconsign_dir", "(", "node", ")", ":", "if", "not", "node", ".", "_sconsign", ":", "import", "SCons", ".", "SConsign", "node", ".", "_sconsign", "=", "SCons", ".", "SConsign", ".", "ForDirectory", "(", "node", ")", "return", "node", ".", "_sconsign" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L74-L80
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosbag/src/rosbag/bag.py
python
Bag.reindex
(self)
return self._reader.reindex()
Reindexes the bag file. Yields position of each chunk for progress.
Reindexes the bag file. Yields position of each chunk for progress.
[ "Reindexes", "the", "bag", "file", ".", "Yields", "position", "of", "each", "chunk", "for", "progress", "." ]
def reindex(self): """ Reindexes the bag file. Yields position of each chunk for progress. """ self._clear_index() return self._reader.reindex()
[ "def", "reindex", "(", "self", ")", ":", "self", ".", "_clear_index", "(", ")", "return", "self", ".", "_reader", ".", "reindex", "(", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosbag/src/rosbag/bag.py#L408-L413
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/protobuf/python/google/protobuf/internal/decoder.py
python
_EndGroup
(buffer, pos, end)
return -1
Skipping an END_GROUP tag returns -1 to tell the parent loop to break.
Skipping an END_GROUP tag returns -1 to tell the parent loop to break.
[ "Skipping", "an", "END_GROUP", "tag", "returns", "-", "1", "to", "tell", "the", "parent", "loop", "to", "break", "." ]
def _EndGroup(buffer, pos, end): """Skipping an END_GROUP tag returns -1 to tell the parent loop to break.""" return -1
[ "def", "_EndGroup", "(", "buffer", ",", "pos", ",", "end", ")", ":", "return", "-", "1" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/google/protobuf/internal/decoder.py#L663-L666
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/stats/_distn_infrastructure.py
python
_expect
(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10, chunksize=32)
return tot
Helper for computing the expectation value of `fun`.
Helper for computing the expectation value of `fun`.
[ "Helper", "for", "computing", "the", "expectation", "value", "of", "fun", "." ]
def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10, chunksize=32): """Helper for computing the expectation value of `fun`.""" # short-circuit if the support size is small enough if (ub - lb) <= chunksize: supp = np.arange(lb, ub+1, inc) vals = fun(supp) return np.sum(vals) # otherwise, iterate starting from x0 if x0 < lb: x0 = lb if x0 > ub: x0 = ub count, tot = 0, 0. # iterate over [x0, ub] inclusive for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) return tot # iterate over [lb, x0) for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc): count += x.size delta = np.sum(fun(x)) tot += delta if abs(delta) < tolerance * x.size: break if count > maxcount: warnings.warn('expect(): sum did not converge', RuntimeWarning) break return tot
[ "def", "_expect", "(", "fun", ",", "lb", ",", "ub", ",", "x0", ",", "inc", ",", "maxcount", "=", "1000", ",", "tolerance", "=", "1e-10", ",", "chunksize", "=", "32", ")", ":", "# short-circuit if the support size is small enough", "if", "(", "ub", "-", "lb", ")", "<=", "chunksize", ":", "supp", "=", "np", ".", "arange", "(", "lb", ",", "ub", "+", "1", ",", "inc", ")", "vals", "=", "fun", "(", "supp", ")", "return", "np", ".", "sum", "(", "vals", ")", "# otherwise, iterate starting from x0", "if", "x0", "<", "lb", ":", "x0", "=", "lb", "if", "x0", ">", "ub", ":", "x0", "=", "ub", "count", ",", "tot", "=", "0", ",", "0.", "# iterate over [x0, ub] inclusive", "for", "x", "in", "_iter_chunked", "(", "x0", ",", "ub", "+", "1", ",", "chunksize", "=", "chunksize", ",", "inc", "=", "inc", ")", ":", "count", "+=", "x", ".", "size", "delta", "=", "np", ".", "sum", "(", "fun", "(", "x", ")", ")", "tot", "+=", "delta", "if", "abs", "(", "delta", ")", "<", "tolerance", "*", "x", ".", "size", ":", "break", "if", "count", ">", "maxcount", ":", "warnings", ".", "warn", "(", "'expect(): sum did not converge'", ",", "RuntimeWarning", ")", "return", "tot", "# iterate over [lb, x0)", "for", "x", "in", "_iter_chunked", "(", "x0", "-", "1", ",", "lb", "-", "1", ",", "chunksize", "=", "chunksize", ",", "inc", "=", "-", "inc", ")", ":", "count", "+=", "x", ".", "size", "delta", "=", "np", ".", "sum", "(", "fun", "(", "x", ")", ")", "tot", "+=", "delta", "if", "abs", "(", "delta", ")", "<", "tolerance", "*", "x", ".", "size", ":", "break", "if", "count", ">", "maxcount", ":", "warnings", ".", "warn", "(", "'expect(): sum did not converge'", ",", "RuntimeWarning", ")", "break", "return", "tot" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/_distn_infrastructure.py#L3256-L3295
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.write_commons
(self)
Writes a common preamble that is used by root and block functions. Primarily this sets up common local helpers and enforces a generator through a dead branch.
Writes a common preamble that is used by root and block functions. Primarily this sets up common local helpers and enforces a generator through a dead branch.
[ "Writes", "a", "common", "preamble", "that", "is", "used", "by", "root", "and", "block", "functions", ".", "Primarily", "this", "sets", "up", "common", "local", "helpers", "and", "enforces", "a", "generator", "through", "a", "dead", "branch", "." ]
def write_commons(self): """Writes a common preamble that is used by root and block functions. Primarily this sets up common local helpers and enforces a generator through a dead branch. """ self.writeline('resolve = context.resolve_or_missing') self.writeline('undefined = environment.undefined') self.writeline('if 0: yield None')
[ "def", "write_commons", "(", "self", ")", ":", "self", ".", "writeline", "(", "'resolve = context.resolve_or_missing'", ")", "self", ".", "writeline", "(", "'undefined = environment.undefined'", ")", "self", ".", "writeline", "(", "'if 0: yield None'", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/compiler.py#L605-L612
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
BaseWidget.destroy
(self)
Destroy this and all descendants widgets.
Destroy this and all descendants widgets.
[ "Destroy", "this", "and", "all", "descendants", "widgets", "." ]
def destroy(self): """Destroy this and all descendants widgets.""" for c in self.children.values(): c.destroy() self.tk.call('destroy', self._w) if self._name in self.master.children: del self.master.children[self._name] Misc.destroy(self)
[ "def", "destroy", "(", "self", ")", ":", "for", "c", "in", "self", ".", "children", ".", "values", "(", ")", ":", "c", ".", "destroy", "(", ")", "self", ".", "tk", ".", "call", "(", "'destroy'", ",", "self", ".", "_w", ")", "if", "self", ".", "_name", "in", "self", ".", "master", ".", "children", ":", "del", "self", ".", "master", ".", "children", "[", "self", ".", "_name", "]", "Misc", ".", "destroy", "(", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2039-L2045
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/mac_tool.py
python
MacTool._GetCFBundleIdentifier
(self)
return info_plist_data['CFBundleIdentifier']
Extracts CFBundleIdentifier value from Info.plist in the bundle. Returns: Value of CFBundleIdentifier in the Info.plist located in the bundle.
Extracts CFBundleIdentifier value from Info.plist in the bundle.
[ "Extracts", "CFBundleIdentifier", "value", "from", "Info", ".", "plist", "in", "the", "bundle", "." ]
def _GetCFBundleIdentifier(self): """Extracts CFBundleIdentifier value from Info.plist in the bundle. Returns: Value of CFBundleIdentifier in the Info.plist located in the bundle. """ info_plist_path = os.path.join( os.environ['TARGET_BUILD_DIR'], os.environ['INFOPLIST_PATH']) info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) return info_plist_data['CFBundleIdentifier']
[ "def", "_GetCFBundleIdentifier", "(", "self", ")", ":", "info_plist_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'TARGET_BUILD_DIR'", "]", ",", "os", ".", "environ", "[", "'INFOPLIST_PATH'", "]", ")", "info_plist_data", "=", "self", ".", "_LoadPlistMaybeBinary", "(", "info_plist_path", ")", "return", "info_plist_data", "[", "'CFBundleIdentifier'", "]" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/mac_tool.py#L541-L551
NVIDIAGameWorks/kaolin
e5148d05e9c1e2ce92a07881ce3593b1c5c3f166
kaolin/ops/voxelgrid.py
python
extract_surface
(voxelgrids, mode="wide")
return output
r"""Removes any internal structure(s) from a voxelgrids. Args: voxelgrids (torch.Tensor): Binary voxelgrids of shape (N, X, Y ,Z) from which to extract surface mode (str): Either "wide" or "thin". Each voxel can be seen as a cube in a grid. "wide" mode keeps each filled voxel with at least one vertex in contact with an empty voxel. "thin" mode keeps each filled voxel with at least one face in contact with an empty voxel. Returns: torch.BoolTensor: binary surface voxelgrids tensor Example: >>> voxelgrids = torch.ones((1, 3, 3, 3)) >>> output = extract_surface(voxelgrids) >>> output[0] tensor([[[ True, True, True], [ True, True, True], [ True, True, True]], <BLANKLINE> [[ True, True, True], [ True, False, True], [ True, True, True]], <BLANKLINE> [[ True, True, True], [ True, True, True], [ True, True, True]]])
r"""Removes any internal structure(s) from a voxelgrids.
[ "r", "Removes", "any", "internal", "structure", "(", "s", ")", "from", "a", "voxelgrids", "." ]
def extract_surface(voxelgrids, mode="wide"): r"""Removes any internal structure(s) from a voxelgrids. Args: voxelgrids (torch.Tensor): Binary voxelgrids of shape (N, X, Y ,Z) from which to extract surface mode (str): Either "wide" or "thin". Each voxel can be seen as a cube in a grid. "wide" mode keeps each filled voxel with at least one vertex in contact with an empty voxel. "thin" mode keeps each filled voxel with at least one face in contact with an empty voxel. Returns: torch.BoolTensor: binary surface voxelgrids tensor Example: >>> voxelgrids = torch.ones((1, 3, 3, 3)) >>> output = extract_surface(voxelgrids) >>> output[0] tensor([[[ True, True, True], [ True, True, True], [ True, True, True]], <BLANKLINE> [[ True, True, True], [ True, False, True], [ True, True, True]], <BLANKLINE> [[ True, True, True], [ True, True, True], [ True, True, True]]]) """ voxelgrids = _force_float(voxelgrids) if voxelgrids.ndim != 4: voxelgrids_dim = voxelgrids.ndim raise ValueError(f"Expected voxelgrids to have 4 dimensions " f"but got {voxelgrids_dim} dimensions.") if mode == "wide": output = F.avg_pool3d(voxelgrids.unsqueeze(1), kernel_size=(3, 3, 3), padding=1, stride=1).squeeze(1) output = (output < 1) * voxelgrids.bool() elif mode == "thin": output_x = F.avg_pool3d(voxelgrids.unsqueeze(1), kernel_size=(3, 1, 1), padding=(1, 0, 0), stride=1).squeeze(1) output_y = F.avg_pool3d(voxelgrids.unsqueeze(1), kernel_size=(1, 3, 1), padding=(0, 1, 0), stride=1).squeeze(1) output_z = F.avg_pool3d(voxelgrids.unsqueeze(1), kernel_size=(1, 1, 3), padding=(0, 0, 1), stride=1).squeeze(1) output = ((output_x < 1) | (output_y < 1) | (output_z < 1)) * voxelgrids.bool() else: raise ValueError(f'mode "{mode}" is not supported.') return output
[ "def", "extract_surface", "(", "voxelgrids", ",", "mode", "=", "\"wide\"", ")", ":", "voxelgrids", "=", "_force_float", "(", "voxelgrids", ")", "if", "voxelgrids", ".", "ndim", "!=", "4", ":", "voxelgrids_dim", "=", "voxelgrids", ".", "ndim", "raise", "ValueError", "(", "f\"Expected voxelgrids to have 4 dimensions \"", "f\"but got {voxelgrids_dim} dimensions.\"", ")", "if", "mode", "==", "\"wide\"", ":", "output", "=", "F", ".", "avg_pool3d", "(", "voxelgrids", ".", "unsqueeze", "(", "1", ")", ",", "kernel_size", "=", "(", "3", ",", "3", ",", "3", ")", ",", "padding", "=", "1", ",", "stride", "=", "1", ")", ".", "squeeze", "(", "1", ")", "output", "=", "(", "output", "<", "1", ")", "*", "voxelgrids", ".", "bool", "(", ")", "elif", "mode", "==", "\"thin\"", ":", "output_x", "=", "F", ".", "avg_pool3d", "(", "voxelgrids", ".", "unsqueeze", "(", "1", ")", ",", "kernel_size", "=", "(", "3", ",", "1", ",", "1", ")", ",", "padding", "=", "(", "1", ",", "0", ",", "0", ")", ",", "stride", "=", "1", ")", ".", "squeeze", "(", "1", ")", "output_y", "=", "F", ".", "avg_pool3d", "(", "voxelgrids", ".", "unsqueeze", "(", "1", ")", ",", "kernel_size", "=", "(", "1", ",", "3", ",", "1", ")", ",", "padding", "=", "(", "0", ",", "1", ",", "0", ")", ",", "stride", "=", "1", ")", ".", "squeeze", "(", "1", ")", "output_z", "=", "F", ".", "avg_pool3d", "(", "voxelgrids", ".", "unsqueeze", "(", "1", ")", ",", "kernel_size", "=", "(", "1", ",", "1", ",", "3", ")", ",", "padding", "=", "(", "0", ",", "0", ",", "1", ")", ",", "stride", "=", "1", ")", ".", "squeeze", "(", "1", ")", "output", "=", "(", "(", "output_x", "<", "1", ")", "|", "(", "output_y", "<", "1", ")", "|", "(", "output_z", "<", "1", ")", ")", "*", "voxelgrids", ".", "bool", "(", ")", "else", ":", "raise", "ValueError", "(", "f'mode \"{mode}\" is not supported.'", ")", "return", "output" ]
https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/ops/voxelgrid.py#L92-L140
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/service.py
python
RpcController.Failed
(self)
Returns true if the call failed. After a call has finished, returns true if the call failed. The possible reasons for failure depend on the RPC implementation. Failed() must not be called before a call has finished. If Failed() returns true, the contents of the response message are undefined.
Returns true if the call failed.
[ "Returns", "true", "if", "the", "call", "failed", "." ]
def Failed(self): """Returns true if the call failed. After a call has finished, returns true if the call failed. The possible reasons for failure depend on the RPC implementation. Failed() must not be called before a call has finished. If Failed() returns true, the contents of the response message are undefined. """ raise NotImplementedError
[ "def", "Failed", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/service.py#L142-L150
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/topics.py
python
_SubscriberImpl.set_buff_size
(self, buff_size)
Set the receive buffer size. The exact meaning of this is transport dependent. @param buff_size: receive buffer size @type buff_size: int
Set the receive buffer size. The exact meaning of this is transport dependent.
[ "Set", "the", "receive", "buffer", "size", ".", "The", "exact", "meaning", "of", "this", "is", "transport", "dependent", "." ]
def set_buff_size(self, buff_size): """ Set the receive buffer size. The exact meaning of this is transport dependent. @param buff_size: receive buffer size @type buff_size: int """ if type(buff_size) != int: raise ROSException("buffer size must be an integer") elif buff_size <= 0: raise ROSException("buffer size must be a positive integer") self.buff_size = buff_size
[ "def", "set_buff_size", "(", "self", ",", "buff_size", ")", ":", "if", "type", "(", "buff_size", ")", "!=", "int", ":", "raise", "ROSException", "(", "\"buffer size must be an integer\"", ")", "elif", "buff_size", "<=", "0", ":", "raise", "ROSException", "(", "\"buffer size must be a positive integer\"", ")", "self", ".", "buff_size", "=", "buff_size" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/topics.py#L657-L668
amd/OpenCL-caffe
638543108517265366c18ae5821f3096cf5cf34a
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/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/python/caffe/io.py#L31-L43
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/ssl.py
python
SSLSocket.do_handshake
(self)
Perform a TLS/SSL handshake.
Perform a TLS/SSL handshake.
[ "Perform", "a", "TLS", "/", "SSL", "handshake", "." ]
def do_handshake(self): """Perform a TLS/SSL handshake.""" self._sslobj.do_handshake()
[ "def", "do_handshake", "(", "self", ")", ":", "self", ".", "_sslobj", ".", "do_handshake", "(", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ssl.py#L289-L293
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/drafttaskpanels/task_scale.py
python
ScaleTaskPanel.setValue
(self, val=None)
Set the value of the points.
Set the value of the points.
[ "Set", "the", "value", "of", "the", "points", "." ]
def setValue(self, val=None): """Set the value of the points.""" if self.lock.isChecked(): if not self.xValue.hasFocus(): self.xValue.setValue(val) if not self.yValue.hasFocus(): self.yValue.setValue(val) if not self.zValue.hasFocus(): self.zValue.setValue(val) if self.sourceCmd: self.sourceCmd.scaleGhost(self.xValue.value(),self.yValue.value(),self.zValue.value(),self.relative.isChecked())
[ "def", "setValue", "(", "self", ",", "val", "=", "None", ")", ":", "if", "self", ".", "lock", ".", "isChecked", "(", ")", ":", "if", "not", "self", ".", "xValue", ".", "hasFocus", "(", ")", ":", "self", ".", "xValue", ".", "setValue", "(", "val", ")", "if", "not", "self", ".", "yValue", ".", "hasFocus", "(", ")", ":", "self", ".", "yValue", ".", "setValue", "(", "val", ")", "if", "not", "self", ".", "zValue", ".", "hasFocus", "(", ")", ":", "self", ".", "zValue", ".", "setValue", "(", "val", ")", "if", "self", ".", "sourceCmd", ":", "self", ".", "sourceCmd", ".", "scaleGhost", "(", "self", ".", "xValue", ".", "value", "(", ")", ",", "self", ".", "yValue", ".", "value", "(", ")", ",", "self", ".", "zValue", ".", "value", "(", ")", ",", "self", ".", "relative", ".", "isChecked", "(", ")", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/drafttaskpanels/task_scale.py#L137-L147
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/analogclock/analogclock.py
python
AnalogClock.GetTickSize
(self, target=ALL)
return self.Box.GetTickSize(target)
Gets sizes of ticks.
Gets sizes of ticks.
[ "Gets", "sizes", "of", "ticks", "." ]
def GetTickSize(self, target=ALL): """Gets sizes of ticks.""" return self.Box.GetTickSize(target)
[ "def", "GetTickSize", "(", "self", ",", "target", "=", "ALL", ")", ":", "return", "self", ".", "Box", ".", "GetTickSize", "(", "target", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/analogclock/analogclock.py#L231-L234
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/copy_helper.py
python
_CompressFileForUpload
(src_url, src_obj_filestream, src_obj_size, logger)
return StorageUrlFromString(gzip_path), gzip_size
Compresses a to-be-uploaded local file to save bandwidth. Args: src_url: Source FileUrl. src_obj_filestream: Read stream of the source file - will be consumed and closed. src_obj_size: Size of the source file. logger: for outputting log messages. Returns: StorageUrl path to compressed file, compressed file size.
Compresses a to-be-uploaded local file to save bandwidth.
[ "Compresses", "a", "to", "-", "be", "-", "uploaded", "local", "file", "to", "save", "bandwidth", "." ]
def _CompressFileForUpload(src_url, src_obj_filestream, src_obj_size, logger): """Compresses a to-be-uploaded local file to save bandwidth. Args: src_url: Source FileUrl. src_obj_filestream: Read stream of the source file - will be consumed and closed. src_obj_size: Size of the source file. logger: for outputting log messages. Returns: StorageUrl path to compressed file, compressed file size. """ # TODO: Compress using a streaming model as opposed to all at once here. if src_obj_size >= MIN_SIZE_COMPUTE_LOGGING: logger.info( 'Compressing %s (to tmp)...', src_url) (gzip_fh, gzip_path) = tempfile.mkstemp() gzip_fp = None try: # Check for temp space. Assume the compressed object is at most 2x # the size of the object (normally should compress to smaller than # the object) if CheckFreeSpace(gzip_path) < 2*int(src_obj_size): raise CommandException('Inadequate temp space available to compress ' '%s. See the CHANGING TEMP DIRECTORIES section ' 'of "gsutil help cp" for more info.' % src_url) gzip_fp = gzip.open(gzip_path, 'wb') data = src_obj_filestream.read(GZIP_CHUNK_SIZE) while data: gzip_fp.write(data) data = src_obj_filestream.read(GZIP_CHUNK_SIZE) finally: if gzip_fp: gzip_fp.close() os.close(gzip_fh) src_obj_filestream.close() gzip_size = os.path.getsize(gzip_path) return StorageUrlFromString(gzip_path), gzip_size
[ "def", "_CompressFileForUpload", "(", "src_url", ",", "src_obj_filestream", ",", "src_obj_size", ",", "logger", ")", ":", "# TODO: Compress using a streaming model as opposed to all at once here.", "if", "src_obj_size", ">=", "MIN_SIZE_COMPUTE_LOGGING", ":", "logger", ".", "info", "(", "'Compressing %s (to tmp)...'", ",", "src_url", ")", "(", "gzip_fh", ",", "gzip_path", ")", "=", "tempfile", ".", "mkstemp", "(", ")", "gzip_fp", "=", "None", "try", ":", "# Check for temp space. Assume the compressed object is at most 2x", "# the size of the object (normally should compress to smaller than", "# the object)", "if", "CheckFreeSpace", "(", "gzip_path", ")", "<", "2", "*", "int", "(", "src_obj_size", ")", ":", "raise", "CommandException", "(", "'Inadequate temp space available to compress '", "'%s. See the CHANGING TEMP DIRECTORIES section '", "'of \"gsutil help cp\" for more info.'", "%", "src_url", ")", "gzip_fp", "=", "gzip", ".", "open", "(", "gzip_path", ",", "'wb'", ")", "data", "=", "src_obj_filestream", ".", "read", "(", "GZIP_CHUNK_SIZE", ")", "while", "data", ":", "gzip_fp", ".", "write", "(", "data", ")", "data", "=", "src_obj_filestream", ".", "read", "(", "GZIP_CHUNK_SIZE", ")", "finally", ":", "if", "gzip_fp", ":", "gzip_fp", ".", "close", "(", ")", "os", ".", "close", "(", "gzip_fh", ")", "src_obj_filestream", ".", "close", "(", ")", "gzip_size", "=", "os", ".", "path", ".", "getsize", "(", "gzip_path", ")", "return", "StorageUrlFromString", "(", "gzip_path", ")", ",", "gzip_size" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/copy_helper.py#L1488-L1526
blackberry/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
tools/build/v2/build/property_set.py
python
PropertySet.add
(self, ps)
return self.added_[ps]
Creates a new property set containing the properties in this one, plus the ones of the property set passed as argument.
Creates a new property set containing the properties in this one, plus the ones of the property set passed as argument.
[ "Creates", "a", "new", "property", "set", "containing", "the", "properties", "in", "this", "one", "plus", "the", "ones", "of", "the", "property", "set", "passed", "as", "argument", "." ]
def add (self, ps): """ Creates a new property set containing the properties in this one, plus the ones of the property set passed as argument. """ if not self.added_.has_key(ps): self.added_[ps] = create(self.all_ + ps.all()) return self.added_[ps]
[ "def", "add", "(", "self", ",", "ps", ")", ":", "if", "not", "self", ".", "added_", ".", "has_key", "(", "ps", ")", ":", "self", ".", "added_", "[", "ps", "]", "=", "create", "(", "self", ".", "all_", "+", "ps", ".", "all", "(", ")", ")", "return", "self", ".", "added_", "[", "ps", "]" ]
https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/property_set.py#L401-L407
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/meta/asttools/visitors/graph_visitor.py
python
make_graph
(node, call_deps=False)
return gen.graph, gen.undefined
Create a dependency graph from an ast node. :param node: ast node. :param call_deps: if true, then the graph will create a cyclic dependence for all function calls. (i.e for `a.b(c)` a depends on b and b depends on a) :returns: a tuple of (graph, undefined)
Create a dependency graph from an ast node.
[ "Create", "a", "dependency", "graph", "from", "an", "ast", "node", "." ]
def make_graph(node, call_deps=False): """ Create a dependency graph from an ast node. :param node: ast node. :param call_deps: if true, then the graph will create a cyclic dependence for all function calls. (i.e for `a.b(c)` a depends on b and b depends on a) :returns: a tuple of (graph, undefined) """ gen = GraphGen(call_deps=call_deps) gen.visit(node) return gen.graph, gen.undefined
[ "def", "make_graph", "(", "node", ",", "call_deps", "=", "False", ")", ":", "gen", "=", "GraphGen", "(", "call_deps", "=", "call_deps", ")", "gen", ".", "visit", "(", "node", ")", "return", "gen", ".", "graph", ",", "gen", ".", "undefined" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/meta/asttools/visitors/graph_visitor.py#L392-L406
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/generator/msvs.py
python
_GetLibraryDirs
(config)
return library_dirs
Returns the list of directories to be used for library search paths. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths.
Returns the list of directories to be used for library search paths.
[ "Returns", "the", "list", "of", "directories", "to", "be", "used", "for", "library", "search", "paths", "." ]
def _GetLibraryDirs(config): """Returns the list of directories to be used for library search paths. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths. """ library_dirs = config.get('library_dirs', []) library_dirs = _FixPaths(library_dirs) return library_dirs
[ "def", "_GetLibraryDirs", "(", "config", ")", ":", "library_dirs", "=", "config", ".", "get", "(", "'library_dirs'", ",", "[", "]", ")", "library_dirs", "=", "_FixPaths", "(", "library_dirs", ")", "return", "library_dirs" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/msvs.py#L1250-L1262
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiManager.DrawHintRect
(*args, **kwargs)
return _aui.AuiManager_DrawHintRect(*args, **kwargs)
DrawHintRect(self, Window paneWindow, Point pt, Point offset)
DrawHintRect(self, Window paneWindow, Point pt, Point offset)
[ "DrawHintRect", "(", "self", "Window", "paneWindow", "Point", "pt", "Point", "offset", ")" ]
def DrawHintRect(*args, **kwargs): """DrawHintRect(self, Window paneWindow, Point pt, Point offset)""" return _aui.AuiManager_DrawHintRect(*args, **kwargs)
[ "def", "DrawHintRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_DrawHintRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L719-L721