repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.respond_file | def respond_file(self, file_path, attachment=False, query=None):
"""
Respond to the client by serving a file, either directly or as
an attachment.
:param str file_path: The path to the file to serve, this does not need to be in the web root.
:param bool attachment: Whether to serve the file as a download by ... | python | def respond_file(self, file_path, attachment=False, query=None):
"""
Respond to the client by serving a file, either directly or as
an attachment.
:param str file_path: The path to the file to serve, this does not need to be in the web root.
:param bool attachment: Whether to serve the file as a download by ... | [
"def",
"respond_file",
"(",
"self",
",",
"file_path",
",",
"attachment",
"=",
"False",
",",
"query",
"=",
"None",
")",
":",
"del",
"query",
"file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"file_path",
")",
"try",
":",
"file_obj",
"=",
"open",... | Respond to the client by serving a file, either directly or as
an attachment.
:param str file_path: The path to the file to serve, this does not need to be in the web root.
:param bool attachment: Whether to serve the file as a download by setting the Content-Disposition header. | [
"Respond",
"to",
"the",
"client",
"by",
"serving",
"a",
"file",
"either",
"directly",
"or",
"as",
"an",
"attachment",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L892-L918 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.respond_list_directory | def respond_list_directory(self, dir_path, query=None):
"""
Respond to the client with an HTML page listing the contents of
the specified directory.
:param str dir_path: The path of the directory to list the contents of.
"""
del query
try:
dir_contents = os.listdir(dir_path)
except os.error:
self... | python | def respond_list_directory(self, dir_path, query=None):
"""
Respond to the client with an HTML page listing the contents of
the specified directory.
:param str dir_path: The path of the directory to list the contents of.
"""
del query
try:
dir_contents = os.listdir(dir_path)
except os.error:
self... | [
"def",
"respond_list_directory",
"(",
"self",
",",
"dir_path",
",",
"query",
"=",
"None",
")",
":",
"del",
"query",
"try",
":",
"dir_contents",
"=",
"os",
".",
"listdir",
"(",
"dir_path",
")",
"except",
"os",
".",
"error",
":",
"self",
".",
"respond_not_... | Respond to the client with an HTML page listing the contents of
the specified directory.
:param str dir_path: The path of the directory to list the contents of. | [
"Respond",
"to",
"the",
"client",
"with",
"an",
"HTML",
"page",
"listing",
"the",
"contents",
"of",
"the",
"specified",
"directory",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L920-L965 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.respond_redirect | def respond_redirect(self, location='/'):
"""
Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to.
"""
self.send_response(301)
self.send_header('Content-Length', 0)
self.send_header('Location', location)
se... | python | def respond_redirect(self, location='/'):
"""
Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to.
"""
self.send_response(301)
self.send_header('Content-Length', 0)
self.send_header('Location', location)
se... | [
"def",
"respond_redirect",
"(",
"self",
",",
"location",
"=",
"'/'",
")",
":",
"self",
".",
"send_response",
"(",
"301",
")",
"self",
".",
"send_header",
"(",
"'Content-Length'",
",",
"0",
")",
"self",
".",
"send_header",
"(",
"'Location'",
",",
"location"... | Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to. | [
"Respond",
"to",
"the",
"client",
"with",
"a",
"301",
"message",
"and",
"redirect",
"them",
"with",
"a",
"Location",
"header",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L972-L983 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.respond_server_error | def respond_server_error(self, status=None, status_line=None, message=None):
"""
Handle an internal server error, logging a traceback if executed
within an exception handler.
:param int status: The status code to respond to the client with.
:param str status_line: The status message to respond to the client ... | python | def respond_server_error(self, status=None, status_line=None, message=None):
"""
Handle an internal server error, logging a traceback if executed
within an exception handler.
:param int status: The status code to respond to the client with.
:param str status_line: The status message to respond to the client ... | [
"def",
"respond_server_error",
"(",
"self",
",",
"status",
"=",
"None",
",",
"status_line",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"(",
"ex_type",
",",
"ex_value",
",",
"ex_traceback",
")",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"ex_... | Handle an internal server error, logging a traceback if executed
within an exception handler.
:param int status: The status code to respond to the client with.
:param str status_line: The status message to respond to the client with.
:param str message: The body of the response that is sent to the client. | [
"Handle",
"an",
"internal",
"server",
"error",
"logging",
"a",
"traceback",
"if",
"executed",
"within",
"an",
"exception",
"handler",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L985-L1018 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.respond_unauthorized | def respond_unauthorized(self, request_authentication=False):
"""
Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header.
"""
headers = {}
if request_authentication:
headers['WWW... | python | def respond_unauthorized(self, request_authentication=False):
"""
Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header.
"""
headers = {}
if request_authentication:
headers['WWW... | [
"def",
"respond_unauthorized",
"(",
"self",
",",
"request_authentication",
"=",
"False",
")",
":",
"headers",
"=",
"{",
"}",
"if",
"request_authentication",
":",
"headers",
"[",
"'WWW-Authenticate'",
"]",
"=",
"'Basic realm=\"'",
"+",
"self",
".",
"__config",
"[... | Respond to the client that the request is unauthorized.
:param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header. | [
"Respond",
"to",
"the",
"client",
"that",
"the",
"request",
"is",
"unauthorized",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1020-L1030 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.dispatch_handler | def dispatch_handler(self, query=None):
"""
Dispatch functions based on the established handler_map. It is
generally not necessary to override this function and doing so
will prevent any handlers from being executed. This function is
executed automatically when requests of either GET, HEAD, or POST
are rece... | python | def dispatch_handler(self, query=None):
"""
Dispatch functions based on the established handler_map. It is
generally not necessary to override this function and doing so
will prevent any handlers from being executed. This function is
executed automatically when requests of either GET, HEAD, or POST
are rece... | [
"def",
"dispatch_handler",
"(",
"self",
",",
"query",
"=",
"None",
")",
":",
"query",
"=",
"(",
"query",
"or",
"{",
"}",
")",
"# normalize the path",
"# abandon query parameters",
"self",
".",
"path",
"=",
"self",
".",
"path",
".",
"split",
"(",
"'?'",
"... | Dispatch functions based on the established handler_map. It is
generally not necessary to override this function and doing so
will prevent any handlers from being executed. This function is
executed automatically when requests of either GET, HEAD, or POST
are received.
:param dict query: Parsed query paramet... | [
"Dispatch",
"functions",
"based",
"on",
"the",
"established",
"handler_map",
".",
"It",
"is",
"generally",
"not",
"necessary",
"to",
"override",
"this",
"function",
"and",
"doing",
"so",
"will",
"prevent",
"any",
"handlers",
"from",
"being",
"executed",
".",
"... | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1032-L1099 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.guess_mime_type | def guess_mime_type(self, path):
"""
Guess an appropriate MIME type based on the extension of the
provided path.
:param str path: The of the file to analyze.
:return: The guessed MIME type of the default if non are found.
:rtype: str
"""
_, ext = posixpath.splitext(path)
if ext in self.extensions_map... | python | def guess_mime_type(self, path):
"""
Guess an appropriate MIME type based on the extension of the
provided path.
:param str path: The of the file to analyze.
:return: The guessed MIME type of the default if non are found.
:rtype: str
"""
_, ext = posixpath.splitext(path)
if ext in self.extensions_map... | [
"def",
"guess_mime_type",
"(",
"self",
",",
"path",
")",
":",
"_",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"ext",
"in",
"self",
".",
"extensions_map",
":",
"return",
"self",
".",
"extensions_map",
"[",
"ext",
"]",
"ext",
... | Guess an appropriate MIME type based on the extension of the
provided path.
:param str path: The of the file to analyze.
:return: The guessed MIME type of the default if non are found.
:rtype: str | [
"Guess",
"an",
"appropriate",
"MIME",
"type",
"based",
"on",
"the",
"extension",
"of",
"the",
"provided",
"path",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1135-L1148 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.check_authorization | def check_authorization(self):
"""
Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool
"""
try:
store = self.__config.get('basic_auth')
if store is None:
return True
... | python | def check_authorization(self):
"""
Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool
"""
try:
store = self.__config.get('basic_auth')
if store is None:
return True
... | [
"def",
"check_authorization",
"(",
"self",
")",
":",
"try",
":",
"store",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"'basic_auth'",
")",
"if",
"store",
"is",
"None",
":",
"return",
"True",
"auth_info",
"=",
"self",
".",
"headers",
".",
"get",
"(",... | Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool | [
"Check",
"for",
"the",
"presence",
"of",
"a",
"basic",
"auth",
"Authorization",
"header",
"and",
"if",
"the",
"credentials",
"contained",
"within",
"in",
"are",
"valid",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1162-L1204 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.cookie_get | def cookie_get(self, name):
"""
Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found.
"""
if not hasattr(self, 'cookies'):
return None
if self.cookies.get(name):
return self.cookies.get(name)... | python | def cookie_get(self, name):
"""
Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found.
"""
if not hasattr(self, 'cookies'):
return None
if self.cookies.get(name):
return self.cookies.get(name)... | [
"def",
"cookie_get",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'cookies'",
")",
":",
"return",
"None",
"if",
"self",
".",
"cookies",
".",
"get",
"(",
"name",
")",
":",
"return",
"self",
".",
"cookies",
".",
"get... | Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found. | [
"Check",
"for",
"a",
"cookie",
"value",
"by",
"name",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1206-L1217 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.cookie_set | def cookie_set(self, name, value):
"""
Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set.
"""
if not self.headers_active:
raise RuntimeError('headers have already b... | python | def cookie_set(self, name, value):
"""
Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set.
"""
if not self.headers_active:
raise RuntimeError('headers have already b... | [
"def",
"cookie_set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"headers_active",
":",
"raise",
"RuntimeError",
"(",
"'headers have already been ended'",
")",
"cookie",
"=",
"\"{0}={1}; Path=/; HttpOnly\"",
".",
"format",
"(",
"n... | Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set. | [
"Set",
"the",
"value",
"of",
"a",
"client",
"cookie",
".",
"This",
"can",
"only",
"be",
"called",
"while",
"headers",
"can",
"be",
"sent",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1219-L1230 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | RequestHandler.get_content_type_charset | def get_content_type_charset(self, default='UTF-8'):
"""
Inspect the Content-Type header to retrieve the charset that the client
has specified.
:param str default: The default charset to return if none exists.
:return: The charset of the request.
:rtype: str
"""
encoding = default
header = self.heade... | python | def get_content_type_charset(self, default='UTF-8'):
"""
Inspect the Content-Type header to retrieve the charset that the client
has specified.
:param str default: The default charset to return if none exists.
:return: The charset of the request.
:rtype: str
"""
encoding = default
header = self.heade... | [
"def",
"get_content_type_charset",
"(",
"self",
",",
"default",
"=",
"'UTF-8'",
")",
":",
"encoding",
"=",
"default",
"header",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"''",
")",
"idx",
"=",
"header",
".",
"find",
"(",
"'char... | Inspect the Content-Type header to retrieve the charset that the client
has specified.
:param str default: The default charset to return if none exists.
:return: The charset of the request.
:rtype: str | [
"Inspect",
"the",
"Content",
"-",
"Type",
"header",
"to",
"retrieve",
"the",
"charset",
"that",
"the",
"client",
"has",
"specified",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1373-L1387 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | WebSocketHandler.close | def close(self):
"""
Close the web socket connection and stop processing results. If the
connection is still open, a WebSocket close message will be sent to the
peer.
"""
if not self.connected:
return
self.connected = False
if self.handler.wfile.closed:
return
if select.select([], [self.handler.... | python | def close(self):
"""
Close the web socket connection and stop processing results. If the
connection is still open, a WebSocket close message will be sent to the
peer.
"""
if not self.connected:
return
self.connected = False
if self.handler.wfile.closed:
return
if select.select([], [self.handler.... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"return",
"self",
".",
"connected",
"=",
"False",
"if",
"self",
".",
"handler",
".",
"wfile",
".",
"closed",
":",
"return",
"if",
"select",
".",
"select",
"(",
"[",
... | Close the web socket connection and stop processing results. If the
connection is still open, a WebSocket close message will be sent to the
peer. | [
"Close",
"the",
"web",
"socket",
"connection",
"and",
"stop",
"processing",
"results",
".",
"If",
"the",
"connection",
"is",
"still",
"open",
"a",
"WebSocket",
"close",
"message",
"will",
"be",
"sent",
"to",
"the",
"peer",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1521-L1536 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | WebSocketHandler.send_message | def send_message(self, opcode, message):
"""
Send a message to the peer over the socket.
:param int opcode: The opcode for the message to send.
:param bytes message: The message data to send.
"""
if not isinstance(message, bytes):
message = message.encode('utf-8')
length = len(message)
if not select... | python | def send_message(self, opcode, message):
"""
Send a message to the peer over the socket.
:param int opcode: The opcode for the message to send.
:param bytes message: The message data to send.
"""
if not isinstance(message, bytes):
message = message.encode('utf-8')
length = len(message)
if not select... | [
"def",
"send_message",
"(",
"self",
",",
"opcode",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"bytes",
")",
":",
"message",
"=",
"message",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"message",
")",
... | Send a message to the peer over the socket.
:param int opcode: The opcode for the message to send.
:param bytes message: The message data to send. | [
"Send",
"a",
"message",
"to",
"the",
"peer",
"over",
"the",
"socket",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1538-L1570 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | WebSocketHandler.on_message | def on_message(self, opcode, message):
"""
The primary dispatch function to handle incoming WebSocket messages.
:param int opcode: The opcode of the message that was received.
:param bytes message: The data contained within the message.
"""
self.logger.debug("processing {0} (opcode: 0x{1:02x}) message".for... | python | def on_message(self, opcode, message):
"""
The primary dispatch function to handle incoming WebSocket messages.
:param int opcode: The opcode of the message that was received.
:param bytes message: The data contained within the message.
"""
self.logger.debug("processing {0} (opcode: 0x{1:02x}) message".for... | [
"def",
"on_message",
"(",
"self",
",",
"opcode",
",",
"message",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"processing {0} (opcode: 0x{1:02x}) message\"",
".",
"format",
"(",
"self",
".",
"_opcode_names",
".",
"get",
"(",
"opcode",
",",
"'UNKNOWN'"... | The primary dispatch function to handle incoming WebSocket messages.
:param int opcode: The opcode of the message that was received.
:param bytes message: The data contained within the message. | [
"The",
"primary",
"dispatch",
"function",
"to",
"handle",
"incoming",
"WebSocket",
"messages",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1595-L1626 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | Serializer.from_content_type | def from_content_type(cls, content_type):
"""
Build a serializer object from a MIME Content-Type string.
:param str content_type: The Content-Type string to parse.
:return: A new serializer instance.
:rtype: :py:class:`.Serializer`
"""
name = content_type
options = {}
if ';' in content_type:
name,... | python | def from_content_type(cls, content_type):
"""
Build a serializer object from a MIME Content-Type string.
:param str content_type: The Content-Type string to parse.
:return: A new serializer instance.
:rtype: :py:class:`.Serializer`
"""
name = content_type
options = {}
if ';' in content_type:
name,... | [
"def",
"from_content_type",
"(",
"cls",
",",
"content_type",
")",
":",
"name",
"=",
"content_type",
"options",
"=",
"{",
"}",
"if",
"';'",
"in",
"content_type",
":",
"name",
",",
"options_str",
"=",
"content_type",
".",
"split",
"(",
"';'",
",",
"1",
")"... | Build a serializer object from a MIME Content-Type string.
:param str content_type: The Content-Type string to parse.
:return: A new serializer instance.
:rtype: :py:class:`.Serializer` | [
"Build",
"a",
"serializer",
"object",
"from",
"a",
"MIME",
"Content",
"-",
"Type",
"string",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1669-L1692 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | Serializer.dumps | def dumps(self, data):
"""
Serialize a python data type for transmission or storage.
:param data: The python object to serialize.
:return: The serialized representation of the object.
:rtype: bytes
"""
data = g_serializer_drivers[self.name]['dumps'](data)
if sys.version_info[0] == 3 and isinstance(data... | python | def dumps(self, data):
"""
Serialize a python data type for transmission or storage.
:param data: The python object to serialize.
:return: The serialized representation of the object.
:rtype: bytes
"""
data = g_serializer_drivers[self.name]['dumps'](data)
if sys.version_info[0] == 3 and isinstance(data... | [
"def",
"dumps",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"g_serializer_drivers",
"[",
"self",
".",
"name",
"]",
"[",
"'dumps'",
"]",
"(",
"data",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
"and",
"isinstance",
"(",
"da... | Serialize a python data type for transmission or storage.
:param data: The python object to serialize.
:return: The serialized representation of the object.
:rtype: bytes | [
"Serialize",
"a",
"python",
"data",
"type",
"for",
"transmission",
"or",
"storage",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1694-L1708 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | Serializer.loads | def loads(self, data):
"""
Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object.
"""
if not isinstance(data, bytes):
raise TypeError("loads() argument 1 must be bytes, not {0}".format(type(data).__name__))
if self.... | python | def loads(self, data):
"""
Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object.
"""
if not isinstance(data, bytes):
raise TypeError("loads() argument 1 must be bytes, not {0}".format(type(data).__name__))
if self.... | [
"def",
"loads",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"loads() argument 1 must be bytes, not {0}\"",
".",
"format",
"(",
"type",
"(",
"data",
")",
".",
"__name__",
"... | Deserialize the data into it's original python object.
:param bytes data: The serialized object to load.
:return: The original python object. | [
"Deserialize",
"the",
"data",
"into",
"it",
"s",
"original",
"python",
"object",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1710-L1726 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.add_sni_cert | def add_sni_cert(self, hostname, ssl_certfile=None, ssl_keyfile=None, ssl_version=None):
"""
Add an SSL certificate for a specific hostname as supported by SSL's
Server Name Indicator (SNI) extension. See :rfc:`3546` for more details
on SSL extensions. In order to use this method, the server instance must
hav... | python | def add_sni_cert(self, hostname, ssl_certfile=None, ssl_keyfile=None, ssl_version=None):
"""
Add an SSL certificate for a specific hostname as supported by SSL's
Server Name Indicator (SNI) extension. See :rfc:`3546` for more details
on SSL extensions. In order to use this method, the server instance must
hav... | [
"def",
"add_sni_cert",
"(",
"self",
",",
"hostname",
",",
"ssl_certfile",
"=",
"None",
",",
"ssl_keyfile",
"=",
"None",
",",
"ssl_version",
"=",
"None",
")",
":",
"if",
"not",
"g_ssl_has_server_sni",
":",
"raise",
"RuntimeError",
"(",
"'the ssl server name indic... | Add an SSL certificate for a specific hostname as supported by SSL's
Server Name Indicator (SNI) extension. See :rfc:`3546` for more details
on SSL extensions. In order to use this method, the server instance must
have been initialized with at least one address configured for SSL.
.. warning::
This method ... | [
"Add",
"an",
"SSL",
"certificate",
"for",
"a",
"specific",
"hostname",
"as",
"supported",
"by",
"SSL",
"s",
"Server",
"Name",
"Indicator",
"(",
"SNI",
")",
"extension",
".",
"See",
":",
"rfc",
":",
"3546",
"for",
"more",
"details",
"on",
"SSL",
"extensio... | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1844-L1878 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.remove_sni_cert | def remove_sni_cert(self, hostname):
"""
Remove the SSL Server Name Indicator (SNI) certificate configuration for
the specified *hostname*.
.. warning::
This method will raise a :py:exc:`RuntimeError` if either the SNI
extension is not available in the :py:mod:`ssl` module or if SSL was
not enabled a... | python | def remove_sni_cert(self, hostname):
"""
Remove the SSL Server Name Indicator (SNI) certificate configuration for
the specified *hostname*.
.. warning::
This method will raise a :py:exc:`RuntimeError` if either the SNI
extension is not available in the :py:mod:`ssl` module or if SSL was
not enabled a... | [
"def",
"remove_sni_cert",
"(",
"self",
",",
"hostname",
")",
":",
"if",
"not",
"g_ssl_has_server_sni",
":",
"raise",
"RuntimeError",
"(",
"'the ssl server name indicator extension is unavailable'",
")",
"if",
"self",
".",
"_ssl_sni_entries",
"is",
"None",
":",
"raise"... | Remove the SSL Server Name Indicator (SNI) certificate configuration for
the specified *hostname*.
.. warning::
This method will raise a :py:exc:`RuntimeError` if either the SNI
extension is not available in the :py:mod:`ssl` module or if SSL was
not enabled at initialization time through the use of argu... | [
"Remove",
"the",
"SSL",
"Server",
"Name",
"Indicator",
"(",
"SNI",
")",
"certificate",
"configuration",
"for",
"the",
"specified",
"*",
"hostname",
"*",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1880-L1902 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.sni_certs | def sni_certs(self):
"""
.. versionadded:: 2.2.0
:return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates that are configured.
:rtype: tuple
"""
if not g_ssl_has_server_sni or self._ssl_sni_entries is None:
return tuple()
return tuple(entry.certificate for entr... | python | def sni_certs(self):
"""
.. versionadded:: 2.2.0
:return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates that are configured.
:rtype: tuple
"""
if not g_ssl_has_server_sni or self._ssl_sni_entries is None:
return tuple()
return tuple(entry.certificate for entr... | [
"def",
"sni_certs",
"(",
"self",
")",
":",
"if",
"not",
"g_ssl_has_server_sni",
"or",
"self",
".",
"_ssl_sni_entries",
"is",
"None",
":",
"return",
"tuple",
"(",
")",
"return",
"tuple",
"(",
"entry",
".",
"certificate",
"for",
"entry",
"in",
"self",
".",
... | .. versionadded:: 2.2.0
:return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates that are configured.
:rtype: tuple | [
"..",
"versionadded",
"::",
"2",
".",
"2",
".",
"0"
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1905-L1914 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.serve_forever | def serve_forever(self, fork=False):
"""
Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
... | python | def serve_forever(self, fork=False):
"""
Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
... | [
"def",
"serve_forever",
"(",
"self",
",",
"fork",
"=",
"False",
")",
":",
"if",
"fork",
":",
"if",
"not",
"hasattr",
"(",
"os",
",",
"'fork'",
")",
":",
"raise",
"OSError",
"(",
"'os.fork is not available'",
")",
"child_pid",
"=",
"os",
".",
"fork",
"(... | Start handling requests. This method must be called and does not
return unless the :py:meth:`.shutdown` method is called from
another thread.
:param bool fork: Whether to fork or not before serving content.
:return: The child processes PID if *fork* is set to True.
:rtype: int | [
"Start",
"handling",
"requests",
".",
"This",
"method",
"must",
"be",
"called",
"and",
"does",
"not",
"return",
"unless",
"the",
":",
"py",
":",
"meth",
":",
".",
"shutdown",
"method",
"is",
"called",
"from",
"another",
"thread",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1929-L1959 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.shutdown | def shutdown(self):
"""Shutdown the server and stop responding to requests."""
self.__should_stop.set()
if self.__server_thread == threading.current_thread():
self.__is_shutdown.set()
self.__is_running.clear()
else:
if self.__wakeup_fd is not None:
os.write(self.__wakeup_fd.write_fd, b'\x00')
se... | python | def shutdown(self):
"""Shutdown the server and stop responding to requests."""
self.__should_stop.set()
if self.__server_thread == threading.current_thread():
self.__is_shutdown.set()
self.__is_running.clear()
else:
if self.__wakeup_fd is not None:
os.write(self.__wakeup_fd.write_fd, b'\x00')
se... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"__should_stop",
".",
"set",
"(",
")",
"if",
"self",
".",
"__server_thread",
"==",
"threading",
".",
"current_thread",
"(",
")",
":",
"self",
".",
"__is_shutdown",
".",
"set",
"(",
")",
"self",
"."... | Shutdown the server and stop responding to requests. | [
"Shutdown",
"the",
"server",
"and",
"stop",
"responding",
"to",
"requests",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1961-L1975 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.auth_set | def auth_set(self, status):
"""
Enable or disable requiring authentication on all incoming requests.
:param bool status: Whether to enable or disable requiring authentication.
"""
if not bool(status):
self.__config['basic_auth'] = None
self.logger.info('basic authentication has been disabled')
else:
... | python | def auth_set(self, status):
"""
Enable or disable requiring authentication on all incoming requests.
:param bool status: Whether to enable or disable requiring authentication.
"""
if not bool(status):
self.__config['basic_auth'] = None
self.logger.info('basic authentication has been disabled')
else:
... | [
"def",
"auth_set",
"(",
"self",
",",
"status",
")",
":",
"if",
"not",
"bool",
"(",
"status",
")",
":",
"self",
".",
"__config",
"[",
"'basic_auth'",
"]",
"=",
"None",
"self",
".",
"logger",
".",
"info",
"(",
"'basic authentication has been disabled'",
")",... | Enable or disable requiring authentication on all incoming requests.
:param bool status: Whether to enable or disable requiring authentication. | [
"Enable",
"or",
"disable",
"requiring",
"authentication",
"on",
"all",
"incoming",
"requests",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L2050-L2061 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.auth_delete_creds | def auth_delete_creds(self, username=None):
"""
Delete the credentials for a specific username if specified or all
stored credentials.
:param str username: The username of the credentials to delete.
"""
if not username:
self.__config['basic_auth'] = {}
self.logger.info('basic authentication database ... | python | def auth_delete_creds(self, username=None):
"""
Delete the credentials for a specific username if specified or all
stored credentials.
:param str username: The username of the credentials to delete.
"""
if not username:
self.__config['basic_auth'] = {}
self.logger.info('basic authentication database ... | [
"def",
"auth_delete_creds",
"(",
"self",
",",
"username",
"=",
"None",
")",
":",
"if",
"not",
"username",
":",
"self",
".",
"__config",
"[",
"'basic_auth'",
"]",
"=",
"{",
"}",
"self",
".",
"logger",
".",
"info",
"(",
"'basic authentication database has been... | Delete the credentials for a specific username if specified or all
stored credentials.
:param str username: The username of the credentials to delete. | [
"Delete",
"the",
"credentials",
"for",
"a",
"specific",
"username",
"if",
"specified",
"or",
"all",
"stored",
"credentials",
"."
] | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L2063-L2074 | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | AdvancedHTTPServer.auth_add_creds | def auth_add_creds(self, username, password, pwtype='plain'):
"""
Add a valid set of credentials to be accepted for authentication.
Calling this function will automatically enable requiring
authentication. Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the *pwtype* a... | python | def auth_add_creds(self, username, password, pwtype='plain'):
"""
Add a valid set of credentials to be accepted for authentication.
Calling this function will automatically enable requiring
authentication. Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the *pwtype* a... | [
"def",
"auth_add_creds",
"(",
"self",
",",
"username",
",",
"password",
",",
"pwtype",
"=",
"'plain'",
")",
":",
"if",
"not",
"isinstance",
"(",
"password",
",",
"(",
"bytes",
",",
"str",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"auth_add_creds() argume... | Add a valid set of credentials to be accepted for authentication.
Calling this function will automatically enable requiring
authentication. Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the *pwtype* argument.
:param str username: The username of the credentials to be... | [
"Add",
"a",
"valid",
"set",
"of",
"credentials",
"to",
"be",
"accepted",
"for",
"authentication",
".",
"Calling",
"this",
"function",
"will",
"automatically",
"enable",
"requiring",
"authentication",
".",
"Passwords",
"can",
"be",
"provided",
"in",
"either",
"pl... | 8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L2076-L2109 | train |
jakevdp/supersmoother | supersmoother/utils.py | setattr_context | def setattr_context(obj, **kwargs):
"""
Context manager to temporarily change the values of object attributes
while executing a function.
Example
-------
>>> class Foo: pass
>>> f = Foo(); f.attr = 'hello'
>>> with setattr_context(f, attr='goodbye'):
... print(f.attr)
goodby... | python | def setattr_context(obj, **kwargs):
"""
Context manager to temporarily change the values of object attributes
while executing a function.
Example
-------
>>> class Foo: pass
>>> f = Foo(); f.attr = 'hello'
>>> with setattr_context(f, attr='goodbye'):
... print(f.attr)
goodby... | [
"def",
"setattr_context",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"old_kwargs",
"=",
"dict",
"(",
"[",
"(",
"key",
",",
"getattr",
"(",
"obj",
",",
"key",
")",
")",
"for",
"key",
"in",
"kwargs",
"]",
")",
"[",
"setattr",
"(",
"obj",
",",
... | Context manager to temporarily change the values of object attributes
while executing a function.
Example
-------
>>> class Foo: pass
>>> f = Foo(); f.attr = 'hello'
>>> with setattr_context(f, attr='goodbye'):
... print(f.attr)
goodbye
>>> print(f.attr)
hello | [
"Context",
"manager",
"to",
"temporarily",
"change",
"the",
"values",
"of",
"object",
"attributes",
"while",
"executing",
"a",
"function",
"."
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/utils.py#L10-L30 | train |
jakevdp/supersmoother | supersmoother/utils.py | validate_inputs | def validate_inputs(*arrays, **kwargs):
"""Validate input arrays
This checks that
- Arrays are mutually broadcastable
- Broadcasted arrays are one-dimensional
Optionally, arrays are sorted according to the ``sort_by`` argument.
Parameters
----------
*args : ndarrays
All non-ke... | python | def validate_inputs(*arrays, **kwargs):
"""Validate input arrays
This checks that
- Arrays are mutually broadcastable
- Broadcasted arrays are one-dimensional
Optionally, arrays are sorted according to the ``sort_by`` argument.
Parameters
----------
*args : ndarrays
All non-ke... | [
"def",
"validate_inputs",
"(",
"*",
"arrays",
",",
"*",
"*",
"kwargs",
")",
":",
"arrays",
"=",
"np",
".",
"broadcast_arrays",
"(",
"*",
"arrays",
")",
"sort_by",
"=",
"kwargs",
".",
"pop",
"(",
"'sort_by'",
",",
"None",
")",
"if",
"kwargs",
":",
"ra... | Validate input arrays
This checks that
- Arrays are mutually broadcastable
- Broadcasted arrays are one-dimensional
Optionally, arrays are sorted according to the ``sort_by`` argument.
Parameters
----------
*args : ndarrays
All non-keyword arguments are arrays which will be valida... | [
"Validate",
"input",
"arrays"
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/utils.py#L43-L73 | train |
jakevdp/supersmoother | supersmoother/utils.py | _prep_smooth | def _prep_smooth(t, y, dy, span, t_out, span_out, period):
"""Private function to prepare & check variables for smooth utilities"""
# If period is provided, sort by phases. Otherwise sort by t
if period:
t = t % period
if t_out is not None:
t_out = t_out % period
t, y, dy =... | python | def _prep_smooth(t, y, dy, span, t_out, span_out, period):
"""Private function to prepare & check variables for smooth utilities"""
# If period is provided, sort by phases. Otherwise sort by t
if period:
t = t % period
if t_out is not None:
t_out = t_out % period
t, y, dy =... | [
"def",
"_prep_smooth",
"(",
"t",
",",
"y",
",",
"dy",
",",
"span",
",",
"t_out",
",",
"span_out",
",",
"period",
")",
":",
"# If period is provided, sort by phases. Otherwise sort by t",
"if",
"period",
":",
"t",
"=",
"t",
"%",
"period",
"if",
"t_out",
"is",... | Private function to prepare & check variables for smooth utilities | [
"Private",
"function",
"to",
"prepare",
"&",
"check",
"variables",
"for",
"smooth",
"utilities"
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/utils.py#L76-L99 | train |
jakevdp/supersmoother | supersmoother/utils.py | moving_average_smooth | def moving_average_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a moving-average smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
t... | python | def moving_average_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a moving-average smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
t... | [
"def",
"moving_average_smooth",
"(",
"t",
",",
"y",
",",
"dy",
",",
"span",
"=",
"None",
",",
"cv",
"=",
"True",
",",
"t_out",
"=",
"None",
",",
"span_out",
"=",
"None",
",",
"period",
"=",
"None",
")",
":",
"prep",
"=",
"_prep_smooth",
"(",
"t",
... | Perform a moving-average smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the data
cv : boolean (default=True)
if True, treat the problem as a cross-validation, i.e. don't ... | [
"Perform",
"a",
"moving",
"-",
"average",
"smooth",
"of",
"the",
"data"
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/utils.py#L102-L138 | train |
jakevdp/supersmoother | supersmoother/utils.py | linear_smooth | def linear_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a linear smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the ... | python | def linear_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a linear smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the ... | [
"def",
"linear_smooth",
"(",
"t",
",",
"y",
",",
"dy",
",",
"span",
"=",
"None",
",",
"cv",
"=",
"True",
",",
"t_out",
"=",
"None",
",",
"span_out",
"=",
"None",
",",
"period",
"=",
"None",
")",
":",
"t_input",
"=",
"t",
"prep",
"=",
"_prep_smoot... | Perform a linear smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
the integer spans of the data
cv : boolean (default=True)
if True, treat the problem as a cross-validation, i.e. don't use
... | [
"Perform",
"a",
"linear",
"smooth",
"of",
"the",
"data"
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/utils.py#L141-L192 | train |
jakevdp/supersmoother | supersmoother/utils.py | multinterp | def multinterp(x, y, xquery, slow=False):
"""Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of que... | python | def multinterp(x, y, xquery, slow=False):
"""Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of que... | [
"def",
"multinterp",
"(",
"x",
",",
"y",
",",
"xquery",
",",
"slow",
"=",
"False",
")",
":",
"x",
",",
"y",
",",
"xquery",
"=",
"map",
"(",
"np",
".",
"asarray",
",",
"(",
"x",
",",
"y",
",",
"xquery",
")",
")",
"assert",
"x",
".",
"ndim",
... | Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of query values
slow : boolean, default=False
... | [
"Multiple",
"linear",
"interpolations"
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/utils.py#L195-L235 | train |
vsudilov/flask-consulate | flask_consulate/consul.py | Consul._create_session | def _create_session(self, test_connection=False):
"""
Create a consulate.session object, and query for its leader to ensure
that the connection is made.
:param test_connection: call .leader() to ensure that the connection
is valid
:type test_connection: bool
... | python | def _create_session(self, test_connection=False):
"""
Create a consulate.session object, and query for its leader to ensure
that the connection is made.
:param test_connection: call .leader() to ensure that the connection
is valid
:type test_connection: bool
... | [
"def",
"_create_session",
"(",
"self",
",",
"test_connection",
"=",
"False",
")",
":",
"session",
"=",
"consulate",
".",
"Session",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
")",
"if",
"test_connection",
":",
"session"... | Create a consulate.session object, and query for its leader to ensure
that the connection is made.
:param test_connection: call .leader() to ensure that the connection
is valid
:type test_connection: bool
:return consulate.Session instance | [
"Create",
"a",
"consulate",
".",
"session",
"object",
"and",
"query",
"for",
"its",
"leader",
"to",
"ensure",
"that",
"the",
"connection",
"is",
"made",
"."
] | 514f8754e7186f960237ed2836206993d5d3d3b6 | https://github.com/vsudilov/flask-consulate/blob/514f8754e7186f960237ed2836206993d5d3d3b6/flask_consulate/consul.py#L62-L75 | train |
vsudilov/flask-consulate | flask_consulate/consul.py | Consul.apply_remote_config | def apply_remote_config(self, namespace=None):
"""
Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_... | python | def apply_remote_config(self, namespace=None):
"""
Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_... | [
"def",
"apply_remote_config",
"(",
"self",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"\"config/{service}/{environment}/\"",
".",
"format",
"(",
"service",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SE... | Applies all config values defined in consul's kv store to self.app.
There is no guarantee that these values will not be overwritten later
elsewhere.
:param namespace: kv namespace/directory. Defaults to
DEFAULT_KV_NAMESPACE
:return: None | [
"Applies",
"all",
"config",
"values",
"defined",
"in",
"consul",
"s",
"kv",
"store",
"to",
"self",
".",
"app",
"."
] | 514f8754e7186f960237ed2836206993d5d3d3b6 | https://github.com/vsudilov/flask-consulate/blob/514f8754e7186f960237ed2836206993d5d3d3b6/flask_consulate/consul.py#L78-L109 | train |
vsudilov/flask-consulate | flask_consulate/consul.py | Consul.register_service | def register_service(self, **kwargs):
"""
register this service with consul
kwargs passed to Consul.agent.service.register
"""
kwargs.setdefault('name', self.app.name)
self.session.agent.service.register(**kwargs) | python | def register_service(self, **kwargs):
"""
register this service with consul
kwargs passed to Consul.agent.service.register
"""
kwargs.setdefault('name', self.app.name)
self.session.agent.service.register(**kwargs) | [
"def",
"register_service",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'name'",
",",
"self",
".",
"app",
".",
"name",
")",
"self",
".",
"session",
".",
"agent",
".",
"service",
".",
"register",
"(",
"*",
"*",
... | register this service with consul
kwargs passed to Consul.agent.service.register | [
"register",
"this",
"service",
"with",
"consul",
"kwargs",
"passed",
"to",
"Consul",
".",
"agent",
".",
"service",
".",
"register"
] | 514f8754e7186f960237ed2836206993d5d3d3b6 | https://github.com/vsudilov/flask-consulate/blob/514f8754e7186f960237ed2836206993d5d3d3b6/flask_consulate/consul.py#L112-L118 | train |
vsudilov/flask-consulate | flask_consulate/service.py | ConsulService._resolve | def _resolve(self):
"""
Query the consul DNS server for the service IP and port
"""
endpoints = {}
r = self.resolver.query(self.service, 'SRV')
for rec in r.response.additional:
name = rec.name.to_text()
addr = rec.items[0].address
endp... | python | def _resolve(self):
"""
Query the consul DNS server for the service IP and port
"""
endpoints = {}
r = self.resolver.query(self.service, 'SRV')
for rec in r.response.additional:
name = rec.name.to_text()
addr = rec.items[0].address
endp... | [
"def",
"_resolve",
"(",
"self",
")",
":",
"endpoints",
"=",
"{",
"}",
"r",
"=",
"self",
".",
"resolver",
".",
"query",
"(",
"self",
".",
"service",
",",
"'SRV'",
")",
"for",
"rec",
"in",
"r",
".",
"response",
".",
"additional",
":",
"name",
"=",
... | Query the consul DNS server for the service IP and port | [
"Query",
"the",
"consul",
"DNS",
"server",
"for",
"the",
"service",
"IP",
"and",
"port"
] | 514f8754e7186f960237ed2836206993d5d3d3b6 | https://github.com/vsudilov/flask-consulate/blob/514f8754e7186f960237ed2836206993d5d3d3b6/flask_consulate/service.py#L55-L72 | train |
vsudilov/flask-consulate | flask_consulate/service.py | ConsulService.request | def request(self, method, endpoint, **kwargs):
"""
Proxy to requests.request
:param method: str formatted http method
:param endpoint: service endpoint
:param kwargs: kwargs passed directly to requests.request
:return:
"""
kwargs.setdefault('timeout', (1, ... | python | def request(self, method, endpoint, **kwargs):
"""
Proxy to requests.request
:param method: str formatted http method
:param endpoint: service endpoint
:param kwargs: kwargs passed directly to requests.request
:return:
"""
kwargs.setdefault('timeout', (1, ... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'timeout'",
",",
"(",
"1",
",",
"30",
")",
")",
"return",
"self",
".",
"session",
".",
"request",
"(",
"method",
",... | Proxy to requests.request
:param method: str formatted http method
:param endpoint: service endpoint
:param kwargs: kwargs passed directly to requests.request
:return: | [
"Proxy",
"to",
"requests",
".",
"request",
":",
"param",
"method",
":",
"str",
"formatted",
"http",
"method",
":",
"param",
"endpoint",
":",
"service",
"endpoint",
":",
"param",
"kwargs",
":",
"kwargs",
"passed",
"directly",
"to",
"requests",
".",
"request",... | 514f8754e7186f960237ed2836206993d5d3d3b6 | https://github.com/vsudilov/flask-consulate/blob/514f8754e7186f960237ed2836206993d5d3d3b6/flask_consulate/service.py#L82-L95 | train |
vsudilov/flask-consulate | flask_consulate/decorators.py | with_retry_connections | def with_retry_connections(max_tries=3, sleep=0.05):
"""
Decorator that wraps an entire function in a try/except clause. On
requests.exceptions.ConnectionError, will re-run the function code
until success or max_tries is reached.
:param max_tries: maximum number of attempts before giving up
:pa... | python | def with_retry_connections(max_tries=3, sleep=0.05):
"""
Decorator that wraps an entire function in a try/except clause. On
requests.exceptions.ConnectionError, will re-run the function code
until success or max_tries is reached.
:param max_tries: maximum number of attempts before giving up
:pa... | [
"def",
"with_retry_connections",
"(",
"max_tries",
"=",
"3",
",",
"sleep",
"=",
"0.05",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"f_retry",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | Decorator that wraps an entire function in a try/except clause. On
requests.exceptions.ConnectionError, will re-run the function code
until success or max_tries is reached.
:param max_tries: maximum number of attempts before giving up
:param sleep: time to sleep between tries, or None | [
"Decorator",
"that",
"wraps",
"an",
"entire",
"function",
"in",
"a",
"try",
"/",
"except",
"clause",
".",
"On",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"will",
"re",
"-",
"run",
"the",
"function",
"code",
"until",
"success",
"or",
"max_tries",... | 514f8754e7186f960237ed2836206993d5d3d3b6 | https://github.com/vsudilov/flask-consulate/blob/514f8754e7186f960237ed2836206993d5d3d3b6/flask_consulate/decorators.py#L11-L34 | train |
casebeer/audiogen | audiogen/util.py | crop | def crop(gens, seconds=5, cropper=None):
'''
Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate.
'''
if hasattr(gens, "next"):
# single generator
gens = ... | python | def crop(gens, seconds=5, cropper=None):
'''
Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate.
'''
if hasattr(gens, "next"):
# single generator
gens = ... | [
"def",
"crop",
"(",
"gens",
",",
"seconds",
"=",
"5",
",",
"cropper",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"gens",
",",
"\"next\"",
")",
":",
"# single generator",
"gens",
"=",
"(",
"gens",
",",
")",
"if",
"cropper",
"==",
"None",
":",
"cro... | Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate. | [
"Crop",
"the",
"generator",
"to",
"a",
"finite",
"number",
"of",
"frames"
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/util.py#L15-L31 | train |
casebeer/audiogen | audiogen/util.py | crop_at_zero_crossing | def crop_at_zero_crossing(gen, seconds=5, error=0.1):
'''
Crop the generator, ending at a zero-crossing
Crop the generator to produce approximately seconds seconds
(default 5s) of audio at the provided FRAME_RATE, attempting
to end the clip at a zero crossing point to avoid clicking.
'''
source = iter(gen)
... | python | def crop_at_zero_crossing(gen, seconds=5, error=0.1):
'''
Crop the generator, ending at a zero-crossing
Crop the generator to produce approximately seconds seconds
(default 5s) of audio at the provided FRAME_RATE, attempting
to end the clip at a zero crossing point to avoid clicking.
'''
source = iter(gen)
... | [
"def",
"crop_at_zero_crossing",
"(",
"gen",
",",
"seconds",
"=",
"5",
",",
"error",
"=",
"0.1",
")",
":",
"source",
"=",
"iter",
"(",
"gen",
")",
"buffer_length",
"=",
"int",
"(",
"2",
"*",
"error",
"*",
"sampler",
".",
"FRAME_RATE",
")",
"# split the ... | Crop the generator, ending at a zero-crossing
Crop the generator to produce approximately seconds seconds
(default 5s) of audio at the provided FRAME_RATE, attempting
to end the clip at a zero crossing point to avoid clicking. | [
"Crop",
"the",
"generator",
"ending",
"at",
"a",
"zero",
"-",
"crossing"
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/util.py#L86-L123 | train |
casebeer/audiogen | audiogen/util.py | volume | def volume(gen, dB=0):
'''Change the volume of gen by dB decibles'''
if not hasattr(dB, 'next'):
# not a generator
scale = 10 ** (dB / 20.)
else:
def scale_gen():
while True:
yield 10 ** (next(dB) / 20.)
scale = scale_gen()
return envelope(gen, scale) | python | def volume(gen, dB=0):
'''Change the volume of gen by dB decibles'''
if not hasattr(dB, 'next'):
# not a generator
scale = 10 ** (dB / 20.)
else:
def scale_gen():
while True:
yield 10 ** (next(dB) / 20.)
scale = scale_gen()
return envelope(gen, scale) | [
"def",
"volume",
"(",
"gen",
",",
"dB",
"=",
"0",
")",
":",
"if",
"not",
"hasattr",
"(",
"dB",
",",
"'next'",
")",
":",
"# not a generator",
"scale",
"=",
"10",
"**",
"(",
"dB",
"/",
"20.",
")",
"else",
":",
"def",
"scale_gen",
"(",
")",
":",
"... | Change the volume of gen by dB decibles | [
"Change",
"the",
"volume",
"of",
"gen",
"by",
"dB",
"decibles"
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/util.py#L161-L171 | train |
casebeer/audiogen | audiogen/util.py | mixer | def mixer(inputs, mix=None):
'''
Mix `inputs` together based on `mix` tuple
`inputs` should be a tuple of *n* generators.
`mix` should be a tuple of *m* tuples, one per desired
output channel. Each of the *m* tuples should contain
*n* generators, corresponding to the time-sequence of
the desired mix levels f... | python | def mixer(inputs, mix=None):
'''
Mix `inputs` together based on `mix` tuple
`inputs` should be a tuple of *n* generators.
`mix` should be a tuple of *m* tuples, one per desired
output channel. Each of the *m* tuples should contain
*n* generators, corresponding to the time-sequence of
the desired mix levels f... | [
"def",
"mixer",
"(",
"inputs",
",",
"mix",
"=",
"None",
")",
":",
"if",
"mix",
"==",
"None",
":",
"# by default, mix all inputs down to one channel",
"mix",
"=",
"(",
"[",
"constant",
"(",
"1.0",
"/",
"len",
"(",
"inputs",
")",
")",
"]",
"*",
"len",
"(... | Mix `inputs` together based on `mix` tuple
`inputs` should be a tuple of *n* generators.
`mix` should be a tuple of *m* tuples, one per desired
output channel. Each of the *m* tuples should contain
*n* generators, corresponding to the time-sequence of
the desired mix levels for each of the *n* input channels.
... | [
"Mix",
"inputs",
"together",
"based",
"on",
"mix",
"tuple"
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/util.py#L199-L250 | train |
casebeer/audiogen | audiogen/util.py | channelize | def channelize(gen, channels):
'''
Break multi-channel generator into one sub-generator per channel
Takes a generator producing n-tuples of samples and returns n generators,
each producing samples for a single channel.
Since multi-channel generators are the only reasonable way to synchronize samples
across chan... | python | def channelize(gen, channels):
'''
Break multi-channel generator into one sub-generator per channel
Takes a generator producing n-tuples of samples and returns n generators,
each producing samples for a single channel.
Since multi-channel generators are the only reasonable way to synchronize samples
across chan... | [
"def",
"channelize",
"(",
"gen",
",",
"channels",
")",
":",
"def",
"pick",
"(",
"g",
",",
"channel",
")",
":",
"for",
"samples",
"in",
"g",
":",
"yield",
"samples",
"[",
"channel",
"]",
"return",
"[",
"pick",
"(",
"gen_copy",
",",
"channel",
")",
"... | Break multi-channel generator into one sub-generator per channel
Takes a generator producing n-tuples of samples and returns n generators,
each producing samples for a single channel.
Since multi-channel generators are the only reasonable way to synchronize samples
across channels, and the sampler functions only ... | [
"Break",
"multi",
"-",
"channel",
"generator",
"into",
"one",
"sub",
"-",
"generator",
"per",
"channel"
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/util.py#L252-L266 | train |
casebeer/audiogen | audiogen/sampler.py | file_is_seekable | def file_is_seekable(f):
'''
Returns True if file `f` is seekable, and False if not
Useful to determine, for example, if `f` is STDOUT to
a pipe.
'''
try:
f.tell()
logger.info("File is seekable!")
except IOError, e:
if e.errno == errno.ESPIPE:
return False
else:
raise
return True | python | def file_is_seekable(f):
'''
Returns True if file `f` is seekable, and False if not
Useful to determine, for example, if `f` is STDOUT to
a pipe.
'''
try:
f.tell()
logger.info("File is seekable!")
except IOError, e:
if e.errno == errno.ESPIPE:
return False
else:
raise
return True | [
"def",
"file_is_seekable",
"(",
"f",
")",
":",
"try",
":",
"f",
".",
"tell",
"(",
")",
"logger",
".",
"info",
"(",
"\"File is seekable!\"",
")",
"except",
"IOError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ESPIPE",
":",
"return",... | Returns True if file `f` is seekable, and False if not
Useful to determine, for example, if `f` is STDOUT to
a pipe. | [
"Returns",
"True",
"if",
"file",
"f",
"is",
"seekable",
"and",
"False",
"if",
"not",
"Useful",
"to",
"determine",
"for",
"example",
"if",
"f",
"is",
"STDOUT",
"to",
"a",
"pipe",
"."
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L54-L69 | train |
casebeer/audiogen | audiogen/sampler.py | sample | def sample(generator, min=-1, max=1, width=SAMPLE_WIDTH):
'''Convert audio waveform generator into packed sample generator.'''
# select signed char, short, or in based on sample width
fmt = { 1: '<B', 2: '<h', 4: '<i' }[width]
return (struct.pack(fmt, int(sample)) for sample in \
normalize(hard_clip(generator, m... | python | def sample(generator, min=-1, max=1, width=SAMPLE_WIDTH):
'''Convert audio waveform generator into packed sample generator.'''
# select signed char, short, or in based on sample width
fmt = { 1: '<B', 2: '<h', 4: '<i' }[width]
return (struct.pack(fmt, int(sample)) for sample in \
normalize(hard_clip(generator, m... | [
"def",
"sample",
"(",
"generator",
",",
"min",
"=",
"-",
"1",
",",
"max",
"=",
"1",
",",
"width",
"=",
"SAMPLE_WIDTH",
")",
":",
"# select signed char, short, or in based on sample width",
"fmt",
"=",
"{",
"1",
":",
"'<B'",
",",
"2",
":",
"'<h'",
",",
"4... | Convert audio waveform generator into packed sample generator. | [
"Convert",
"audio",
"waveform",
"generator",
"into",
"packed",
"sample",
"generator",
"."
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L72-L78 | train |
casebeer/audiogen | audiogen/sampler.py | sample_all | def sample_all(generators, *args, **kwargs):
'''Convert list of audio waveform generators into list of packed sample generators.'''
return [sample(gen, *args, **kwargs) for gen in generators] | python | def sample_all(generators, *args, **kwargs):
'''Convert list of audio waveform generators into list of packed sample generators.'''
return [sample(gen, *args, **kwargs) for gen in generators] | [
"def",
"sample_all",
"(",
"generators",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"sample",
"(",
"gen",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"gen",
"in",
"generators",
"]"
] | Convert list of audio waveform generators into list of packed sample generators. | [
"Convert",
"list",
"of",
"audio",
"waveform",
"generators",
"into",
"list",
"of",
"packed",
"sample",
"generators",
"."
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L82-L84 | train |
casebeer/audiogen | audiogen/sampler.py | buffer | def buffer(stream, buffer_size=BUFFER_SIZE):
'''
Buffer the generator into byte strings of buffer_size samples
Return a generator that outputs reasonably sized byte strings
containing buffer_size samples from the generator stream.
This allows us to outputing big chunks of the audio stream to
disk at once for ... | python | def buffer(stream, buffer_size=BUFFER_SIZE):
'''
Buffer the generator into byte strings of buffer_size samples
Return a generator that outputs reasonably sized byte strings
containing buffer_size samples from the generator stream.
This allows us to outputing big chunks of the audio stream to
disk at once for ... | [
"def",
"buffer",
"(",
"stream",
",",
"buffer_size",
"=",
"BUFFER_SIZE",
")",
":",
"i",
"=",
"iter",
"(",
"stream",
")",
"return",
"iter",
"(",
"lambda",
":",
"\"\"",
".",
"join",
"(",
"itertools",
".",
"islice",
"(",
"i",
",",
"buffer_size",
")",
")"... | Buffer the generator into byte strings of buffer_size samples
Return a generator that outputs reasonably sized byte strings
containing buffer_size samples from the generator stream.
This allows us to outputing big chunks of the audio stream to
disk at once for faster writes. | [
"Buffer",
"the",
"generator",
"into",
"byte",
"strings",
"of",
"buffer_size",
"samples"
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L97-L108 | train |
casebeer/audiogen | audiogen/sampler.py | wave_module_patched | def wave_module_patched():
'''True if wave module can write data size of 0xFFFFFFFF, False otherwise.'''
f = StringIO()
w = wave.open(f, "wb")
w.setparams((1, 2, 44100, 0, "NONE", "no compression"))
patched = True
try:
w.setnframes((0xFFFFFFFF - 36) / w.getnchannels() / w.getsampwidth())
w._ensure_header_writ... | python | def wave_module_patched():
'''True if wave module can write data size of 0xFFFFFFFF, False otherwise.'''
f = StringIO()
w = wave.open(f, "wb")
w.setparams((1, 2, 44100, 0, "NONE", "no compression"))
patched = True
try:
w.setnframes((0xFFFFFFFF - 36) / w.getnchannels() / w.getsampwidth())
w._ensure_header_writ... | [
"def",
"wave_module_patched",
"(",
")",
":",
"f",
"=",
"StringIO",
"(",
")",
"w",
"=",
"wave",
".",
"open",
"(",
"f",
",",
"\"wb\"",
")",
"w",
".",
"setparams",
"(",
"(",
"1",
",",
"2",
",",
"44100",
",",
"0",
",",
"\"NONE\"",
",",
"\"no compress... | True if wave module can write data size of 0xFFFFFFFF, False otherwise. | [
"True",
"if",
"wave",
"module",
"can",
"write",
"data",
"size",
"of",
"0xFFFFFFFF",
"False",
"otherwise",
"."
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L134-L148 | train |
casebeer/audiogen | audiogen/sampler.py | cache_finite_samples | def cache_finite_samples(f):
'''Decorator to cache audio samples produced by the wrapped generator.'''
cache = {}
def wrap(*args):
key = FRAME_RATE, args
if key not in cache:
cache[key] = [sample for sample in f(*args)]
return (sample for sample in cache[key])
return wrap | python | def cache_finite_samples(f):
'''Decorator to cache audio samples produced by the wrapped generator.'''
cache = {}
def wrap(*args):
key = FRAME_RATE, args
if key not in cache:
cache[key] = [sample for sample in f(*args)]
return (sample for sample in cache[key])
return wrap | [
"def",
"cache_finite_samples",
"(",
"f",
")",
":",
"cache",
"=",
"{",
"}",
"def",
"wrap",
"(",
"*",
"args",
")",
":",
"key",
"=",
"FRAME_RATE",
",",
"args",
"if",
"key",
"not",
"in",
"cache",
":",
"cache",
"[",
"key",
"]",
"=",
"[",
"sample",
"fo... | Decorator to cache audio samples produced by the wrapped generator. | [
"Decorator",
"to",
"cache",
"audio",
"samples",
"produced",
"by",
"the",
"wrapped",
"generator",
"."
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L189-L197 | train |
casebeer/audiogen | audiogen/sampler.py | play | def play(channels, blocking=True, raw_samples=False):
'''
Play the contents of the generator using PyAudio
Play to the system soundcard using PyAudio. PyAudio, an otherwise optional
depenency, must be installed for this feature to work.
'''
if not pyaudio_loaded:
raise Exception("Soundcard playback requires P... | python | def play(channels, blocking=True, raw_samples=False):
'''
Play the contents of the generator using PyAudio
Play to the system soundcard using PyAudio. PyAudio, an otherwise optional
depenency, must be installed for this feature to work.
'''
if not pyaudio_loaded:
raise Exception("Soundcard playback requires P... | [
"def",
"play",
"(",
"channels",
",",
"blocking",
"=",
"True",
",",
"raw_samples",
"=",
"False",
")",
":",
"if",
"not",
"pyaudio_loaded",
":",
"raise",
"Exception",
"(",
"\"Soundcard playback requires PyAudio. Install with `pip install pyaudio`.\"",
")",
"channel_count",... | Play the contents of the generator using PyAudio
Play to the system soundcard using PyAudio. PyAudio, an otherwise optional
depenency, must be installed for this feature to work. | [
"Play",
"the",
"contents",
"of",
"the",
"generator",
"using",
"PyAudio"
] | 184dee2ca32c2bb4315a0f18e62288728fcd7881 | https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/sampler.py#L211-L245 | train |
jakevdp/supersmoother | supersmoother/windowed_sum.py | windowed_sum_slow | def windowed_sum_slow(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
This is a slow function, used primarily for testing and validation
of the faster version of ``windowed_sum()``
Parameters
--... | python | def windowed_sum_slow(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
This is a slow function, used primarily for testing and validation
of the faster version of ``windowed_sum()``
Parameters
--... | [
"def",
"windowed_sum_slow",
"(",
"arrays",
",",
"span",
",",
"t",
"=",
"None",
",",
"indices",
"=",
"None",
",",
"tpowers",
"=",
"0",
",",
"period",
"=",
"None",
",",
"subtract_mid",
"=",
"False",
")",
":",
"span",
"=",
"np",
".",
"asarray",
"(",
"... | Compute the windowed sum of the given arrays.
This is a slow function, used primarily for testing and validation
of the faster version of ``windowed_sum()``
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum a... | [
"Compute",
"the",
"windowed",
"sum",
"of",
"the",
"given",
"arrays",
"."
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/windowed_sum.py#L4-L84 | train |
jakevdp/supersmoother | supersmoother/windowed_sum.py | windowed_sum | def windowed_sum(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum... | python | def windowed_sum(arrays, span, t=None, indices=None, tpowers=0,
period=None, subtract_mid=False):
"""Compute the windowed sum of the given arrays.
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum... | [
"def",
"windowed_sum",
"(",
"arrays",
",",
"span",
",",
"t",
"=",
"None",
",",
"indices",
"=",
"None",
",",
"tpowers",
"=",
"0",
",",
"period",
"=",
"None",
",",
"subtract_mid",
"=",
"False",
")",
":",
"span",
"=",
"np",
".",
"asarray",
"(",
"span"... | Compute the windowed sum of the given arrays.
Parameters
----------
arrays : tuple of arrays
arrays to window
span : int or array of ints
The span to use for the sum at each point. If array is provided,
it must be broadcastable with ``indices``
indices : array
the in... | [
"Compute",
"the",
"windowed",
"sum",
"of",
"the",
"given",
"arrays",
"."
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/windowed_sum.py#L87-L212 | train |
jakevdp/supersmoother | supersmoother/windowed_sum.py | _pad_arrays | def _pad_arrays(t, arrays, indices, span, period):
"""Internal routine to pad arrays for periodic models."""
N = len(t)
if indices is None:
indices = np.arange(N)
pad_left = max(0, 0 - np.min(indices - span // 2))
pad_right = max(0, np.max(indices + span - span // 2) - (N - 1))
if pad_... | python | def _pad_arrays(t, arrays, indices, span, period):
"""Internal routine to pad arrays for periodic models."""
N = len(t)
if indices is None:
indices = np.arange(N)
pad_left = max(0, 0 - np.min(indices - span // 2))
pad_right = max(0, np.max(indices + span - span // 2) - (N - 1))
if pad_... | [
"def",
"_pad_arrays",
"(",
"t",
",",
"arrays",
",",
"indices",
",",
"span",
",",
"period",
")",
":",
"N",
"=",
"len",
"(",
"t",
")",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"np",
".",
"arange",
"(",
"N",
")",
"pad_left",
"=",
"max",
... | Internal routine to pad arrays for periodic models. | [
"Internal",
"routine",
"to",
"pad",
"arrays",
"for",
"periodic",
"models",
"."
] | 0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f | https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/windowed_sum.py#L215-L242 | train |
voidpp/PCA9685-driver | pca9685_driver/device.py | Device.get_i2c_bus_numbers | def get_i2c_bus_numbers(glober = glob.glob):
"""Search all the available I2C devices in the system"""
res = []
for device in glober("/dev/i2c-*"):
r = re.match("/dev/i2c-([\d]){1,2}", device)
res.append(int(r.group(1)))
return res | python | def get_i2c_bus_numbers(glober = glob.glob):
"""Search all the available I2C devices in the system"""
res = []
for device in glober("/dev/i2c-*"):
r = re.match("/dev/i2c-([\d]){1,2}", device)
res.append(int(r.group(1)))
return res | [
"def",
"get_i2c_bus_numbers",
"(",
"glober",
"=",
"glob",
".",
"glob",
")",
":",
"res",
"=",
"[",
"]",
"for",
"device",
"in",
"glober",
"(",
"\"/dev/i2c-*\"",
")",
":",
"r",
"=",
"re",
".",
"match",
"(",
"\"/dev/i2c-([\\d]){1,2}\"",
",",
"device",
")",
... | Search all the available I2C devices in the system | [
"Search",
"all",
"the",
"available",
"I2C",
"devices",
"in",
"the",
"system"
] | 774790028cbced30fd69384f945198148b1793fc | https://github.com/voidpp/PCA9685-driver/blob/774790028cbced30fd69384f945198148b1793fc/pca9685_driver/device.py#L69-L75 | train |
voidpp/PCA9685-driver | pca9685_driver/device.py | Device.get_led_register_from_name | def get_led_register_from_name(self, name):
"""Parse the name for led number
:param name: attribute name, like: led_1
"""
res = re.match('^led_([0-9]{1,2})$', name)
if res is None:
raise AttributeError("Unknown attribute: '%s'" % name)
led_num = int(res.group... | python | def get_led_register_from_name(self, name):
"""Parse the name for led number
:param name: attribute name, like: led_1
"""
res = re.match('^led_([0-9]{1,2})$', name)
if res is None:
raise AttributeError("Unknown attribute: '%s'" % name)
led_num = int(res.group... | [
"def",
"get_led_register_from_name",
"(",
"self",
",",
"name",
")",
":",
"res",
"=",
"re",
".",
"match",
"(",
"'^led_([0-9]{1,2})$'",
",",
"name",
")",
"if",
"res",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"\"Unknown attribute: '%s'\"",
"%",
"name",
... | Parse the name for led number
:param name: attribute name, like: led_1 | [
"Parse",
"the",
"name",
"for",
"led",
"number"
] | 774790028cbced30fd69384f945198148b1793fc | https://github.com/voidpp/PCA9685-driver/blob/774790028cbced30fd69384f945198148b1793fc/pca9685_driver/device.py#L87-L98 | train |
voidpp/PCA9685-driver | pca9685_driver/device.py | Device.set_pwm | def set_pwm(self, led_num, value):
"""Set PWM value for the specified LED
:param led_num: LED number (0-15)
:param value: the 12 bit value (0-4095)
"""
self.__check_range('led_number', led_num)
self.__check_range('led_value', value)
register_low = self.calc_led_... | python | def set_pwm(self, led_num, value):
"""Set PWM value for the specified LED
:param led_num: LED number (0-15)
:param value: the 12 bit value (0-4095)
"""
self.__check_range('led_number', led_num)
self.__check_range('led_value', value)
register_low = self.calc_led_... | [
"def",
"set_pwm",
"(",
"self",
",",
"led_num",
",",
"value",
")",
":",
"self",
".",
"__check_range",
"(",
"'led_number'",
",",
"led_num",
")",
"self",
".",
"__check_range",
"(",
"'led_value'",
",",
"value",
")",
"register_low",
"=",
"self",
".",
"calc_led_... | Set PWM value for the specified LED
:param led_num: LED number (0-15)
:param value: the 12 bit value (0-4095) | [
"Set",
"PWM",
"value",
"for",
"the",
"specified",
"LED"
] | 774790028cbced30fd69384f945198148b1793fc | https://github.com/voidpp/PCA9685-driver/blob/774790028cbced30fd69384f945198148b1793fc/pca9685_driver/device.py#L115-L127 | train |
voidpp/PCA9685-driver | pca9685_driver/device.py | Device.get_pwm | def get_pwm(self, led_num):
"""Generic getter for all LED PWM value"""
self.__check_range('led_number', led_num)
register_low = self.calc_led_register(led_num)
return self.__get_led_value(register_low) | python | def get_pwm(self, led_num):
"""Generic getter for all LED PWM value"""
self.__check_range('led_number', led_num)
register_low = self.calc_led_register(led_num)
return self.__get_led_value(register_low) | [
"def",
"get_pwm",
"(",
"self",
",",
"led_num",
")",
":",
"self",
".",
"__check_range",
"(",
"'led_number'",
",",
"led_num",
")",
"register_low",
"=",
"self",
".",
"calc_led_register",
"(",
"led_num",
")",
"return",
"self",
".",
"__get_led_value",
"(",
"regis... | Generic getter for all LED PWM value | [
"Generic",
"getter",
"for",
"all",
"LED",
"PWM",
"value"
] | 774790028cbced30fd69384f945198148b1793fc | https://github.com/voidpp/PCA9685-driver/blob/774790028cbced30fd69384f945198148b1793fc/pca9685_driver/device.py#L134-L138 | train |
voidpp/PCA9685-driver | pca9685_driver/device.py | Device.sleep | def sleep(self):
"""Send the controller to sleep"""
logger.debug("Sleep the controller")
self.write(Registers.MODE_1, self.mode_1 | (1 << Mode1.SLEEP)) | python | def sleep(self):
"""Send the controller to sleep"""
logger.debug("Sleep the controller")
self.write(Registers.MODE_1, self.mode_1 | (1 << Mode1.SLEEP)) | [
"def",
"sleep",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Sleep the controller\"",
")",
"self",
".",
"write",
"(",
"Registers",
".",
"MODE_1",
",",
"self",
".",
"mode_1",
"|",
"(",
"1",
"<<",
"Mode1",
".",
"SLEEP",
")",
")"
] | Send the controller to sleep | [
"Send",
"the",
"controller",
"to",
"sleep"
] | 774790028cbced30fd69384f945198148b1793fc | https://github.com/voidpp/PCA9685-driver/blob/774790028cbced30fd69384f945198148b1793fc/pca9685_driver/device.py#L145-L148 | train |
voidpp/PCA9685-driver | pca9685_driver/device.py | Device.write | def write(self, reg, value):
"""Write raw byte value to the specified register
:param reg: the register number (0-69, 250-255)
:param value: byte value
"""
# TODO: check reg: 0-69, 250-255
self.__check_range('register_value', value)
logger.debug("Write '%s' to re... | python | def write(self, reg, value):
"""Write raw byte value to the specified register
:param reg: the register number (0-69, 250-255)
:param value: byte value
"""
# TODO: check reg: 0-69, 250-255
self.__check_range('register_value', value)
logger.debug("Write '%s' to re... | [
"def",
"write",
"(",
"self",
",",
"reg",
",",
"value",
")",
":",
"# TODO: check reg: 0-69, 250-255",
"self",
".",
"__check_range",
"(",
"'register_value'",
",",
"value",
")",
"logger",
".",
"debug",
"(",
"\"Write '%s' to register '%s'\"",
"%",
"(",
"value",
",",... | Write raw byte value to the specified register
:param reg: the register number (0-69, 250-255)
:param value: byte value | [
"Write",
"raw",
"byte",
"value",
"to",
"the",
"specified",
"register"
] | 774790028cbced30fd69384f945198148b1793fc | https://github.com/voidpp/PCA9685-driver/blob/774790028cbced30fd69384f945198148b1793fc/pca9685_driver/device.py#L155-L164 | train |
voidpp/PCA9685-driver | pca9685_driver/device.py | Device.set_pwm_frequency | def set_pwm_frequency(self, value):
"""Set the frequency for all PWM output
:param value: the frequency in Hz
"""
self.__check_range('pwm_frequency', value)
reg_val = self.calc_pre_scale(value)
logger.debug("Calculated prescale value is %s" % reg_val)
self.sleep(... | python | def set_pwm_frequency(self, value):
"""Set the frequency for all PWM output
:param value: the frequency in Hz
"""
self.__check_range('pwm_frequency', value)
reg_val = self.calc_pre_scale(value)
logger.debug("Calculated prescale value is %s" % reg_val)
self.sleep(... | [
"def",
"set_pwm_frequency",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__check_range",
"(",
"'pwm_frequency'",
",",
"value",
")",
"reg_val",
"=",
"self",
".",
"calc_pre_scale",
"(",
"value",
")",
"logger",
".",
"debug",
"(",
"\"Calculated prescale valu... | Set the frequency for all PWM output
:param value: the frequency in Hz | [
"Set",
"the",
"frequency",
"for",
"all",
"PWM",
"output"
] | 774790028cbced30fd69384f945198148b1793fc | https://github.com/voidpp/PCA9685-driver/blob/774790028cbced30fd69384f945198148b1793fc/pca9685_driver/device.py#L180-L190 | train |
obulkin/string-dist | stringdist/pystringdist/levenshtein.py | levenshtein_norm | def levenshtein_norm(source, target):
"""Calculates the normalized Levenshtein distance between two string
arguments. The result will be a float in the range [0.0, 1.0], with 1.0
signifying the biggest possible distance between strings with these lengths
"""
# Compute Levenshtein distance using hel... | python | def levenshtein_norm(source, target):
"""Calculates the normalized Levenshtein distance between two string
arguments. The result will be a float in the range [0.0, 1.0], with 1.0
signifying the biggest possible distance between strings with these lengths
"""
# Compute Levenshtein distance using hel... | [
"def",
"levenshtein_norm",
"(",
"source",
",",
"target",
")",
":",
"# Compute Levenshtein distance using helper function. The max is always",
"# just the length of the longer string, so this is used to normalize result",
"# before returning it",
"distance",
"=",
"_levenshtein_compute",
"... | Calculates the normalized Levenshtein distance between two string
arguments. The result will be a float in the range [0.0, 1.0], with 1.0
signifying the biggest possible distance between strings with these lengths | [
"Calculates",
"the",
"normalized",
"Levenshtein",
"distance",
"between",
"two",
"string",
"arguments",
".",
"The",
"result",
"will",
"be",
"a",
"float",
"in",
"the",
"range",
"[",
"0",
".",
"0",
"1",
".",
"0",
"]",
"with",
"1",
".",
"0",
"signifying",
... | 38d04352d617a5d43b06832cc1bf0aee8978559f | https://github.com/obulkin/string-dist/blob/38d04352d617a5d43b06832cc1bf0aee8978559f/stringdist/pystringdist/levenshtein.py#L15-L25 | train |
wdecoster/nanoplotter | nanoplotter/nanoplotter_main.py | check_valid_color | def check_valid_color(color):
"""Check if the color provided by the user is valid.
If color is invalid the default is returned.
"""
if color in list(mcolors.CSS4_COLORS.keys()) + ["#4CB391"]:
logging.info("Nanoplotter: Valid color {}.".format(color))
return color
else:
loggi... | python | def check_valid_color(color):
"""Check if the color provided by the user is valid.
If color is invalid the default is returned.
"""
if color in list(mcolors.CSS4_COLORS.keys()) + ["#4CB391"]:
logging.info("Nanoplotter: Valid color {}.".format(color))
return color
else:
loggi... | [
"def",
"check_valid_color",
"(",
"color",
")",
":",
"if",
"color",
"in",
"list",
"(",
"mcolors",
".",
"CSS4_COLORS",
".",
"keys",
"(",
")",
")",
"+",
"[",
"\"#4CB391\"",
"]",
":",
"logging",
".",
"info",
"(",
"\"Nanoplotter: Valid color {}.\"",
".",
"forma... | Check if the color provided by the user is valid.
If color is invalid the default is returned. | [
"Check",
"if",
"the",
"color",
"provided",
"by",
"the",
"user",
"is",
"valid",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/nanoplotter_main.py#L43-L54 | train |
wdecoster/nanoplotter | nanoplotter/nanoplotter_main.py | check_valid_format | def check_valid_format(figformat):
"""Check if the specified figure format is valid.
If format is invalid the default is returned.
Probably installation-dependent
"""
fig = plt.figure()
if figformat in list(fig.canvas.get_supported_filetypes().keys()):
logging.info("Nanoplotter: valid o... | python | def check_valid_format(figformat):
"""Check if the specified figure format is valid.
If format is invalid the default is returned.
Probably installation-dependent
"""
fig = plt.figure()
if figformat in list(fig.canvas.get_supported_filetypes().keys()):
logging.info("Nanoplotter: valid o... | [
"def",
"check_valid_format",
"(",
"figformat",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"if",
"figformat",
"in",
"list",
"(",
"fig",
".",
"canvas",
".",
"get_supported_filetypes",
"(",
")",
".",
"keys",
"(",
")",
")",
":",
"logging",
".",
... | Check if the specified figure format is valid.
If format is invalid the default is returned.
Probably installation-dependent | [
"Check",
"if",
"the",
"specified",
"figure",
"format",
"is",
"valid",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/nanoplotter_main.py#L57-L70 | train |
wdecoster/nanoplotter | nanoplotter/nanoplotter_main.py | scatter | def scatter(x, y, names, path, plots, color="#4CB391", figformat="png",
stat=None, log=False, minvalx=0, minvaly=0, title=None, plot_settings=None):
"""Create bivariate plots.
Create four types of bivariate plots of x vs y, containing marginal summaries
-A scatter plot with histograms on axes
... | python | def scatter(x, y, names, path, plots, color="#4CB391", figformat="png",
stat=None, log=False, minvalx=0, minvaly=0, title=None, plot_settings=None):
"""Create bivariate plots.
Create four types of bivariate plots of x vs y, containing marginal summaries
-A scatter plot with histograms on axes
... | [
"def",
"scatter",
"(",
"x",
",",
"y",
",",
"names",
",",
"path",
",",
"plots",
",",
"color",
"=",
"\"#4CB391\"",
",",
"figformat",
"=",
"\"png\"",
",",
"stat",
"=",
"None",
",",
"log",
"=",
"False",
",",
"minvalx",
"=",
"0",
",",
"minvaly",
"=",
... | Create bivariate plots.
Create four types of bivariate plots of x vs y, containing marginal summaries
-A scatter plot with histograms on axes
-A hexagonal binned plot with histograms on axes
-A kernel density plot with density curves on axes
-A pauvre-style plot using code from https://github.com/c... | [
"Create",
"bivariate",
"plots",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/nanoplotter_main.py#L78-L206 | train |
wdecoster/nanoplotter | nanoplotter/nanoplotter_main.py | contains_variance | def contains_variance(arrays, names):
"""
Make sure both arrays for bivariate ("scatter") plot have a stddev > 0
"""
for ar, name in zip(arrays, names):
if np.std(ar) == 0:
sys.stderr.write(
"No variation in '{}', skipping bivariate plots.\n".format(name.lower()))
... | python | def contains_variance(arrays, names):
"""
Make sure both arrays for bivariate ("scatter") plot have a stddev > 0
"""
for ar, name in zip(arrays, names):
if np.std(ar) == 0:
sys.stderr.write(
"No variation in '{}', skipping bivariate plots.\n".format(name.lower()))
... | [
"def",
"contains_variance",
"(",
"arrays",
",",
"names",
")",
":",
"for",
"ar",
",",
"name",
"in",
"zip",
"(",
"arrays",
",",
"names",
")",
":",
"if",
"np",
".",
"std",
"(",
"ar",
")",
"==",
"0",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\... | Make sure both arrays for bivariate ("scatter") plot have a stddev > 0 | [
"Make",
"sure",
"both",
"arrays",
"for",
"bivariate",
"(",
"scatter",
")",
"plot",
"have",
"a",
"stddev",
">",
"0"
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/nanoplotter_main.py#L209-L220 | train |
wdecoster/nanoplotter | nanoplotter/nanoplotter_main.py | length_plots | def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"):
"""Create histogram of normal and log transformed read lengths."""
logging.info("Nanoplotter: Creating length plots for {}.".format(name))
maxvalx = np.amax(array)
if n50:
logging.info("Nanoplotter: Usin... | python | def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"):
"""Create histogram of normal and log transformed read lengths."""
logging.info("Nanoplotter: Creating length plots for {}.".format(name))
maxvalx = np.amax(array)
if n50:
logging.info("Nanoplotter: Usin... | [
"def",
"length_plots",
"(",
"array",
",",
"name",
",",
"path",
",",
"title",
"=",
"None",
",",
"n50",
"=",
"None",
",",
"color",
"=",
"\"#4CB391\"",
",",
"figformat",
"=",
"\"png\"",
")",
":",
"logging",
".",
"info",
"(",
"\"Nanoplotter: Creating length pl... | Create histogram of normal and log transformed read lengths. | [
"Create",
"histogram",
"of",
"normal",
"and",
"log",
"transformed",
"read",
"lengths",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/nanoplotter_main.py#L223-L298 | train |
wdecoster/nanoplotter | nanoplotter/spatial_heatmap.py | make_layout | def make_layout(maxval):
"""Make the physical layout of the MinION flowcell.
based on https://bioinformatics.stackexchange.com/a/749/681
returned as a numpy array
"""
if maxval > 512:
return Layout(
structure=np.concatenate([np.array([list(range(10 * i + 1, i * 10 + 11))
... | python | def make_layout(maxval):
"""Make the physical layout of the MinION flowcell.
based on https://bioinformatics.stackexchange.com/a/749/681
returned as a numpy array
"""
if maxval > 512:
return Layout(
structure=np.concatenate([np.array([list(range(10 * i + 1, i * 10 + 11))
... | [
"def",
"make_layout",
"(",
"maxval",
")",
":",
"if",
"maxval",
">",
"512",
":",
"return",
"Layout",
"(",
"structure",
"=",
"np",
".",
"concatenate",
"(",
"[",
"np",
".",
"array",
"(",
"[",
"list",
"(",
"range",
"(",
"10",
"*",
"i",
"+",
"1",
",",... | Make the physical layout of the MinION flowcell.
based on https://bioinformatics.stackexchange.com/a/749/681
returned as a numpy array | [
"Make",
"the",
"physical",
"layout",
"of",
"the",
"MinION",
"flowcell",
".",
"based",
"on",
"https",
":",
"//",
"bioinformatics",
".",
"stackexchange",
".",
"com",
"/",
"a",
"/",
"749",
"/",
"681",
"returned",
"as",
"a",
"numpy",
"array"
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/spatial_heatmap.py#L17-L43 | train |
wdecoster/nanoplotter | nanoplotter/spatial_heatmap.py | spatial_heatmap | def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
"""Taking channel information and creating post run channel activity plots."""
logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
.format(array.size))
activity_map = Plot(
p... | python | def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
"""Taking channel information and creating post run channel activity plots."""
logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
.format(array.size))
activity_map = Plot(
p... | [
"def",
"spatial_heatmap",
"(",
"array",
",",
"path",
",",
"title",
"=",
"None",
",",
"color",
"=",
"\"Greens\"",
",",
"figformat",
"=",
"\"png\"",
")",
":",
"logging",
".",
"info",
"(",
"\"Nanoplotter: Creating heatmap of reads per channel using {} reads.\"",
".",
... | Taking channel information and creating post run channel activity plots. | [
"Taking",
"channel",
"information",
"and",
"creating",
"post",
"run",
"channel",
"activity",
"plots",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/spatial_heatmap.py#L46-L70 | train |
occrp/cronosparser | cronos/cli.py | main | def main(database_dir, target_dir):
"""Generate CSV files from a CronosPro/CronosPlus database."""
if not os.path.isdir(database_dir):
raise click.ClickException("Database directory does not exist!")
try:
os.makedirs(target_dir)
except:
pass
try:
parse(database_dir, t... | python | def main(database_dir, target_dir):
"""Generate CSV files from a CronosPro/CronosPlus database."""
if not os.path.isdir(database_dir):
raise click.ClickException("Database directory does not exist!")
try:
os.makedirs(target_dir)
except:
pass
try:
parse(database_dir, t... | [
"def",
"main",
"(",
"database_dir",
",",
"target_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"database_dir",
")",
":",
"raise",
"click",
".",
"ClickException",
"(",
"\"Database directory does not exist!\"",
")",
"try",
":",
"os",
".",
... | Generate CSV files from a CronosPro/CronosPlus database. | [
"Generate",
"CSV",
"files",
"from",
"a",
"CronosPro",
"/",
"CronosPlus",
"database",
"."
] | e7748a1a98992b2cc2191f4ce3b1621db1365c3f | https://github.com/occrp/cronosparser/blob/e7748a1a98992b2cc2191f4ce3b1621db1365c3f/cronos/cli.py#L11-L22 | train |
wdecoster/nanoplotter | nanoplotter/timeplots.py | check_valid_time_and_sort | def check_valid_time_and_sort(df, timescol, days=5, warning=True):
"""Check if the data contains reads created within the same `days` timeframe.
if not, print warning and only return part of the data which is within `days` days
Resetting the index twice to get also an "index" column for plotting the cum_yi... | python | def check_valid_time_and_sort(df, timescol, days=5, warning=True):
"""Check if the data contains reads created within the same `days` timeframe.
if not, print warning and only return part of the data which is within `days` days
Resetting the index twice to get also an "index" column for plotting the cum_yi... | [
"def",
"check_valid_time_and_sort",
"(",
"df",
",",
"timescol",
",",
"days",
"=",
"5",
",",
"warning",
"=",
"True",
")",
":",
"timediff",
"=",
"(",
"df",
"[",
"timescol",
"]",
".",
"max",
"(",
")",
"-",
"df",
"[",
"timescol",
"]",
".",
"min",
"(",
... | Check if the data contains reads created within the same `days` timeframe.
if not, print warning and only return part of the data which is within `days` days
Resetting the index twice to get also an "index" column for plotting the cum_yield_reads plot | [
"Check",
"if",
"the",
"data",
"contains",
"reads",
"created",
"within",
"the",
"same",
"days",
"timeframe",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/timeplots.py#L12-L34 | train |
wdecoster/nanoplotter | nanoplotter/timeplots.py | time_plots | def time_plots(df, path, title=None, color="#4CB391", figformat="png",
log_length=False, plot_settings=None):
"""Making plots of time vs read length, time vs quality and cumulative yield."""
dfs = check_valid_time_and_sort(df, "start_time")
logging.info("Nanoplotter: Creating timeplots using ... | python | def time_plots(df, path, title=None, color="#4CB391", figformat="png",
log_length=False, plot_settings=None):
"""Making plots of time vs read length, time vs quality and cumulative yield."""
dfs = check_valid_time_and_sort(df, "start_time")
logging.info("Nanoplotter: Creating timeplots using ... | [
"def",
"time_plots",
"(",
"df",
",",
"path",
",",
"title",
"=",
"None",
",",
"color",
"=",
"\"#4CB391\"",
",",
"figformat",
"=",
"\"png\"",
",",
"log_length",
"=",
"False",
",",
"plot_settings",
"=",
"None",
")",
":",
"dfs",
"=",
"check_valid_time_and_sort... | Making plots of time vs read length, time vs quality and cumulative yield. | [
"Making",
"plots",
"of",
"time",
"vs",
"read",
"length",
"time",
"vs",
"quality",
"and",
"cumulative",
"yield",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/timeplots.py#L37-L58 | train |
wdecoster/nanoplotter | nanoplotter/compplots.py | violin_or_box_plot | def violin_or_box_plot(df, y, figformat, path, y_name,
title=None, plot="violin", log=False, palette=None):
"""Create a violin or boxplot from the received DataFrame.
The x-axis should be divided based on the 'dataset' column,
the y-axis is specified in the arguments
"""
comp... | python | def violin_or_box_plot(df, y, figformat, path, y_name,
title=None, plot="violin", log=False, palette=None):
"""Create a violin or boxplot from the received DataFrame.
The x-axis should be divided based on the 'dataset' column,
the y-axis is specified in the arguments
"""
comp... | [
"def",
"violin_or_box_plot",
"(",
"df",
",",
"y",
",",
"figformat",
",",
"path",
",",
"y_name",
",",
"title",
"=",
"None",
",",
"plot",
"=",
"\"violin\"",
",",
"log",
"=",
"False",
",",
"palette",
"=",
"None",
")",
":",
"comp",
"=",
"Plot",
"(",
"p... | Create a violin or boxplot from the received DataFrame.
The x-axis should be divided based on the 'dataset' column,
the y-axis is specified in the arguments | [
"Create",
"a",
"violin",
"or",
"boxplot",
"from",
"the",
"received",
"DataFrame",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/compplots.py#L13-L68 | train |
wdecoster/nanoplotter | nanoplotter/compplots.py | output_barplot | def output_barplot(df, figformat, path, title=None, palette=None):
"""Create barplots based on number of reads and total sum of nucleotides sequenced."""
logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.")
read_count = Plot(path=path + "NanoComp_number_of_reads." + figfo... | python | def output_barplot(df, figformat, path, title=None, palette=None):
"""Create barplots based on number of reads and total sum of nucleotides sequenced."""
logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.")
read_count = Plot(path=path + "NanoComp_number_of_reads." + figfo... | [
"def",
"output_barplot",
"(",
"df",
",",
"figformat",
",",
"path",
",",
"title",
"=",
"None",
",",
"palette",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"Nanoplotter: Creating barplots for number of reads and total throughput.\"",
")",
"read_count",
"=",
... | Create barplots based on number of reads and total sum of nucleotides sequenced. | [
"Create",
"barplots",
"based",
"on",
"number",
"of",
"reads",
"and",
"total",
"sum",
"of",
"nucleotides",
"sequenced",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/compplots.py#L83-L116 | train |
wdecoster/nanoplotter | nanoplotter/compplots.py | overlay_histogram | def overlay_histogram(df, path, palette=None):
"""
Use plotly to create an overlay of length histograms
Return html code, but also save as png
Only has 10 colors, which get recycled up to 5 times.
"""
if palette is None:
palette = plotly.colors.DEFAULT_PLOTLY_COLORS * 5
hist = Plot... | python | def overlay_histogram(df, path, palette=None):
"""
Use plotly to create an overlay of length histograms
Return html code, but also save as png
Only has 10 colors, which get recycled up to 5 times.
"""
if palette is None:
palette = plotly.colors.DEFAULT_PLOTLY_COLORS * 5
hist = Plot... | [
"def",
"overlay_histogram",
"(",
"df",
",",
"path",
",",
"palette",
"=",
"None",
")",
":",
"if",
"palette",
"is",
"None",
":",
"palette",
"=",
"plotly",
".",
"colors",
".",
"DEFAULT_PLOTLY_COLORS",
"*",
"5",
"hist",
"=",
"Plot",
"(",
"path",
"=",
"path... | Use plotly to create an overlay of length histograms
Return html code, but also save as png
Only has 10 colors, which get recycled up to 5 times. | [
"Use",
"plotly",
"to",
"create",
"an",
"overlay",
"of",
"length",
"histograms",
"Return",
"html",
"code",
"but",
"also",
"save",
"as",
"png"
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/compplots.py#L178-L210 | train |
wdecoster/nanoplotter | nanoplotter/compplots.py | plot_log_histogram | def plot_log_histogram(df, palette, title, histnorm=""):
"""
Plot overlaying histograms with log transformation of length
Return both html and fig for png
"""
data = [go.Histogram(x=np.log10(df.loc[df["dataset"] == d, "lengths"]),
opacity=0.4,
name=d... | python | def plot_log_histogram(df, palette, title, histnorm=""):
"""
Plot overlaying histograms with log transformation of length
Return both html and fig for png
"""
data = [go.Histogram(x=np.log10(df.loc[df["dataset"] == d, "lengths"]),
opacity=0.4,
name=d... | [
"def",
"plot_log_histogram",
"(",
"df",
",",
"palette",
",",
"title",
",",
"histnorm",
"=",
"\"\"",
")",
":",
"data",
"=",
"[",
"go",
".",
"Histogram",
"(",
"x",
"=",
"np",
".",
"log10",
"(",
"df",
".",
"loc",
"[",
"df",
"[",
"\"dataset\"",
"]",
... | Plot overlaying histograms with log transformation of length
Return both html and fig for png | [
"Plot",
"overlaying",
"histograms",
"with",
"log",
"transformation",
"of",
"length",
"Return",
"both",
"html",
"and",
"fig",
"for",
"png"
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/compplots.py#L233-L259 | train |
occrp/cronosparser | cronos/parser.py | get_file | def get_file(db_folder, file_name):
"""Glob for the poor."""
if not os.path.isdir(db_folder):
return
file_name = file_name.lower().strip()
for cand_name in os.listdir(db_folder):
if cand_name.lower().strip() == file_name:
return os.path.join(db_folder, cand_name) | python | def get_file(db_folder, file_name):
"""Glob for the poor."""
if not os.path.isdir(db_folder):
return
file_name = file_name.lower().strip()
for cand_name in os.listdir(db_folder):
if cand_name.lower().strip() == file_name:
return os.path.join(db_folder, cand_name) | [
"def",
"get_file",
"(",
"db_folder",
",",
"file_name",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"db_folder",
")",
":",
"return",
"file_name",
"=",
"file_name",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"for",
"cand_name",
"i... | Glob for the poor. | [
"Glob",
"for",
"the",
"poor",
"."
] | e7748a1a98992b2cc2191f4ce3b1621db1365c3f | https://github.com/occrp/cronosparser/blob/e7748a1a98992b2cc2191f4ce3b1621db1365c3f/cronos/parser.py#L270-L277 | train |
occrp/cronosparser | cronos/parser.py | parse | def parse(db_folder, out_folder):
"""
Parse a cronos database.
Convert the database located in ``db_folder`` into CSV files in the
directory ``out_folder``.
"""
# The database structure, containing table and column definitions as
# well as other data.
stru_dat = get_file(db_folder, 'Cro... | python | def parse(db_folder, out_folder):
"""
Parse a cronos database.
Convert the database located in ``db_folder`` into CSV files in the
directory ``out_folder``.
"""
# The database structure, containing table and column definitions as
# well as other data.
stru_dat = get_file(db_folder, 'Cro... | [
"def",
"parse",
"(",
"db_folder",
",",
"out_folder",
")",
":",
"# The database structure, containing table and column definitions as",
"# well as other data.",
"stru_dat",
"=",
"get_file",
"(",
"db_folder",
",",
"'CroStru.dat'",
")",
"# Index file for the database, which contains... | Parse a cronos database.
Convert the database located in ``db_folder`` into CSV files in the
directory ``out_folder``. | [
"Parse",
"a",
"cronos",
"database",
"."
] | e7748a1a98992b2cc2191f4ce3b1621db1365c3f | https://github.com/occrp/cronosparser/blob/e7748a1a98992b2cc2191f4ce3b1621db1365c3f/cronos/parser.py#L280-L309 | train |
wdecoster/nanoplotter | nanoplotter/plot.py | Plot.encode1 | def encode1(self):
"""Return the base64 encoding of the figure file and insert in html image tag."""
data_uri = b64encode(open(self.path, 'rb').read()).decode('utf-8').replace('\n', '')
return '<img src="data:image/png;base64,{0}">'.format(data_uri) | python | def encode1(self):
"""Return the base64 encoding of the figure file and insert in html image tag."""
data_uri = b64encode(open(self.path, 'rb').read()).decode('utf-8').replace('\n', '')
return '<img src="data:image/png;base64,{0}">'.format(data_uri) | [
"def",
"encode1",
"(",
"self",
")",
":",
"data_uri",
"=",
"b64encode",
"(",
"open",
"(",
"self",
".",
"path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"return"... | Return the base64 encoding of the figure file and insert in html image tag. | [
"Return",
"the",
"base64",
"encoding",
"of",
"the",
"figure",
"file",
"and",
"insert",
"in",
"html",
"image",
"tag",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/plot.py#L26-L29 | train |
wdecoster/nanoplotter | nanoplotter/plot.py | Plot.encode2 | def encode2(self):
"""Return the base64 encoding of the fig attribute and insert in html image tag."""
buf = BytesIO()
self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
string = b64encode(buf.read())
return '<img src="data:image/png;base64,{0}"... | python | def encode2(self):
"""Return the base64 encoding of the fig attribute and insert in html image tag."""
buf = BytesIO()
self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
string = b64encode(buf.read())
return '<img src="data:image/png;base64,{0}"... | [
"def",
"encode2",
"(",
"self",
")",
":",
"buf",
"=",
"BytesIO",
"(",
")",
"self",
".",
"fig",
".",
"savefig",
"(",
"buf",
",",
"format",
"=",
"'png'",
",",
"bbox_inches",
"=",
"'tight'",
",",
"dpi",
"=",
"100",
")",
"buf",
".",
"seek",
"(",
"0",
... | Return the base64 encoding of the fig attribute and insert in html image tag. | [
"Return",
"the",
"base64",
"encoding",
"of",
"the",
"fig",
"attribute",
"and",
"insert",
"in",
"html",
"image",
"tag",
"."
] | 80908dd1be585f450da5a66989de9de4d544ec85 | https://github.com/wdecoster/nanoplotter/blob/80908dd1be585f450da5a66989de9de4d544ec85/nanoplotter/plot.py#L31-L37 | train |
obulkin/string-dist | stringdist/pystringdist/rdlevenshtein.py | rdlevenshtein_norm | def rdlevenshtein_norm(source, target):
"""Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between string... | python | def rdlevenshtein_norm(source, target):
"""Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between string... | [
"def",
"rdlevenshtein_norm",
"(",
"source",
",",
"target",
")",
":",
"# Compute restricted Damerau-Levenshtein distance using helper function.",
"# The max is always just the length of the longer string, so this is used",
"# to normalize result before returning it",
"distance",
"=",
"_leve... | Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between strings with these lengths | [
"Calculates",
"the",
"normalized",
"restricted",
"Damerau",
"-",
"Levenshtein",
"distance",
"(",
"a",
".",
"k",
".",
"a",
".",
"the",
"normalized",
"optimal",
"string",
"alignment",
"distance",
")",
"between",
"two",
"string",
"arguments",
".",
"The",
"result"... | 38d04352d617a5d43b06832cc1bf0aee8978559f | https://github.com/obulkin/string-dist/blob/38d04352d617a5d43b06832cc1bf0aee8978559f/stringdist/pystringdist/rdlevenshtein.py#L18-L29 | train |
obulkin/string-dist | stringdist/pystringdist/levenshtein_shared.py | _levenshtein_compute | def _levenshtein_compute(source, target, rd_flag):
"""Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using t... | python | def _levenshtein_compute(source, target, rd_flag):
"""Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using t... | [
"def",
"_levenshtein_compute",
"(",
"source",
",",
"target",
",",
"rd_flag",
")",
":",
"# Create matrix of correct size (this is s_len + 1 * t_len + 1 so that the",
"# empty prefixes \"\" can also be included). The leftmost column represents",
"# transforming various source prefixes into an ... | Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using the
Wagner-Fischer algorithm
(https://en.wikipedia.... | [
"Computes",
"the",
"Levenshtein",
"(",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Levenshtein_distance",
")",
"and",
"restricted",
"Damerau",
"-",
"Levenshtein",
"(",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
... | 38d04352d617a5d43b06832cc1bf0aee8978559f | https://github.com/obulkin/string-dist/blob/38d04352d617a5d43b06832cc1bf0aee8978559f/stringdist/pystringdist/levenshtein_shared.py#L5-L65 | train |
mretegan/crispy | setup.py | main | def main():
"""The main entry point."""
if sys.version_info < (2, 7):
sys.exit('crispy requires at least Python 2.7')
elif sys.version_info[0] == 3 and sys.version_info < (3, 4):
sys.exit('crispy requires at least Python 3.4')
kwargs = dict(
name='crispy',
version=get_ve... | python | def main():
"""The main entry point."""
if sys.version_info < (2, 7):
sys.exit('crispy requires at least Python 2.7')
elif sys.version_info[0] == 3 and sys.version_info < (3, 4):
sys.exit('crispy requires at least Python 3.4')
kwargs = dict(
name='crispy',
version=get_ve... | [
"def",
"main",
"(",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"7",
")",
":",
"sys",
".",
"exit",
"(",
"'crispy requires at least Python 2.7'",
")",
"elif",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
"and",
"sys",
".",... | The main entry point. | [
"The",
"main",
"entry",
"point",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/setup.py#L68-L145 | train |
mretegan/crispy | crispy/gui/quanty.py | QuantySpectra.loadFromDisk | def loadFromDisk(self, calculation):
"""
Read the spectra from the files generated by Quanty and store them
as a list of spectum objects.
"""
suffixes = {
'Isotropic': 'iso',
'Circular Dichroism (R-L)': 'cd',
'Right Polarized (R)': 'r',
... | python | def loadFromDisk(self, calculation):
"""
Read the spectra from the files generated by Quanty and store them
as a list of spectum objects.
"""
suffixes = {
'Isotropic': 'iso',
'Circular Dichroism (R-L)': 'cd',
'Right Polarized (R)': 'r',
... | [
"def",
"loadFromDisk",
"(",
"self",
",",
"calculation",
")",
":",
"suffixes",
"=",
"{",
"'Isotropic'",
":",
"'iso'",
",",
"'Circular Dichroism (R-L)'",
":",
"'cd'",
",",
"'Right Polarized (R)'",
":",
"'r'",
",",
"'Left Polarized (L)'",
":",
"'l'",
",",
"'Linear ... | Read the spectra from the files generated by Quanty and store them
as a list of spectum objects. | [
"Read",
"the",
"spectra",
"from",
"the",
"files",
"generated",
"by",
"Quanty",
"and",
"store",
"them",
"as",
"a",
"list",
"of",
"spectum",
"objects",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/quanty.py#L284-L372 | train |
mretegan/crispy | crispy/gui/quanty.py | QuantyDockWidget.populateWidget | def populateWidget(self):
"""
Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but i... | python | def populateWidget(self):
"""
Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but i... | [
"def",
"populateWidget",
"(",
"self",
")",
":",
"self",
".",
"elementComboBox",
".",
"setItems",
"(",
"self",
".",
"state",
".",
"_elements",
",",
"self",
".",
"state",
".",
"element",
")",
"self",
".",
"chargeComboBox",
".",
"setItems",
"(",
"self",
"."... | Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but in practice it is very fast.
Don't try ... | [
"Populate",
"the",
"widget",
"using",
"data",
"stored",
"in",
"the",
"state",
"object",
".",
"The",
"order",
"in",
"which",
"the",
"individual",
"widgets",
"are",
"populated",
"follows",
"their",
"arrangment",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/quanty.py#L754-L899 | train |
mretegan/crispy | crispy/gui/quanty.py | QuantyDockWidget.updateResultsView | def updateResultsView(self, index):
"""
Update the selection to contain only the result specified by
the index. This should be the last index of the model. Finally updade
the context menu.
The selectionChanged signal is used to trigger the update of
the Quanty dock widge... | python | def updateResultsView(self, index):
"""
Update the selection to contain only the result specified by
the index. This should be the last index of the model. Finally updade
the context menu.
The selectionChanged signal is used to trigger the update of
the Quanty dock widge... | [
"def",
"updateResultsView",
"(",
"self",
",",
"index",
")",
":",
"flags",
"=",
"(",
"QItemSelectionModel",
".",
"Clear",
"|",
"QItemSelectionModel",
".",
"Rows",
"|",
"QItemSelectionModel",
".",
"Select",
")",
"self",
".",
"resultsView",
".",
"selectionModel",
... | Update the selection to contain only the result specified by
the index. This should be the last index of the model. Finally updade
the context menu.
The selectionChanged signal is used to trigger the update of
the Quanty dock widget and result details dialog.
:param index: Inde... | [
"Update",
"the",
"selection",
"to",
"contain",
"only",
"the",
"result",
"specified",
"by",
"the",
"index",
".",
"This",
"should",
"be",
"the",
"last",
"index",
"of",
"the",
"model",
".",
"Finally",
"updade",
"the",
"context",
"menu",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/quanty.py#L1774-L1791 | train |
mretegan/crispy | crispy/gui/quanty.py | QuantyDockWidget.updatePlotWidget | def updatePlotWidget(self):
"""Updating the plotting widget should not require any information
about the current state of the widget."""
pw = self.getPlotWidget()
pw.reset()
results = self.resultsModel.getCheckedItems()
for result in results:
if isinstance(r... | python | def updatePlotWidget(self):
"""Updating the plotting widget should not require any information
about the current state of the widget."""
pw = self.getPlotWidget()
pw.reset()
results = self.resultsModel.getCheckedItems()
for result in results:
if isinstance(r... | [
"def",
"updatePlotWidget",
"(",
"self",
")",
":",
"pw",
"=",
"self",
".",
"getPlotWidget",
"(",
")",
"pw",
".",
"reset",
"(",
")",
"results",
"=",
"self",
".",
"resultsModel",
".",
"getCheckedItems",
"(",
")",
"for",
"result",
"in",
"results",
":",
"if... | Updating the plotting widget should not require any information
about the current state of the widget. | [
"Updating",
"the",
"plotting",
"widget",
"should",
"not",
"require",
"any",
"information",
"about",
"the",
"current",
"state",
"of",
"the",
"widget",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/quanty.py#L1832-L1854 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianItem.row | def row(self):
"""Return the row of the child."""
if self.parent is not None:
children = self.parent.getChildren()
# The index method of the list object.
return children.index(self)
else:
return 0 | python | def row(self):
"""Return the row of the child."""
if self.parent is not None:
children = self.parent.getChildren()
# The index method of the list object.
return children.index(self)
else:
return 0 | [
"def",
"row",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"children",
"=",
"self",
".",
"parent",
".",
"getChildren",
"(",
")",
"# The index method of the list object.",
"return",
"children",
".",
"index",
"(",
"self",
")"... | Return the row of the child. | [
"Return",
"the",
"row",
"of",
"the",
"child",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L254-L261 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel.index | def index(self, row, column, parent=QModelIndex()):
"""Return the index of the item in the model specified by the
given row, column, and parent index.
"""
if parent is not None and not parent.isValid():
parentItem = self.rootItem
else:
parentItem = self.it... | python | def index(self, row, column, parent=QModelIndex()):
"""Return the index of the item in the model specified by the
given row, column, and parent index.
"""
if parent is not None and not parent.isValid():
parentItem = self.rootItem
else:
parentItem = self.it... | [
"def",
"index",
"(",
"self",
",",
"row",
",",
"column",
",",
"parent",
"=",
"QModelIndex",
"(",
")",
")",
":",
"if",
"parent",
"is",
"not",
"None",
"and",
"not",
"parent",
".",
"isValid",
"(",
")",
":",
"parentItem",
"=",
"self",
".",
"rootItem",
"... | Return the index of the item in the model specified by the
given row, column, and parent index. | [
"Return",
"the",
"index",
"of",
"the",
"item",
"in",
"the",
"model",
"specified",
"by",
"the",
"given",
"row",
"column",
"and",
"parent",
"index",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L307-L323 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel.parent | def parent(self, index):
"""Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item.
"""
... | python | def parent(self, index):
"""Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item.
"""
... | [
"def",
"parent",
"(",
"self",
",",
"index",
")",
":",
"childItem",
"=",
"self",
".",
"item",
"(",
"index",
")",
"parentItem",
"=",
"childItem",
".",
"parent",
"if",
"parentItem",
"==",
"self",
".",
"rootItem",
":",
"parentIndex",
"=",
"QModelIndex",
"(",... | Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item. | [
"Return",
"the",
"index",
"of",
"the",
"parent",
"for",
"a",
"given",
"index",
"of",
"the",
"child",
".",
"Unfortunately",
"the",
"name",
"of",
"the",
"method",
"has",
"to",
"be",
"parent",
"even",
"though",
"a",
"more",
"verbose",
"name",
"like",
"paren... | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L325-L339 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel.rowCount | def rowCount(self, parentIndex):
"""Return the number of rows under the given parent. When the
parentIndex is valid, rowCount() returns the number of children
of the parent. For this it uses item() method to extract the
parentItem from the parentIndex, and calls the childCount() of
... | python | def rowCount(self, parentIndex):
"""Return the number of rows under the given parent. When the
parentIndex is valid, rowCount() returns the number of children
of the parent. For this it uses item() method to extract the
parentItem from the parentIndex, and calls the childCount() of
... | [
"def",
"rowCount",
"(",
"self",
",",
"parentIndex",
")",
":",
"if",
"parentIndex",
".",
"column",
"(",
")",
">",
"0",
":",
"return",
"0",
"if",
"not",
"parentIndex",
".",
"isValid",
"(",
")",
":",
"parentItem",
"=",
"self",
".",
"rootItem",
"else",
"... | Return the number of rows under the given parent. When the
parentIndex is valid, rowCount() returns the number of children
of the parent. For this it uses item() method to extract the
parentItem from the parentIndex, and calls the childCount() of
the item to get number of children. | [
"Return",
"the",
"number",
"of",
"rows",
"under",
"the",
"given",
"parent",
".",
"When",
"the",
"parentIndex",
"is",
"valid",
"rowCount",
"()",
"returns",
"the",
"number",
"of",
"children",
"of",
"the",
"parent",
".",
"For",
"this",
"it",
"uses",
"item",
... | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L358-L373 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel.data | def data(self, index, role):
"""Return role specific data for the item referred by
index.column()."""
if not index.isValid():
return
item = self.item(index)
column = index.column()
value = item.getItemData(column)
if role == Qt.DisplayRole:
... | python | def data(self, index, role):
"""Return role specific data for the item referred by
index.column()."""
if not index.isValid():
return
item = self.item(index)
column = index.column()
value = item.getItemData(column)
if role == Qt.DisplayRole:
... | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"item",
"=",
"self",
".",
"item",
"(",
"index",
")",
"column",
"=",
"index",
".",
"column",
"(",
")",
"value",
"=",
... | Return role specific data for the item referred by
index.column(). | [
"Return",
"role",
"specific",
"data",
"for",
"the",
"item",
"referred",
"by",
"index",
".",
"column",
"()",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L382-L418 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel.setData | def setData(self, index, value, role):
"""Set the role data for the item at index to value."""
if not index.isValid():
return False
item = self.item(index)
column = index.column()
if role == Qt.EditRole:
items = list()
items.append(item)
... | python | def setData(self, index, value, role):
"""Set the role data for the item at index to value."""
if not index.isValid():
return False
item = self.item(index)
column = index.column()
if role == Qt.EditRole:
items = list()
items.append(item)
... | [
"def",
"setData",
"(",
"self",
",",
"index",
",",
"value",
",",
"role",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"False",
"item",
"=",
"self",
".",
"item",
"(",
"index",
")",
"column",
"=",
"index",
".",
"column",
... | Set the role data for the item at index to value. | [
"Set",
"the",
"role",
"data",
"for",
"the",
"item",
"at",
"index",
"to",
"value",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L420-L459 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel.flags | def flags(self, index):
"""Return the active flags for the given index. Add editable
flag to items other than the first column.
"""
activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable)
item = self.item(index)
column = ind... | python | def flags(self, index):
"""Return the active flags for the given index. Add editable
flag to items other than the first column.
"""
activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable)
item = self.item(index)
column = ind... | [
"def",
"flags",
"(",
"self",
",",
"index",
")",
":",
"activeFlags",
"=",
"(",
"Qt",
".",
"ItemIsEnabled",
"|",
"Qt",
".",
"ItemIsSelectable",
"|",
"Qt",
".",
"ItemIsUserCheckable",
")",
"item",
"=",
"self",
".",
"item",
"(",
"index",
")",
"column",
"="... | Return the active flags for the given index. Add editable
flag to items other than the first column. | [
"Return",
"the",
"active",
"flags",
"for",
"the",
"given",
"index",
".",
"Add",
"editable",
"flag",
"to",
"items",
"other",
"than",
"the",
"first",
"column",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L464-L477 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel._getModelData | def _getModelData(self, modelData, parentItem=None):
"""Return the data contained in the model."""
if parentItem is None:
parentItem = self.rootItem
for item in parentItem.getChildren():
key = item.getItemData(0)
if item.childCount():
modelDat... | python | def _getModelData(self, modelData, parentItem=None):
"""Return the data contained in the model."""
if parentItem is None:
parentItem = self.rootItem
for item in parentItem.getChildren():
key = item.getItemData(0)
if item.childCount():
modelDat... | [
"def",
"_getModelData",
"(",
"self",
",",
"modelData",
",",
"parentItem",
"=",
"None",
")",
":",
"if",
"parentItem",
"is",
"None",
":",
"parentItem",
"=",
"self",
".",
"rootItem",
"for",
"item",
"in",
"parentItem",
".",
"getChildren",
"(",
")",
":",
"key... | Return the data contained in the model. | [
"Return",
"the",
"data",
"contained",
"in",
"the",
"model",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L533-L547 | train |
mretegan/crispy | crispy/gui/models.py | HamiltonianModel.getNodesCheckState | def getNodesCheckState(self, parentItem=None):
"""Return the check state (disabled, tristate, enable) of all items
belonging to a parent.
"""
if parentItem is None:
parentItem = self.rootItem
checkStates = odict()
children = parentItem.getChildren()
... | python | def getNodesCheckState(self, parentItem=None):
"""Return the check state (disabled, tristate, enable) of all items
belonging to a parent.
"""
if parentItem is None:
parentItem = self.rootItem
checkStates = odict()
children = parentItem.getChildren()
... | [
"def",
"getNodesCheckState",
"(",
"self",
",",
"parentItem",
"=",
"None",
")",
":",
"if",
"parentItem",
"is",
"None",
":",
"parentItem",
"=",
"self",
".",
"rootItem",
"checkStates",
"=",
"odict",
"(",
")",
"children",
"=",
"parentItem",
".",
"getChildren",
... | Return the check state (disabled, tristate, enable) of all items
belonging to a parent. | [
"Return",
"the",
"check",
"state",
"(",
"disabled",
"tristate",
"enable",
")",
"of",
"all",
"items",
"belonging",
"to",
"a",
"parent",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/models.py#L567-L580 | train |
mretegan/crispy | crispy/version.py | calc_hexversion | def calc_hexversion(major=0, minor=0, micro=0, releaselevel='dev', serial=0):
"""Calculate the hexadecimal version number from the tuple version_info:
:param major: integer
:param minor: integer
:param micro: integer
:param relev: integer or string
:param serial: integer
:return: integerm a... | python | def calc_hexversion(major=0, minor=0, micro=0, releaselevel='dev', serial=0):
"""Calculate the hexadecimal version number from the tuple version_info:
:param major: integer
:param minor: integer
:param micro: integer
:param relev: integer or string
:param serial: integer
:return: integerm a... | [
"def",
"calc_hexversion",
"(",
"major",
"=",
"0",
",",
"minor",
"=",
"0",
",",
"micro",
"=",
"0",
",",
"releaselevel",
"=",
"'dev'",
",",
"serial",
"=",
"0",
")",
":",
"try",
":",
"releaselevel",
"=",
"int",
"(",
"releaselevel",
")",
"except",
"Value... | Calculate the hexadecimal version number from the tuple version_info:
:param major: integer
:param minor: integer
:param micro: integer
:param relev: integer or string
:param serial: integer
:return: integerm always increasing with revision numbers | [
"Calculate",
"the",
"hexadecimal",
"version",
"number",
"from",
"the",
"tuple",
"version_info",
":"
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/version.py#L89-L109 | train |
mretegan/crispy | crispy/gui/plot.py | MainPlotWidget._contextMenu | def _contextMenu(self, pos):
"""Handle plot area customContextMenuRequested signal.
:param QPoint pos: Mouse position relative to plot area
"""
# Create the context menu.
menu = QMenu(self)
menu.addAction(self._zoomBackAction)
# Displaying the context menu at th... | python | def _contextMenu(self, pos):
"""Handle plot area customContextMenuRequested signal.
:param QPoint pos: Mouse position relative to plot area
"""
# Create the context menu.
menu = QMenu(self)
menu.addAction(self._zoomBackAction)
# Displaying the context menu at th... | [
"def",
"_contextMenu",
"(",
"self",
",",
"pos",
")",
":",
"# Create the context menu.",
"menu",
"=",
"QMenu",
"(",
"self",
")",
"menu",
".",
"addAction",
"(",
"self",
".",
"_zoomBackAction",
")",
"# Displaying the context menu at the mouse position requires",
"# a glo... | Handle plot area customContextMenuRequested signal.
:param QPoint pos: Mouse position relative to plot area | [
"Handle",
"plot",
"area",
"customContextMenuRequested",
"signal",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/gui/plot.py#L247-L262 | train |
mretegan/crispy | crispy/utils/broaden.py | convolve_fft | def convolve_fft(array, kernel):
"""
Convolve an array with a kernel using FFT.
Implemntation based on the convolve_fft function from astropy.
https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py
"""
array = np.asarray(array, dtype=np.complex)
kernel = np.asarray(... | python | def convolve_fft(array, kernel):
"""
Convolve an array with a kernel using FFT.
Implemntation based on the convolve_fft function from astropy.
https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py
"""
array = np.asarray(array, dtype=np.complex)
kernel = np.asarray(... | [
"def",
"convolve_fft",
"(",
"array",
",",
"kernel",
")",
":",
"array",
"=",
"np",
".",
"asarray",
"(",
"array",
",",
"dtype",
"=",
"np",
".",
"complex",
")",
"kernel",
"=",
"np",
".",
"asarray",
"(",
"kernel",
",",
"dtype",
"=",
"np",
".",
"complex... | Convolve an array with a kernel using FFT.
Implemntation based on the convolve_fft function from astropy.
https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py | [
"Convolve",
"an",
"array",
"with",
"a",
"kernel",
"using",
"FFT",
".",
"Implemntation",
"based",
"on",
"the",
"convolve_fft",
"function",
"from",
"astropy",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/utils/broaden.py#L65-L114 | train |
mretegan/crispy | crispy/modules/orca/parser.py | Tensor.diagonalize | def diagonalize(self):
'''Diagonalize the tensor.'''
self.eigvals, self.eigvecs = np.linalg.eig(
(self.tensor.transpose() + self.tensor) / 2.0)
self.eigvals = np.diag(np.dot(
np.dot(self.eigvecs.transpose(), self.tensor), self.eigvecs)) | python | def diagonalize(self):
'''Diagonalize the tensor.'''
self.eigvals, self.eigvecs = np.linalg.eig(
(self.tensor.transpose() + self.tensor) / 2.0)
self.eigvals = np.diag(np.dot(
np.dot(self.eigvecs.transpose(), self.tensor), self.eigvecs)) | [
"def",
"diagonalize",
"(",
"self",
")",
":",
"self",
".",
"eigvals",
",",
"self",
".",
"eigvecs",
"=",
"np",
".",
"linalg",
".",
"eig",
"(",
"(",
"self",
".",
"tensor",
".",
"transpose",
"(",
")",
"+",
"self",
".",
"tensor",
")",
"/",
"2.0",
")",... | Diagonalize the tensor. | [
"Diagonalize",
"the",
"tensor",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/modules/orca/parser.py#L61-L66 | train |
mretegan/crispy | crispy/modules/orca/parser.py | Tensor.euler_angles_and_eigenframes | def euler_angles_and_eigenframes(self):
'''Calculate the Euler angles only if the rotation matrix
(eigenframe) has positive determinant.'''
signs = np.array([[1, 1, 1], [-1, 1, 1], [1, -1, 1],
[1, 1, -1], [-1, -1, 1], [-1, 1, -1],
[1, -1, -1... | python | def euler_angles_and_eigenframes(self):
'''Calculate the Euler angles only if the rotation matrix
(eigenframe) has positive determinant.'''
signs = np.array([[1, 1, 1], [-1, 1, 1], [1, -1, 1],
[1, 1, -1], [-1, -1, 1], [-1, 1, -1],
[1, -1, -1... | [
"def",
"euler_angles_and_eigenframes",
"(",
"self",
")",
":",
"signs",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"1",
",",
"1",
"]",
",",
"[",
"-",
"1",
",",
"1",
",",
"1",
"]",
",",
"[",
"1",
",",
"-",
"1",
",",
"1",
"]",
",",
"[... | Calculate the Euler angles only if the rotation matrix
(eigenframe) has positive determinant. | [
"Calculate",
"the",
"Euler",
"angles",
"only",
"if",
"the",
"rotation",
"matrix",
"(",
"eigenframe",
")",
"has",
"positive",
"determinant",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/modules/orca/parser.py#L75-L92 | train |
mretegan/crispy | crispy/modules/orca/parser.py | OutputData._skip_lines | def _skip_lines(self, n):
'''Skip a number of lines from the output.'''
for i in range(n):
self.line = next(self.output)
return self.line | python | def _skip_lines(self, n):
'''Skip a number of lines from the output.'''
for i in range(n):
self.line = next(self.output)
return self.line | [
"def",
"_skip_lines",
"(",
"self",
",",
"n",
")",
":",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"self",
".",
"line",
"=",
"next",
"(",
"self",
".",
"output",
")",
"return",
"self",
".",
"line"
] | Skip a number of lines from the output. | [
"Skip",
"a",
"number",
"of",
"lines",
"from",
"the",
"output",
"."
] | 7e241ac1a48d34ca769f3a6183c430360b5f6725 | https://github.com/mretegan/crispy/blob/7e241ac1a48d34ca769f3a6183c430360b5f6725/crispy/modules/orca/parser.py#L151-L155 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.