repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
zimeon/iiif
iiif/auth.py
IIIFAuth.access_token_valid
def access_token_valid(self, token, log_msg): """Check token validity. Returns true if the token is valid. The set of allowed access tokens is stored in self.access_tokens. Uses log_msg as prefix to info level log message of acceptance or rejection. """ if (toke...
python
def access_token_valid(self, token, log_msg): """Check token validity. Returns true if the token is valid. The set of allowed access tokens is stored in self.access_tokens. Uses log_msg as prefix to info level log message of acceptance or rejection. """ if (toke...
[ "def", "access_token_valid", "(", "self", ",", "token", ",", "log_msg", ")", ":", "if", "(", "token", "in", "self", ".", "access_tokens", ")", ":", "(", "cookie", ",", "issue_time", ")", "=", "self", ".", "access_tokens", "[", "token", "]", "age", "=",...
Check token validity. Returns true if the token is valid. The set of allowed access tokens is stored in self.access_tokens. Uses log_msg as prefix to info level log message of acceptance or rejection.
[ "Check", "token", "validity", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth.py#L271-L298
zimeon/iiif
iiif/auth_flask.py
IIIFAuthFlask.info_authn
def info_authn(self): """Check to see if user if authenticated for info.json. Must have Authorization header with value that has the form "Bearer TOKEN", where TOKEN is an appropriate and valid access token. """ authz_header = request.headers.get('Authorization', '[none]...
python
def info_authn(self): """Check to see if user if authenticated for info.json. Must have Authorization header with value that has the form "Bearer TOKEN", where TOKEN is an appropriate and valid access token. """ authz_header = request.headers.get('Authorization', '[none]...
[ "def", "info_authn", "(", "self", ")", ":", "authz_header", "=", "request", ".", "headers", ".", "get", "(", "'Authorization'", ",", "'[none]'", ")", "if", "(", "not", "authz_header", ".", "startswith", "(", "'Bearer '", ")", ")", ":", "return", "False", ...
Check to see if user if authenticated for info.json. Must have Authorization header with value that has the form "Bearer TOKEN", where TOKEN is an appropriate and valid access token.
[ "Check", "to", "see", "if", "user", "if", "authenticated", "for", "info", ".", "json", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_flask.py#L23-L35
zimeon/iiif
iiif/auth_flask.py
IIIFAuthFlask.image_authn
def image_authn(self): """Check to see if user if authenticated for image requests. Must have access cookie with an appropriate value. """ authn_cookie = request.cookies.get( self.access_cookie_name, default='[none]') return self.access_cookie_valid(authn_cookie, "im...
python
def image_authn(self): """Check to see if user if authenticated for image requests. Must have access cookie with an appropriate value. """ authn_cookie = request.cookies.get( self.access_cookie_name, default='[none]') return self.access_cookie_valid(authn_cookie, "im...
[ "def", "image_authn", "(", "self", ")", ":", "authn_cookie", "=", "request", ".", "cookies", ".", "get", "(", "self", ".", "access_cookie_name", ",", "default", "=", "'[none]'", ")", "return", "self", ".", "access_cookie_valid", "(", "authn_cookie", ",", "\"...
Check to see if user if authenticated for image requests. Must have access cookie with an appropriate value.
[ "Check", "to", "see", "if", "user", "if", "authenticated", "for", "image", "requests", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_flask.py#L37-L44
zimeon/iiif
iiif/auth_flask.py
IIIFAuthFlask.logout_handler
def logout_handler(self, **args): """Handler for logout button. Delete cookies and return HTML that immediately closes window """ response = make_response( "<html><script>window.close();</script></html>", 200, {'Content-Type': "text/html"}) response.set_c...
python
def logout_handler(self, **args): """Handler for logout button. Delete cookies and return HTML that immediately closes window """ response = make_response( "<html><script>window.close();</script></html>", 200, {'Content-Type': "text/html"}) response.set_c...
[ "def", "logout_handler", "(", "self", ",", "*", "*", "args", ")", ":", "response", "=", "make_response", "(", "\"<html><script>window.close();</script></html>\"", ",", "200", ",", "{", "'Content-Type'", ":", "\"text/html\"", "}", ")", "response", ".", "set_cookie"...
Handler for logout button. Delete cookies and return HTML that immediately closes window
[ "Handler", "for", "logout", "button", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_flask.py#L57-L68
zimeon/iiif
iiif/auth_flask.py
IIIFAuthFlask.access_token_handler
def access_token_handler(self, **args): """Get access token based on cookie sent with this request. This handler deals with two cases: 1) Non-browser client (indicated by no messageId set in request) where the response is a simple JSON response. 2) Browser client (indicate by ...
python
def access_token_handler(self, **args): """Get access token based on cookie sent with this request. This handler deals with two cases: 1) Non-browser client (indicated by no messageId set in request) where the response is a simple JSON response. 2) Browser client (indicate by ...
[ "def", "access_token_handler", "(", "self", ",", "*", "*", "args", ")", ":", "message_id", "=", "request", ".", "args", ".", "get", "(", "'messageId'", ",", "default", "=", "None", ")", "origin", "=", "request", ".", "args", ".", "get", "(", "'origin'"...
Get access token based on cookie sent with this request. This handler deals with two cases: 1) Non-browser client (indicated by no messageId set in request) where the response is a simple JSON response. 2) Browser client (indicate by messageId setin request) where the request ...
[ "Get", "access", "token", "based", "on", "cookie", "sent", "with", "this", "request", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_flask.py#L70-L121
zimeon/iiif
iiif/auth_flask.py
IIIFAuthFlask.set_cookie_close_window_response
def set_cookie_close_window_response(self, account_cookie_value): """Response to set account cookie and close window HTML/JavaScript.""" response = make_response( "<html><script>window.close();</script></html>", 200, {'Content-Type': "text/html"}) response.set_cookie(self...
python
def set_cookie_close_window_response(self, account_cookie_value): """Response to set account cookie and close window HTML/JavaScript.""" response = make_response( "<html><script>window.close();</script></html>", 200, {'Content-Type': "text/html"}) response.set_cookie(self...
[ "def", "set_cookie_close_window_response", "(", "self", ",", "account_cookie_value", ")", ":", "response", "=", "make_response", "(", "\"<html><script>window.close();</script></html>\"", ",", "200", ",", "{", "'Content-Type'", ":", "\"text/html\"", "}", ")", "response", ...
Response to set account cookie and close window HTML/JavaScript.
[ "Response", "to", "set", "account", "cookie", "and", "close", "window", "HTML", "/", "JavaScript", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_flask.py#L123-L130
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.find_binaries
def find_binaries(cls, tmpdir=None, shellsetup=None, pnmdir=None): """Set instance variables for directory and binary locations. FIXME - should accept params to set things other than defaults. """ cls.tmpdir = ('/tmp' if (tmpdir is None) else tmpdir) # Shell setup command (e.g s...
python
def find_binaries(cls, tmpdir=None, shellsetup=None, pnmdir=None): """Set instance variables for directory and binary locations. FIXME - should accept params to set things other than defaults. """ cls.tmpdir = ('/tmp' if (tmpdir is None) else tmpdir) # Shell setup command (e.g s...
[ "def", "find_binaries", "(", "cls", ",", "tmpdir", "=", "None", ",", "shellsetup", "=", "None", ",", "pnmdir", "=", "None", ")", ":", "cls", ".", "tmpdir", "=", "(", "'/tmp'", "if", "(", "tmpdir", "is", "None", ")", "else", "tmpdir", ")", "# Shell se...
Set instance variables for directory and binary locations. FIXME - should accept params to set things other than defaults.
[ "Set", "instance", "variables", "for", "directory", "and", "binary", "locations", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L41-L70
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.do_first
def do_first(self): """Create PNM file from input image file.""" pid = os.getpid() self.basename = os.path.join(self.tmpdir, 'iiif_netpbm_' + str(pid)) outfile = self.basename + '.pnm' # Convert source file to pnm filetype = self.file_type(self.srcfile) if (filety...
python
def do_first(self): """Create PNM file from input image file.""" pid = os.getpid() self.basename = os.path.join(self.tmpdir, 'iiif_netpbm_' + str(pid)) outfile = self.basename + '.pnm' # Convert source file to pnm filetype = self.file_type(self.srcfile) if (filety...
[ "def", "do_first", "(", "self", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "self", ".", "basename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tmpdir", ",", "'iiif_netpbm_'", "+", "str", "(", "pid", ")", ")", "outfile", "="...
Create PNM file from input image file.
[ "Create", "PNM", "file", "from", "input", "image", "file", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L72-L90
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.do_region
def do_region(self, x, y, w, h): """Apply region selection.""" infile = self.tmpfile outfile = self.basename + '.reg' # simeon@ice ~>cat m.pnm | pnmcut 10 10 100 200 > m1.pnm if (x is None): # print "region: full" self.tmpfile = infile else: ...
python
def do_region(self, x, y, w, h): """Apply region selection.""" infile = self.tmpfile outfile = self.basename + '.reg' # simeon@ice ~>cat m.pnm | pnmcut 10 10 100 200 > m1.pnm if (x is None): # print "region: full" self.tmpfile = infile else: ...
[ "def", "do_region", "(", "self", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "infile", "=", "self", ".", "tmpfile", "outfile", "=", "self", ".", "basename", "+", "'.reg'", "# simeon@ice ~>cat m.pnm | pnmcut 10 10 100 200 > m1.pnm", "if", "(", "x", "i...
Apply region selection.
[ "Apply", "region", "selection", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L92-L106
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.do_size
def do_size(self, w, h): """Apply size scaling.""" # simeon@ice ~>cat m1.pnm | pnmscale -width 50 > m2.pnm infile = self.tmpfile outfile = self.basename + '.siz' if (w is None): # print "size: no scaling" self.tmpfile = infile else: # p...
python
def do_size(self, w, h): """Apply size scaling.""" # simeon@ice ~>cat m1.pnm | pnmscale -width 50 > m2.pnm infile = self.tmpfile outfile = self.basename + '.siz' if (w is None): # print "size: no scaling" self.tmpfile = infile else: # p...
[ "def", "do_size", "(", "self", ",", "w", ",", "h", ")", ":", "# simeon@ice ~>cat m1.pnm | pnmscale -width 50 > m2.pnm", "infile", "=", "self", ".", "tmpfile", "outfile", "=", "self", ".", "basename", "+", "'.siz'", "if", "(", "w", "is", "None", ")", ":", "...
Apply size scaling.
[ "Apply", "size", "scaling", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L108-L123
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.do_rotation
def do_rotation(self, mirror, rot): """Apply rotation and/or mirroring.""" infile = self.tmpfile outfile = self.basename + '.rot' # NOTE: pnmrotate: angle must be between -90 and 90 and # rotations is CCW not CW per IIIF spec # # BUG in pnmrotate: +90 and -90 rota...
python
def do_rotation(self, mirror, rot): """Apply rotation and/or mirroring.""" infile = self.tmpfile outfile = self.basename + '.rot' # NOTE: pnmrotate: angle must be between -90 and 90 and # rotations is CCW not CW per IIIF spec # # BUG in pnmrotate: +90 and -90 rota...
[ "def", "do_rotation", "(", "self", ",", "mirror", ",", "rot", ")", ":", "infile", "=", "self", ".", "tmpfile", "outfile", "=", "self", ".", "basename", "+", "'.rot'", "# NOTE: pnmrotate: angle must be between -90 and 90 and", "# rotations is CCW not CW per IIIF spec", ...
Apply rotation and/or mirroring.
[ "Apply", "rotation", "and", "/", "or", "mirroring", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L125-L174
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.do_quality
def do_quality(self, quality): """Apply value of quality parameter.""" infile = self.tmpfile outfile = self.basename + '.col' # Quality (bit-depth): if (quality == 'grey' or quality == 'gray'): if (self.shell_call('cat ' + infile + ' | ' + self.ppmtopgm + ' > ' + outf...
python
def do_quality(self, quality): """Apply value of quality parameter.""" infile = self.tmpfile outfile = self.basename + '.col' # Quality (bit-depth): if (quality == 'grey' or quality == 'gray'): if (self.shell_call('cat ' + infile + ' | ' + self.ppmtopgm + ' > ' + outf...
[ "def", "do_quality", "(", "self", ",", "quality", ")", ":", "infile", "=", "self", ".", "tmpfile", "outfile", "=", "self", ".", "basename", "+", "'.col'", "# Quality (bit-depth):", "if", "(", "quality", "==", "'grey'", "or", "quality", "==", "'gray'", ")",...
Apply value of quality parameter.
[ "Apply", "value", "of", "quality", "parameter", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L176-L197
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.do_format
def do_format(self, format): """Apply format selection.""" infile = self.tmpfile outfile = self.basename + '.out' outfile_jp2 = self.basename + '.jp2' # Now convert finished pnm file to output format # simeon@ice ~>cat m3.pnm | pnmtojpeg > m4.jpg # simeon@ice ~>c...
python
def do_format(self, format): """Apply format selection.""" infile = self.tmpfile outfile = self.basename + '.out' outfile_jp2 = self.basename + '.jp2' # Now convert finished pnm file to output format # simeon@ice ~>cat m3.pnm | pnmtojpeg > m4.jpg # simeon@ice ~>c...
[ "def", "do_format", "(", "self", ",", "format", ")", ":", "infile", "=", "self", ".", "tmpfile", "outfile", "=", "self", ".", "basename", "+", "'.out'", "outfile_jp2", "=", "self", ".", "basename", "+", "'.jp2'", "# Now convert finished pnm file to output format...
Apply format selection.
[ "Apply", "format", "selection", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L199-L242
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.file_type
def file_type(self, file): """Use python-magic to determine file type. Returns 'png' or 'jpg' on success, nothing on failure. """ try: magic_text = magic.from_file(file) if (isinstance(magic_text, bytes)): # In python2 and travis python3 (?!) deco...
python
def file_type(self, file): """Use python-magic to determine file type. Returns 'png' or 'jpg' on success, nothing on failure. """ try: magic_text = magic.from_file(file) if (isinstance(magic_text, bytes)): # In python2 and travis python3 (?!) deco...
[ "def", "file_type", "(", "self", ",", "file", ")", ":", "try", ":", "magic_text", "=", "magic", ".", "from_file", "(", "file", ")", "if", "(", "isinstance", "(", "magic_text", ",", "bytes", ")", ")", ":", "# In python2 and travis python3 (?!) decode to get uni...
Use python-magic to determine file type. Returns 'png' or 'jpg' on success, nothing on failure.
[ "Use", "python", "-", "magic", "to", "determine", "file", "type", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L244-L261
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.image_size
def image_size(self, pnmfile): """Get width and height of pnm file. simeon@homebox src>pnmfile /tmp/214-2.png /tmp/214-2.png:PPM raw, 100 by 100 maxval 255 """ pout = os.popen(self.shellsetup + self.pnmfile + ' ' + pnmfile, 'r') pnmfileout = pout.read(200) pout....
python
def image_size(self, pnmfile): """Get width and height of pnm file. simeon@homebox src>pnmfile /tmp/214-2.png /tmp/214-2.png:PPM raw, 100 by 100 maxval 255 """ pout = os.popen(self.shellsetup + self.pnmfile + ' ' + pnmfile, 'r') pnmfileout = pout.read(200) pout....
[ "def", "image_size", "(", "self", ",", "pnmfile", ")", ":", "pout", "=", "os", ".", "popen", "(", "self", ".", "shellsetup", "+", "self", ".", "pnmfile", "+", "' '", "+", "pnmfile", ",", "'r'", ")", "pnmfileout", "=", "pout", ".", "read", "(", "200...
Get width and height of pnm file. simeon@homebox src>pnmfile /tmp/214-2.png /tmp/214-2.png:PPM raw, 100 by 100 maxval 255
[ "Get", "width", "and", "height", "of", "pnm", "file", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L263-L280
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.shell_call
def shell_call(self, shellcmd): """Shell call with necessary setup first.""" return(subprocess.call(self.shellsetup + shellcmd, shell=True))
python
def shell_call(self, shellcmd): """Shell call with necessary setup first.""" return(subprocess.call(self.shellsetup + shellcmd, shell=True))
[ "def", "shell_call", "(", "self", ",", "shellcmd", ")", ":", "return", "(", "subprocess", ".", "call", "(", "self", ".", "shellsetup", "+", "shellcmd", ",", "shell", "=", "True", ")", ")" ]
Shell call with necessary setup first.
[ "Shell", "call", "with", "necessary", "setup", "first", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L282-L284
zimeon/iiif
iiif/manipulator_netpbm.py
IIIFManipulatorNetpbm.cleanup
def cleanup(self): """Clean up any temporary files.""" for file in glob.glob(self.basename + '*'): os.unlink(file)
python
def cleanup(self): """Clean up any temporary files.""" for file in glob.glob(self.basename + '*'): os.unlink(file)
[ "def", "cleanup", "(", "self", ")", ":", "for", "file", "in", "glob", ".", "glob", "(", "self", ".", "basename", "+", "'*'", ")", ":", "os", ".", "unlink", "(", "file", ")" ]
Clean up any temporary files.
[ "Clean", "up", "any", "temporary", "files", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_netpbm.py#L286-L289
zimeon/iiif
iiif/error.py
IIIFError.image_server_response
def image_server_response(self, api_version=None): """Response, code and headers for image server error response. api_version selects the format (XML of 1.0). The return value is a tuple of response - body of HTTP response status - the HTTP status code headers - a ...
python
def image_server_response(self, api_version=None): """Response, code and headers for image server error response. api_version selects the format (XML of 1.0). The return value is a tuple of response - body of HTTP response status - the HTTP status code headers - a ...
[ "def", "image_server_response", "(", "self", ",", "api_version", "=", "None", ")", ":", "headers", "=", "dict", "(", "self", ".", "headers", ")", "if", "(", "api_version", "<", "'1.1'", ")", ":", "headers", "[", "'Content-Type'", "]", "=", "'text/xml'", ...
Response, code and headers for image server error response. api_version selects the format (XML of 1.0). The return value is a tuple of response - body of HTTP response status - the HTTP status code headers - a dict of HTTP headers which will include the Content-Type ...
[ "Response", "code", "and", "headers", "for", "image", "server", "error", "response", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/error.py#L50-L69
zimeon/iiif
iiif/error.py
IIIFError.as_xml
def as_xml(self): """XML representation of the error to be used in HTTP response. This XML format follows the IIIF Image API v1.0 specification, see <http://iiif.io/api/image/1.0/#error> """ # Build tree spacing = ("\n" if (self.pretty_xml) else "") root = Elemen...
python
def as_xml(self): """XML representation of the error to be used in HTTP response. This XML format follows the IIIF Image API v1.0 specification, see <http://iiif.io/api/image/1.0/#error> """ # Build tree spacing = ("\n" if (self.pretty_xml) else "") root = Elemen...
[ "def", "as_xml", "(", "self", ")", ":", "# Build tree", "spacing", "=", "(", "\"\\n\"", "if", "(", "self", ".", "pretty_xml", ")", "else", "\"\"", ")", "root", "=", "Element", "(", "'error'", ",", "{", "'xmlns'", ":", "I3F_NS", "}", ")", "root", ".",...
XML representation of the error to be used in HTTP response. This XML format follows the IIIF Image API v1.0 specification, see <http://iiif.io/api/image/1.0/#error>
[ "XML", "representation", "of", "the", "error", "to", "be", "used", "in", "HTTP", "response", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/error.py#L71-L98
zimeon/iiif
iiif/error.py
IIIFError.as_txt
def as_txt(self): """Text rendering of error response. Designed for use with Image API version 1.1 and above where the error response is suggested to be text or html but not otherwise specified. Intended to provide useful information for debugging. """ s = "IIIF Image Se...
python
def as_txt(self): """Text rendering of error response. Designed for use with Image API version 1.1 and above where the error response is suggested to be text or html but not otherwise specified. Intended to provide useful information for debugging. """ s = "IIIF Image Se...
[ "def", "as_txt", "(", "self", ")", ":", "s", "=", "\"IIIF Image Server Error\\n\\n\"", "s", "+=", "self", ".", "text", "if", "(", "self", ".", "text", ")", "else", "'UNKNOWN_ERROR'", "s", "+=", "\"\\n\\n\"", "if", "(", "self", ".", "parameter", ")", ":",...
Text rendering of error response. Designed for use with Image API version 1.1 and above where the error response is suggested to be text or html but not otherwise specified. Intended to provide useful information for debugging.
[ "Text", "rendering", "of", "error", "response", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/error.py#L100-L116
zimeon/iiif
iiif/auth_google.py
IIIFAuthGoogle.login_handler
def login_handler(self, config=None, prefix=None, **args): """OAuth starts here, redirect user to Google.""" params = { 'response_type': 'code', 'client_id': self.google_api_client_id, 'redirect_uri': self.scheme_host_port_prefix( 'http', config.host, ...
python
def login_handler(self, config=None, prefix=None, **args): """OAuth starts here, redirect user to Google.""" params = { 'response_type': 'code', 'client_id': self.google_api_client_id, 'redirect_uri': self.scheme_host_port_prefix( 'http', config.host, ...
[ "def", "login_handler", "(", "self", ",", "config", "=", "None", ",", "prefix", "=", "None", ",", "*", "*", "args", ")", ":", "params", "=", "{", "'response_type'", ":", "'code'", ",", "'client_id'", ":", "self", ".", "google_api_client_id", ",", "'redir...
OAuth starts here, redirect user to Google.
[ "OAuth", "starts", "here", "redirect", "user", "to", "Google", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_google.py#L53-L64
zimeon/iiif
iiif/auth_google.py
IIIFAuthGoogle.home_handler
def home_handler(self, config=None, prefix=None, **args): """Handler for /home redirect path after Google auth. OAuth ends up back here from Google. Set the account cookie and close window to trigger next step. """ gresponse = self.google_get_token(config, prefix) gdata ...
python
def home_handler(self, config=None, prefix=None, **args): """Handler for /home redirect path after Google auth. OAuth ends up back here from Google. Set the account cookie and close window to trigger next step. """ gresponse = self.google_get_token(config, prefix) gdata ...
[ "def", "home_handler", "(", "self", ",", "config", "=", "None", ",", "prefix", "=", "None", ",", "*", "*", "args", ")", ":", "gresponse", "=", "self", ".", "google_get_token", "(", "config", ",", "prefix", ")", "gdata", "=", "self", ".", "google_get_da...
Handler for /home redirect path after Google auth. OAuth ends up back here from Google. Set the account cookie and close window to trigger next step.
[ "Handler", "for", "/", "home", "redirect", "path", "after", "Google", "auth", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_google.py#L66-L78
zimeon/iiif
iiif/auth_google.py
IIIFAuthGoogle.google_get_token
def google_get_token(self, config, prefix): """Make request to Google API to get token.""" params = { 'code': self.request_args_get( 'code', default=''), 'client_id': self.google_api_client_id, 'client_secret': self.google_api_client_se...
python
def google_get_token(self, config, prefix): """Make request to Google API to get token.""" params = { 'code': self.request_args_get( 'code', default=''), 'client_id': self.google_api_client_id, 'client_secret': self.google_api_client_se...
[ "def", "google_get_token", "(", "self", ",", "config", ",", "prefix", ")", ":", "params", "=", "{", "'code'", ":", "self", ".", "request_args_get", "(", "'code'", ",", "default", "=", "''", ")", ",", "'client_id'", ":", "self", ".", "google_api_client_id",...
Make request to Google API to get token.
[ "Make", "request", "to", "Google", "API", "to", "get", "token", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_google.py#L84-L100
zimeon/iiif
iiif/auth_google.py
IIIFAuthGoogle.google_get_data
def google_get_data(self, config, response): """Make request to Google API to get profile data for the user.""" params = { 'access_token': response['access_token'], } payload = urlencode(params) url = self.google_api_url + 'userinfo?' + payload req = Request(u...
python
def google_get_data(self, config, response): """Make request to Google API to get profile data for the user.""" params = { 'access_token': response['access_token'], } payload = urlencode(params) url = self.google_api_url + 'userinfo?' + payload req = Request(u...
[ "def", "google_get_data", "(", "self", ",", "config", ",", "response", ")", ":", "params", "=", "{", "'access_token'", ":", "response", "[", "'access_token'", "]", ",", "}", "payload", "=", "urlencode", "(", "params", ")", "url", "=", "self", ".", "googl...
Make request to Google API to get profile data for the user.
[ "Make", "request", "to", "Google", "API", "to", "get", "profile", "data", "for", "the", "user", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_google.py#L102-L111
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.compliance_uri
def compliance_uri(self): """Compliance URI based on api_version. Value is based on api_version and complicance_level, will be None if either are unset/unrecognized. The assumption here is that the api_version and level are orthogonal, override this method if that isn't true. ...
python
def compliance_uri(self): """Compliance URI based on api_version. Value is based on api_version and complicance_level, will be None if either are unset/unrecognized. The assumption here is that the api_version and level are orthogonal, override this method if that isn't true. ...
[ "def", "compliance_uri", "(", "self", ")", ":", "if", "(", "self", ".", "api_version", "==", "'1.0'", ")", ":", "uri_pattern", "=", "r'http://library.stanford.edu/iiif/image-api/compliance.html#level%d'", "elif", "(", "self", ".", "api_version", "==", "'1.1'", ")", ...
Compliance URI based on api_version. Value is based on api_version and complicance_level, will be None if either are unset/unrecognized. The assumption here is that the api_version and level are orthogonal, override this method if that isn't true.
[ "Compliance", "URI", "based", "on", "api_version", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L49-L68
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.derive
def derive(self, srcfile=None, request=None, outfile=None): """Do sequence of manipulations for IIIF to derive output image. Named argments: srcfile -- source image file request -- IIIFRequest object with parsed parameters outfile -- output image file. If set the the output file...
python
def derive(self, srcfile=None, request=None, outfile=None): """Do sequence of manipulations for IIIF to derive output image. Named argments: srcfile -- source image file request -- IIIFRequest object with parsed parameters outfile -- output image file. If set the the output file...
[ "def", "derive", "(", "self", ",", "srcfile", "=", "None", ",", "request", "=", "None", ",", "outfile", "=", "None", ")", ":", "# set if specified", "if", "(", "srcfile", "is", "not", "None", ")", ":", "self", ".", "srcfile", "=", "srcfile", "if", "(...
Do sequence of manipulations for IIIF to derive output image. Named argments: srcfile -- source image file request -- IIIFRequest object with parsed parameters outfile -- output image file. If set the the output file will be written to that file, otherwise a new tempo...
[ "Do", "sequence", "of", "manipulations", "for", "IIIF", "to", "derive", "output", "image", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L70-L120
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.do_region
def do_region(self, x, y, w, h): """Null implementation of region selection.""" if (x is not None): raise IIIFError(code=501, parameter="region", text="Null manipulator supports only region=/full/.")
python
def do_region(self, x, y, w, h): """Null implementation of region selection.""" if (x is not None): raise IIIFError(code=501, parameter="region", text="Null manipulator supports only region=/full/.")
[ "def", "do_region", "(", "self", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "if", "(", "x", "is", "not", "None", ")", ":", "raise", "IIIFError", "(", "code", "=", "501", ",", "parameter", "=", "\"region\"", ",", "text", "=", "\"Null manipu...
Null implementation of region selection.
[ "Null", "implementation", "of", "region", "selection", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L130-L134
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.do_rotation
def do_rotation(self, mirror, rot): """Null implementation of rotate and/or mirror.""" if (mirror): raise IIIFError(code=501, parameter="rotation", text="Null manipulator does not support mirroring.") if (rot != 0.0): raise IIIFError(code=501, ...
python
def do_rotation(self, mirror, rot): """Null implementation of rotate and/or mirror.""" if (mirror): raise IIIFError(code=501, parameter="rotation", text="Null manipulator does not support mirroring.") if (rot != 0.0): raise IIIFError(code=501, ...
[ "def", "do_rotation", "(", "self", ",", "mirror", ",", "rot", ")", ":", "if", "(", "mirror", ")", ":", "raise", "IIIFError", "(", "code", "=", "501", ",", "parameter", "=", "\"rotation\"", ",", "text", "=", "\"Null manipulator does not support mirroring.\"", ...
Null implementation of rotate and/or mirror.
[ "Null", "implementation", "of", "rotate", "and", "/", "or", "mirror", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L142-L149
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.do_quality
def do_quality(self, quality): """Null implementation of quality.""" if (self.api_version >= '2.0'): if (quality != "default"): raise IIIFError(code=501, parameter="default", text="Null manipulator supports only quality=default.") else:...
python
def do_quality(self, quality): """Null implementation of quality.""" if (self.api_version >= '2.0'): if (quality != "default"): raise IIIFError(code=501, parameter="default", text="Null manipulator supports only quality=default.") else:...
[ "def", "do_quality", "(", "self", ",", "quality", ")", ":", "if", "(", "self", ".", "api_version", ">=", "'2.0'", ")", ":", "if", "(", "quality", "!=", "\"default\"", ")", ":", "raise", "IIIFError", "(", "code", "=", "501", ",", "parameter", "=", "\"...
Null implementation of quality.
[ "Null", "implementation", "of", "quality", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L151-L160
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.do_format
def do_format(self, format): """Null implementation of format selection. This is the last step, this null implementation does not accept any specification of a format because we don't even know what the input format is. """ if (format is not None): raise IIIF...
python
def do_format(self, format): """Null implementation of format selection. This is the last step, this null implementation does not accept any specification of a format because we don't even know what the input format is. """ if (format is not None): raise IIIF...
[ "def", "do_format", "(", "self", ",", "format", ")", ":", "if", "(", "format", "is", "not", "None", ")", ":", "raise", "IIIFError", "(", "code", "=", "415", ",", "parameter", "=", "\"format\"", ",", "text", "=", "\"Null manipulator does not support specifica...
Null implementation of format selection. This is the last step, this null implementation does not accept any specification of a format because we don't even know what the input format is.
[ "Null", "implementation", "of", "format", "selection", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L162-L181
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.region_to_apply
def region_to_apply(self): """Return the x,y,w,h parameters to extract given image width and height. Assume image width and height are available in self.width and self.height, and self.request is IIIFRequest object Expected use: (x,y,w,h) = self.region_to_apply() if...
python
def region_to_apply(self): """Return the x,y,w,h parameters to extract given image width and height. Assume image width and height are available in self.width and self.height, and self.request is IIIFRequest object Expected use: (x,y,w,h) = self.region_to_apply() if...
[ "def", "region_to_apply", "(", "self", ")", ":", "if", "(", "self", ".", "request", ".", "region_full", "or", "(", "self", ".", "request", ".", "region_pct", "and", "self", ".", "request", ".", "region_xywh", "==", "(", "0", ",", "0", ",", "100", ","...
Return the x,y,w,h parameters to extract given image width and height. Assume image width and height are available in self.width and self.height, and self.request is IIIFRequest object Expected use: (x,y,w,h) = self.region_to_apply() if (x is None): # full ima...
[ "Return", "the", "x", "y", "w", "h", "parameters", "to", "extract", "given", "image", "width", "and", "height", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L192-L243
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.size_to_apply
def size_to_apply(self): """Calculate size of image scaled using size parameters. Assumes current image width and height are available in self.width and self.height, and self.request is IIIFRequest object. Formats are: w, ,h w,h pct:p !w,h full max Returns (None,None) if no sc...
python
def size_to_apply(self): """Calculate size of image scaled using size parameters. Assumes current image width and height are available in self.width and self.height, and self.request is IIIFRequest object. Formats are: w, ,h w,h pct:p !w,h full max Returns (None,None) if no sc...
[ "def", "size_to_apply", "(", "self", ")", ":", "if", "(", "self", ".", "request", ".", "size_full", "or", "self", ".", "request", ".", "size_pct", "==", "100.0", ")", ":", "# full size", "return", "(", "None", ",", "None", ")", "# Not trivially full size, ...
Calculate size of image scaled using size parameters. Assumes current image width and height are available in self.width and self.height, and self.request is IIIFRequest object. Formats are: w, ,h w,h pct:p !w,h full max Returns (None,None) if no scaling is required. If max i...
[ "Calculate", "size", "of", "image", "scaled", "using", "size", "parameters", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L245-L313
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.rotation_to_apply
def rotation_to_apply(self, only90s=False, no_mirror=False): """Check and interpret rotation. Returns a truth value as to whether to mirror, and a floating point number 0 <= angle < 360 (degrees). """ rotation = self.request.rotation_deg if (no_mirror and self.request.ro...
python
def rotation_to_apply(self, only90s=False, no_mirror=False): """Check and interpret rotation. Returns a truth value as to whether to mirror, and a floating point number 0 <= angle < 360 (degrees). """ rotation = self.request.rotation_deg if (no_mirror and self.request.ro...
[ "def", "rotation_to_apply", "(", "self", ",", "only90s", "=", "False", ",", "no_mirror", "=", "False", ")", ":", "rotation", "=", "self", ".", "request", ".", "rotation_deg", "if", "(", "no_mirror", "and", "self", ".", "request", ".", "rotation_mirror", ")...
Check and interpret rotation. Returns a truth value as to whether to mirror, and a floating point number 0 <= angle < 360 (degrees).
[ "Check", "and", "interpret", "rotation", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L315-L329
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.quality_to_apply
def quality_to_apply(self): """Value of quality parameter to use in processing request. Simple substitution of 'native' or 'default' if no quality parameter is specified. """ if (self.request.quality is None): if (self.api_version <= '1.1'): return('n...
python
def quality_to_apply(self): """Value of quality parameter to use in processing request. Simple substitution of 'native' or 'default' if no quality parameter is specified. """ if (self.request.quality is None): if (self.api_version <= '1.1'): return('n...
[ "def", "quality_to_apply", "(", "self", ")", ":", "if", "(", "self", ".", "request", ".", "quality", "is", "None", ")", ":", "if", "(", "self", ".", "api_version", "<=", "'1.1'", ")", ":", "return", "(", "'native'", ")", "else", ":", "return", "(", ...
Value of quality parameter to use in processing request. Simple substitution of 'native' or 'default' if no quality parameter is specified.
[ "Value", "of", "quality", "parameter", "to", "use", "in", "processing", "request", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L331-L342
zimeon/iiif
iiif/manipulator.py
IIIFManipulator.scale_factors
def scale_factors(self, tile_width, tile_height=None): """Return a set of scale factors for given tile and window size. Gives a set of scale factors, starting at 1, and in multiples of 2. Largest scale_factor is so that one tile will cover the entire image (self.width,self.height). ...
python
def scale_factors(self, tile_width, tile_height=None): """Return a set of scale factors for given tile and window size. Gives a set of scale factors, starting at 1, and in multiples of 2. Largest scale_factor is so that one tile will cover the entire image (self.width,self.height). ...
[ "def", "scale_factors", "(", "self", ",", "tile_width", ",", "tile_height", "=", "None", ")", ":", "if", "(", "not", "tile_height", ")", ":", "tile_height", "=", "tile_width", "sf", "=", "1", "scale_factors", "=", "[", "sf", "]", "for", "j", "in", "ran...
Return a set of scale factors for given tile and window size. Gives a set of scale factors, starting at 1, and in multiples of 2. Largest scale_factor is so that one tile will cover the entire image (self.width,self.height). If tile_height is not specified then tiles are assumed to be ...
[ "Return", "a", "set", "of", "scale", "factors", "for", "given", "tile", "and", "window", "size", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L353-L373
zimeon/iiif
iiif/generators/diagonal_cross.py
PixelGen.pixel
def pixel(self, x, y, size=None): """Return color for a pixel.""" if (size is None): size = self.sz # Have we go to the smallest element? if (size <= 3): if (_not_diagonal(x, y)): return None else: return (0, 0, 0) ...
python
def pixel(self, x, y, size=None): """Return color for a pixel.""" if (size is None): size = self.sz # Have we go to the smallest element? if (size <= 3): if (_not_diagonal(x, y)): return None else: return (0, 0, 0) ...
[ "def", "pixel", "(", "self", ",", "x", ",", "y", ",", "size", "=", "None", ")", ":", "if", "(", "size", "is", "None", ")", ":", "size", "=", "self", ".", "sz", "# Have we go to the smallest element?", "if", "(", "size", "<=", "3", ")", ":", "if", ...
Return color for a pixel.
[ "Return", "color", "for", "a", "pixel", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/generators/diagonal_cross.py#L29-L42
zimeon/iiif
iiif/generators/mandlebrot_100k.py
PixelGen.color
def color(self, n): """Color of pixel that reached limit after n iterations. Returns a color tuple for use with PIL, tending toward red as we tend toward self.max_iter iterations. """ red = int(n * self.shade_factor) if (red > 255): red = 255 return (...
python
def color(self, n): """Color of pixel that reached limit after n iterations. Returns a color tuple for use with PIL, tending toward red as we tend toward self.max_iter iterations. """ red = int(n * self.shade_factor) if (red > 255): red = 255 return (...
[ "def", "color", "(", "self", ",", "n", ")", ":", "red", "=", "int", "(", "n", "*", "self", ".", "shade_factor", ")", "if", "(", "red", ">", "255", ")", ":", "red", "=", "255", "return", "(", "red", ",", "50", ",", "100", ")" ]
Color of pixel that reached limit after n iterations. Returns a color tuple for use with PIL, tending toward red as we tend toward self.max_iter iterations.
[ "Color", "of", "pixel", "that", "reached", "limit", "after", "n", "iterations", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/generators/mandlebrot_100k.py#L44-L53
zimeon/iiif
iiif/generators/mandlebrot_100k.py
PixelGen.mpixel
def mpixel(self, z, n=0): """Iteration in Mandlebrot coordinate z.""" z = z * z + self.c if (abs(z) > 2.0): return self.color(n) n += 1 if (n > self.max_iter): return None return self.mpixel(z, n)
python
def mpixel(self, z, n=0): """Iteration in Mandlebrot coordinate z.""" z = z * z + self.c if (abs(z) > 2.0): return self.color(n) n += 1 if (n > self.max_iter): return None return self.mpixel(z, n)
[ "def", "mpixel", "(", "self", ",", "z", ",", "n", "=", "0", ")", ":", "z", "=", "z", "*", "z", "+", "self", ".", "c", "if", "(", "abs", "(", "z", ")", ">", "2.0", ")", ":", "return", "self", ".", "color", "(", "n", ")", "n", "+=", "1", ...
Iteration in Mandlebrot coordinate z.
[ "Iteration", "in", "Mandlebrot", "coordinate", "z", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/generators/mandlebrot_100k.py#L55-L63
zimeon/iiif
iiif/generators/mandlebrot_100k.py
PixelGen.pixel
def pixel(self, ix, iy): """Return color for a pixel. Does translation from image coordinates (ix,iy) into the complex plane coordinate z = x+yi, and then calls self.mpixel(z) to find the color at point z. """ x = (ix - self.xoffset + 0.5) / self.scale y = (iy - ...
python
def pixel(self, ix, iy): """Return color for a pixel. Does translation from image coordinates (ix,iy) into the complex plane coordinate z = x+yi, and then calls self.mpixel(z) to find the color at point z. """ x = (ix - self.xoffset + 0.5) / self.scale y = (iy - ...
[ "def", "pixel", "(", "self", ",", "ix", ",", "iy", ")", ":", "x", "=", "(", "ix", "-", "self", ".", "xoffset", "+", "0.5", ")", "/", "self", ".", "scale", "y", "=", "(", "iy", "-", "self", ".", "yoffset", "+", "0.5", ")", "/", "self", ".", ...
Return color for a pixel. Does translation from image coordinates (ix,iy) into the complex plane coordinate z = x+yi, and then calls self.mpixel(z) to find the color at point z.
[ "Return", "color", "for", "a", "pixel", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/generators/mandlebrot_100k.py#L65-L76
zimeon/iiif
iiif/static.py
static_partial_tile_sizes
def static_partial_tile_sizes(width, height, tilesize, scale_factors): """Generator for partial tile sizes for zoomed in views. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles scale_factors -- iterable of scale fa...
python
def static_partial_tile_sizes(width, height, tilesize, scale_factors): """Generator for partial tile sizes for zoomed in views. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles scale_factors -- iterable of scale fa...
[ "def", "static_partial_tile_sizes", "(", "width", ",", "height", ",", "tilesize", ",", "scale_factors", ")", ":", "for", "sf", "in", "scale_factors", ":", "if", "(", "sf", "*", "tilesize", ">=", "width", "and", "sf", "*", "tilesize", ">=", "height", ")", ...
Generator for partial tile sizes for zoomed in views. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles scale_factors -- iterable of scale factors, typically [1,2,4..] Yields ([rx,ry,rw,rh],[sw,sh]), the region and...
[ "Generator", "for", "partial", "tile", "sizes", "for", "zoomed", "in", "views", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L21-L54
zimeon/iiif
iiif/static.py
static_full_sizes
def static_full_sizes(width, height, tilesize): """Generator for scaled-down full image sizes. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles Yields [sw,sh], the size for each full-region tile that is less than ...
python
def static_full_sizes(width, height, tilesize): """Generator for scaled-down full image sizes. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles Yields [sw,sh], the size for each full-region tile that is less than ...
[ "def", "static_full_sizes", "(", "width", ",", "height", ",", "tilesize", ")", ":", "# FIXME - Not sure what correct algorithm is for this, from", "# observation of Openseadragon it seems that one keeps halving", "# the pixel size of the full image until until both width and", "# height ar...
Generator for scaled-down full image sizes. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles Yields [sw,sh], the size for each full-region tile that is less than the tilesize. This includes tiles up to the full im...
[ "Generator", "for", "scaled", "-", "down", "full", "image", "sizes", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L57-L89
zimeon/iiif
iiif/static.py
IIIFStatic.parse_extra
def parse_extra(self, extra): """Parse extra request parameters to IIIFRequest object.""" if extra.startswith('/'): extra = extra[1:] r = IIIFRequest(identifier='dummy', api_version=self.api_version) r.parse_url(extra) if (r.info): ...
python
def parse_extra(self, extra): """Parse extra request parameters to IIIFRequest object.""" if extra.startswith('/'): extra = extra[1:] r = IIIFRequest(identifier='dummy', api_version=self.api_version) r.parse_url(extra) if (r.info): ...
[ "def", "parse_extra", "(", "self", ",", "extra", ")", ":", "if", "extra", ".", "startswith", "(", "'/'", ")", ":", "extra", "=", "extra", "[", "1", ":", "]", "r", "=", "IIIFRequest", "(", "identifier", "=", "'dummy'", ",", "api_version", "=", "self",...
Parse extra request parameters to IIIFRequest object.
[ "Parse", "extra", "request", "parameters", "to", "IIIFRequest", "object", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L191-L200
zimeon/iiif
iiif/static.py
IIIFStatic.get_osd_config
def get_osd_config(self, osd_version): """Select appropriate portion of config. If the version requested is not supported the raise an exception with a helpful error message listing the versions supported. """ if (osd_version in self.osd_config): return(self.osd_conf...
python
def get_osd_config(self, osd_version): """Select appropriate portion of config. If the version requested is not supported the raise an exception with a helpful error message listing the versions supported. """ if (osd_version in self.osd_config): return(self.osd_conf...
[ "def", "get_osd_config", "(", "self", ",", "osd_version", ")", ":", "if", "(", "osd_version", "in", "self", ".", "osd_config", ")", ":", "return", "(", "self", ".", "osd_config", "[", "osd_version", "]", ")", "else", ":", "raise", "IIIFStaticError", "(", ...
Select appropriate portion of config. If the version requested is not supported the raise an exception with a helpful error message listing the versions supported.
[ "Select", "appropriate", "portion", "of", "config", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L202-L212
zimeon/iiif
iiif/static.py
IIIFStatic.generate
def generate(self, src=None, identifier=None): """Generate static files for one source image.""" self.src = src self.identifier = identifier # Get image details and calculate tiles im = self.manipulator_klass() im.srcfile = self.src im.set_max_image_pixels(self.ma...
python
def generate(self, src=None, identifier=None): """Generate static files for one source image.""" self.src = src self.identifier = identifier # Get image details and calculate tiles im = self.manipulator_klass() im.srcfile = self.src im.set_max_image_pixels(self.ma...
[ "def", "generate", "(", "self", ",", "src", "=", "None", ",", "identifier", "=", "None", ")", ":", "self", ".", "src", "=", "src", "self", ".", "identifier", "=", "identifier", "# Get image details and calculate tiles", "im", "=", "self", ".", "manipulator_k...
Generate static files for one source image.
[ "Generate", "static", "files", "for", "one", "source", "image", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L214-L261
zimeon/iiif
iiif/static.py
IIIFStatic.generate_tile
def generate_tile(self, region, size): """Generate one tile for this given region, size of this image.""" r = IIIFRequest(identifier=self.identifier, api_version=self.api_version) if (region == 'full'): r.region_full = True else: r.region_x...
python
def generate_tile(self, region, size): """Generate one tile for this given region, size of this image.""" r = IIIFRequest(identifier=self.identifier, api_version=self.api_version) if (region == 'full'): r.region_full = True else: r.region_x...
[ "def", "generate_tile", "(", "self", ",", "region", ",", "size", ")", ":", "r", "=", "IIIFRequest", "(", "identifier", "=", "self", ".", "identifier", ",", "api_version", "=", "self", ".", "api_version", ")", "if", "(", "region", "==", "'full'", ")", "...
Generate one tile for this given region, size of this image.
[ "Generate", "one", "tile", "for", "this", "given", "region", "size", "of", "this", "image", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L263-L273
zimeon/iiif
iiif/static.py
IIIFStatic.generate_file
def generate_file(self, r, undistorted=False): """Generate file for IIIFRequest object r from this image. FIXME - Would be nicer to have the test for an undistorted image request based on the IIIFRequest object, and then know whether to apply canonicalization or not. Logically ...
python
def generate_file(self, r, undistorted=False): """Generate file for IIIFRequest object r from this image. FIXME - Would be nicer to have the test for an undistorted image request based on the IIIFRequest object, and then know whether to apply canonicalization or not. Logically ...
[ "def", "generate_file", "(", "self", ",", "r", ",", "undistorted", "=", "False", ")", ":", "use_canonical", "=", "self", ".", "get_osd_config", "(", "self", ".", "osd_version", ")", "[", "'use_canonical'", "]", "height", "=", "None", "if", "(", "undistorte...
Generate file for IIIFRequest object r from this image. FIXME - Would be nicer to have the test for an undistorted image request based on the IIIFRequest object, and then know whether to apply canonicalization or not. Logically we might use `w,h` instead of the Image API v2.0 canonical...
[ "Generate", "file", "for", "IIIFRequest", "object", "r", "from", "this", "image", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L275-L329
zimeon/iiif
iiif/static.py
IIIFStatic.setup_destination
def setup_destination(self): """Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure. """ # Do we have a separate identifier? if (not self.identifier): # No separate identi...
python
def setup_destination(self): """Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure. """ # Do we have a separate identifier? if (not self.identifier): # No separate identi...
[ "def", "setup_destination", "(", "self", ")", ":", "# Do we have a separate identifier?", "if", "(", "not", "self", ".", "identifier", ")", ":", "# No separate identifier specified, split off the last path segment", "# of the source name, strip the extension to get the identifier", ...
Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure.
[ "Setup", "output", "directory", "based", "on", "self", ".", "dst", "and", "self", ".", "identifier", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L331-L368
zimeon/iiif
iiif/static.py
IIIFStatic.write_html
def write_html(self, html_dir='/tmp', include_osd=False, osd_width=500, osd_height=500): """Write HTML test page using OpenSeadragon for the tiles generated. Assumes that the generate(..) method has already been called to set up identifier etc. Parameters: html_dir ...
python
def write_html(self, html_dir='/tmp', include_osd=False, osd_width=500, osd_height=500): """Write HTML test page using OpenSeadragon for the tiles generated. Assumes that the generate(..) method has already been called to set up identifier etc. Parameters: html_dir ...
[ "def", "write_html", "(", "self", ",", "html_dir", "=", "'/tmp'", ",", "include_osd", "=", "False", ",", "osd_width", "=", "500", ",", "osd_height", "=", "500", ")", ":", "osd_config", "=", "self", ".", "get_osd_config", "(", "self", ".", "osd_version", ...
Write HTML test page using OpenSeadragon for the tiles generated. Assumes that the generate(..) method has already been called to set up identifier etc. Parameters: html_dir - output directory for HTML files, will be created if it does not already exist include_...
[ "Write", "HTML", "test", "page", "using", "OpenSeadragon", "for", "the", "tiles", "generated", "." ]
train
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L370-L436
polyaxon/polyaxon-schemas
polyaxon_schemas/utils.py
get_value
def get_value(key, obj, default=missing): """Helper for pulling a keyed value off various types of objects""" if isinstance(key, int): return _get_value_for_key(key, obj, default) return _get_value_for_keys(key.split('.'), obj, default)
python
def get_value(key, obj, default=missing): """Helper for pulling a keyed value off various types of objects""" if isinstance(key, int): return _get_value_for_key(key, obj, default) return _get_value_for_keys(key.split('.'), obj, default)
[ "def", "get_value", "(", "key", ",", "obj", ",", "default", "=", "missing", ")", ":", "if", "isinstance", "(", "key", ",", "int", ")", ":", "return", "_get_value_for_key", "(", "key", ",", "obj", ",", "default", ")", "return", "_get_value_for_keys", "(",...
Helper for pulling a keyed value off various types of objects
[ "Helper", "for", "pulling", "a", "keyed", "value", "off", "various", "types", "of", "objects" ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/utils.py#L371-L375
polyaxon/polyaxon-schemas
polyaxon_schemas/utils.py
UnknownSchemaMixin._handle_load_unknown
def _handle_load_unknown(self, data, original): """Preserve unknown keys during deserialization.""" for key, val in original.items(): if key not in self.fields: data[key] = val return data
python
def _handle_load_unknown(self, data, original): """Preserve unknown keys during deserialization.""" for key, val in original.items(): if key not in self.fields: data[key] = val return data
[ "def", "_handle_load_unknown", "(", "self", ",", "data", ",", "original", ")", ":", "for", "key", ",", "val", "in", "original", ".", "items", "(", ")", ":", "if", "key", "not", "in", "self", ".", "fields", ":", "data", "[", "key", "]", "=", "val", ...
Preserve unknown keys during deserialization.
[ "Preserve", "unknown", "keys", "during", "deserialization", "." ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/utils.py#L352-L357
polyaxon/polyaxon-schemas
polyaxon_schemas/utils.py
UnknownSchemaMixin._handle_dump_unknown
def _handle_dump_unknown(self, data, original): """Preserve unknown keys during deserialization.""" for key, val in original.items(): if key not in self.fields: data[key] = val return data
python
def _handle_dump_unknown(self, data, original): """Preserve unknown keys during deserialization.""" for key, val in original.items(): if key not in self.fields: data[key] = val return data
[ "def", "_handle_dump_unknown", "(", "self", ",", "data", ",", "original", ")", ":", "for", "key", ",", "val", "in", "original", ".", "items", "(", ")", ":", "if", "key", "not", "in", "self", ".", "fields", ":", "data", "[", "key", "]", "=", "val", ...
Preserve unknown keys during deserialization.
[ "Preserve", "unknown", "keys", "during", "deserialization", "." ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/utils.py#L360-L365
polyaxon/polyaxon-schemas
polyaxon_schemas/specs/libs/validator.py
validate_headers
def validate_headers(spec, data): """Validates headers data and creates the config objects""" validated_data = { spec.VERSION: data[spec.VERSION], spec.KIND: data[spec.KIND], } if data.get(spec.LOGGING): validated_data[spec.LOGGING] = LoggingConfig.from_dict( data[sp...
python
def validate_headers(spec, data): """Validates headers data and creates the config objects""" validated_data = { spec.VERSION: data[spec.VERSION], spec.KIND: data[spec.KIND], } if data.get(spec.LOGGING): validated_data[spec.LOGGING] = LoggingConfig.from_dict( data[sp...
[ "def", "validate_headers", "(", "spec", ",", "data", ")", ":", "validated_data", "=", "{", "spec", ".", "VERSION", ":", "data", "[", "spec", ".", "VERSION", "]", ",", "spec", ".", "KIND", ":", "data", "[", "spec", ".", "KIND", "]", ",", "}", "if", ...
Validates headers data and creates the config objects
[ "Validates", "headers", "data", "and", "creates", "the", "config", "objects" ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/specs/libs/validator.py#L16-L34
polyaxon/polyaxon-schemas
polyaxon_schemas/specs/libs/validator.py
validate
def validate(spec, data): """Validates the data and creates the config objects""" data = copy.deepcopy(data) validated_data = {} def validate_keys(section, config, section_data): if not isinstance(section_data, dict) or section == spec.MODEL: return extra_args = [key for ke...
python
def validate(spec, data): """Validates the data and creates the config objects""" data = copy.deepcopy(data) validated_data = {} def validate_keys(section, config, section_data): if not isinstance(section_data, dict) or section == spec.MODEL: return extra_args = [key for ke...
[ "def", "validate", "(", "spec", ",", "data", ")", ":", "data", "=", "copy", ".", "deepcopy", "(", "data", ")", "validated_data", "=", "{", "}", "def", "validate_keys", "(", "section", ",", "config", ",", "section_data", ")", ":", "if", "not", "isinstan...
Validates the data and creates the config objects
[ "Validates", "the", "data", "and", "creates", "the", "config", "objects" ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/specs/libs/validator.py#L37-L64
polyaxon/polyaxon-schemas
polyaxon_schemas/ops/experiment.py
ExperimentSchema.validate_replicas
def validate_replicas(self, data): """Validate distributed experiment""" environment = data.get('environment') if environment and environment.replicas: validate_replicas(data.get('framework'), environment.replicas)
python
def validate_replicas(self, data): """Validate distributed experiment""" environment = data.get('environment') if environment and environment.replicas: validate_replicas(data.get('framework'), environment.replicas)
[ "def", "validate_replicas", "(", "self", ",", "data", ")", ":", "environment", "=", "data", ".", "get", "(", "'environment'", ")", "if", "environment", "and", "environment", ".", "replicas", ":", "validate_replicas", "(", "data", ".", "get", "(", "'framework...
Validate distributed experiment
[ "Validate", "distributed", "experiment" ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/ops/experiment.py#L89-L93
polyaxon/polyaxon-schemas
polyaxon_schemas/specs/group.py
GroupSpecification.get_experiment_spec
def get_experiment_spec(self, matrix_declaration): """Returns an experiment spec for this group spec and the given matrix declaration.""" parsed_data = Parser.parse(self, self._data, matrix_declaration) del parsed_data[self.HP_TUNING] validator.validate(spec=self, data=parsed_data) ...
python
def get_experiment_spec(self, matrix_declaration): """Returns an experiment spec for this group spec and the given matrix declaration.""" parsed_data = Parser.parse(self, self._data, matrix_declaration) del parsed_data[self.HP_TUNING] validator.validate(spec=self, data=parsed_data) ...
[ "def", "get_experiment_spec", "(", "self", ",", "matrix_declaration", ")", ":", "parsed_data", "=", "Parser", ".", "parse", "(", "self", ",", "self", ".", "_data", ",", "matrix_declaration", ")", "del", "parsed_data", "[", "self", ".", "HP_TUNING", "]", "val...
Returns an experiment spec for this group spec and the given matrix declaration.
[ "Returns", "an", "experiment", "spec", "for", "this", "group", "spec", "and", "the", "given", "matrix", "declaration", "." ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/specs/group.py#L75-L80
polyaxon/polyaxon-schemas
polyaxon_schemas/specs/group.py
GroupSpecification.get_build_spec
def get_build_spec(self): """Returns a build spec for this group spec.""" if BaseSpecification.BUILD not in self._data: return None return BuildConfig.from_dict(self._data[BaseSpecification.BUILD])
python
def get_build_spec(self): """Returns a build spec for this group spec.""" if BaseSpecification.BUILD not in self._data: return None return BuildConfig.from_dict(self._data[BaseSpecification.BUILD])
[ "def", "get_build_spec", "(", "self", ")", ":", "if", "BaseSpecification", ".", "BUILD", "not", "in", "self", ".", "_data", ":", "return", "None", "return", "BuildConfig", ".", "from_dict", "(", "self", ".", "_data", "[", "BaseSpecification", ".", "BUILD", ...
Returns a build spec for this group spec.
[ "Returns", "a", "build", "spec", "for", "this", "group", "spec", "." ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/specs/group.py#L82-L86
polyaxon/polyaxon-schemas
polyaxon_schemas/ops/hptuning.py
HPTuningSchema.validate_matrix
def validate_matrix(self, data): """Validates matrix data and creates the config objects""" is_grid_search = ( data.get('grid_search') is not None or (data.get('grid_search') is None and data.get('random_search') is None and data.get('hyperband') is None...
python
def validate_matrix(self, data): """Validates matrix data and creates the config objects""" is_grid_search = ( data.get('grid_search') is not None or (data.get('grid_search') is None and data.get('random_search') is None and data.get('hyperband') is None...
[ "def", "validate_matrix", "(", "self", ",", "data", ")", ":", "is_grid_search", "=", "(", "data", ".", "get", "(", "'grid_search'", ")", "is", "not", "None", "or", "(", "data", ".", "get", "(", "'grid_search'", ")", "is", "None", "and", "data", ".", ...
Validates matrix data and creates the config objects
[ "Validates", "matrix", "data", "and", "creates", "the", "config", "objects" ]
train
https://github.com/polyaxon/polyaxon-schemas/blob/a5360240316f4bbccfcdcb97a489cab14458277a/polyaxon_schemas/ops/hptuning.py#L371-L381
inorton/junit2html
junit2htmlreport/parser.py
AnchorBase.anchor
def anchor(self): """ Generate a html anchor name :return: """ if not self._anchor: self._anchor = str(uuid.uuid4()) return self._anchor
python
def anchor(self): """ Generate a html anchor name :return: """ if not self._anchor: self._anchor = str(uuid.uuid4()) return self._anchor
[ "def", "anchor", "(", "self", ")", ":", "if", "not", "self", ".", "_anchor", ":", "self", ".", "_anchor", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "return", "self", ".", "_anchor" ]
Generate a html anchor name :return:
[ "Generate", "a", "html", "anchor", "name", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L24-L31
inorton/junit2html
junit2htmlreport/parser.py
Class.html
def html(self): """ Render this test class as html :return: """ cases = [x.html() for x in self.cases] return """ <hr size="2"/> <a name="{anchor}"> <div class="testclass"> <div>Test Class: {name}</div> <div class="testcase...
python
def html(self): """ Render this test class as html :return: """ cases = [x.html() for x in self.cases] return """ <hr size="2"/> <a name="{anchor}"> <div class="testclass"> <div>Test Class: {name}</div> <div class="testcase...
[ "def", "html", "(", "self", ")", ":", "cases", "=", "[", "x", ".", "html", "(", ")", "for", "x", "in", "self", ".", "cases", "]", "return", "\"\"\"\n <hr size=\"2\"/>\n <a name=\"{anchor}\">\n <div class=\"testclass\">\n <div>Test Class: {n...
Render this test class as html :return:
[ "Render", "this", "test", "class", "as", "html", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L43-L63
inorton/junit2html
junit2htmlreport/parser.py
Property.html
def html(self): """ Render those properties as html :return: """ return """ <div class="property"><i>{name}</i><br/> <pre>{value}</pre></div> """.format(name=tag.text(self.name), value=tag.text(self.value))
python
def html(self): """ Render those properties as html :return: """ return """ <div class="property"><i>{name}</i><br/> <pre>{value}</pre></div> """.format(name=tag.text(self.name), value=tag.text(self.value))
[ "def", "html", "(", "self", ")", ":", "return", "\"\"\"\n <div class=\"property\"><i>{name}</i><br/>\n <pre>{value}</pre></div>\n \"\"\"", ".", "format", "(", "name", "=", "tag", ".", "text", "(", "self", ".", "name", ")", ",", "value", "=", "tag"...
Render those properties as html :return:
[ "Render", "those", "properties", "as", "html", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L74-L82
inorton/junit2html
junit2htmlreport/parser.py
Case.html
def html(self): """ Render this test case as HTML :return: """ failure = "" skipped = None stdout = tag.text(self.stdout) stderr = tag.text(self.stderr) if self.skipped: skipped = """ <hr size="1"/> <div class="...
python
def html(self): """ Render this test case as HTML :return: """ failure = "" skipped = None stdout = tag.text(self.stdout) stderr = tag.text(self.stderr) if self.skipped: skipped = """ <hr size="1"/> <div class="...
[ "def", "html", "(", "self", ")", ":", "failure", "=", "\"\"", "skipped", "=", "None", "stdout", "=", "tag", ".", "text", "(", "self", ".", "stdout", ")", "stderr", "=", "tag", ".", "text", "(", "self", ".", "stderr", ")", "if", "self", ".", "skip...
Render this test case as HTML :return:
[ "Render", "this", "test", "case", "as", "HTML", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L108-L165
inorton/junit2html
junit2htmlreport/parser.py
Suite.all
def all(self): """ Return all testcases :return: """ tests = list() for testclass in self.classes: tests.extend(self.classes[testclass].cases) return tests
python
def all(self): """ Return all testcases :return: """ tests = list() for testclass in self.classes: tests.extend(self.classes[testclass].cases) return tests
[ "def", "all", "(", "self", ")", ":", "tests", "=", "list", "(", ")", "for", "testclass", "in", "self", ".", "classes", ":", "tests", ".", "extend", "(", "self", ".", "classes", "[", "testclass", "]", ".", "cases", ")", "return", "tests" ]
Return all testcases :return:
[ "Return", "all", "testcases", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L208-L216
inorton/junit2html
junit2htmlreport/parser.py
Suite.passed
def passed(self): """ Return all the passing testcases :return: """ return [test for test in self.all() if not test.failed() and not test.skipped()]
python
def passed(self): """ Return all the passing testcases :return: """ return [test for test in self.all() if not test.failed() and not test.skipped()]
[ "def", "passed", "(", "self", ")", ":", "return", "[", "test", "for", "test", "in", "self", ".", "all", "(", ")", "if", "not", "test", ".", "failed", "(", ")", "and", "not", "test", ".", "skipped", "(", ")", "]" ]
Return all the passing testcases :return:
[ "Return", "all", "the", "passing", "testcases", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L232-L237
inorton/junit2html
junit2htmlreport/parser.py
Suite.toc
def toc(self): """ Return a html table of contents :return: """ fails = "" skips = "" if len(self.failed()): faillist = list() for failure in self.failed(): faillist.append( """ <li> ...
python
def toc(self): """ Return a html table of contents :return: """ fails = "" skips = "" if len(self.failed()): faillist = list() for failure in self.failed(): faillist.append( """ <li> ...
[ "def", "toc", "(", "self", ")", ":", "fails", "=", "\"\"", "skips", "=", "\"\"", "if", "len", "(", "self", ".", "failed", "(", ")", ")", ":", "faillist", "=", "list", "(", ")", "for", "failure", "in", "self", ".", "failed", "(", ")", ":", "fail...
Return a html table of contents :return:
[ "Return", "a", "html", "table", "of", "contents", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L239-L321
inorton/junit2html
junit2htmlreport/parser.py
Suite.html
def html(self): """ Render this as html. :return: """ classes = list() package = "" if self.package is not None: package = "Package: " + self.package + "<br/>" for classname in self.classes: classes.append(self.classes[classname]....
python
def html(self): """ Render this as html. :return: """ classes = list() package = "" if self.package is not None: package = "Package: " + self.package + "<br/>" for classname in self.classes: classes.append(self.classes[classname]....
[ "def", "html", "(", "self", ")", ":", "classes", "=", "list", "(", ")", "package", "=", "\"\"", "if", "self", ".", "package", "is", "not", "None", ":", "package", "=", "\"Package: \"", "+", "self", ".", "package", "+", "\"<br/>\"", "for", "classname", ...
Render this as html. :return:
[ "Render", "this", "as", "html", ".", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L323-L396
inorton/junit2html
junit2htmlreport/parser.py
Junit.get_css
def get_css(self): """ Return the content of the css file :return: """ thisdir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(thisdir, self.css), "r") as cssfile: return cssfile.read()
python
def get_css(self): """ Return the content of the css file :return: """ thisdir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(thisdir, self.css), "r") as cssfile: return cssfile.read()
[ "def", "get_css", "(", "self", ")", ":", "thisdir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "thisdir", ",", "self", ".", ...
Return the content of the css file :return:
[ "Return", "the", "content", "of", "the", "css", "file", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L430-L437
inorton/junit2html
junit2htmlreport/parser.py
Junit.process
def process(self): """ populate the report from the xml :return: """ suites = None if isinstance(self.tree, ET.Element): root = self.tree else: root = self.tree.getroot() if root.tag == "testrun": root = root[0] ...
python
def process(self): """ populate the report from the xml :return: """ suites = None if isinstance(self.tree, ET.Element): root = self.tree else: root = self.tree.getroot() if root.tag == "testrun": root = root[0] ...
[ "def", "process", "(", "self", ")", ":", "suites", "=", "None", "if", "isinstance", "(", "self", ".", "tree", ",", "ET", ".", "Element", ")", ":", "root", "=", "self", ".", "tree", "else", ":", "root", "=", "self", ".", "tree", ".", "getroot", "(...
populate the report from the xml :return:
[ "populate", "the", "report", "from", "the", "xml", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L439-L529
inorton/junit2html
junit2htmlreport/parser.py
Junit.toc
def toc(self): """ If this report has multiple suite results, make a table of contents listing each suite :return: """ if len(self.suites) > 1: tochtml = "<ul>" for suite in self.suites: tochtml += '<li><a href="#{anchor}">{name}</a></li>'....
python
def toc(self): """ If this report has multiple suite results, make a table of contents listing each suite :return: """ if len(self.suites) > 1: tochtml = "<ul>" for suite in self.suites: tochtml += '<li><a href="#{anchor}">{name}</a></li>'....
[ "def", "toc", "(", "self", ")", ":", "if", "len", "(", "self", ".", "suites", ")", ">", "1", ":", "tochtml", "=", "\"<ul>\"", "for", "suite", "in", "self", ".", "suites", ":", "tochtml", "+=", "'<li><a href=\"#{anchor}\">{name}</a></li>'", ".", "format", ...
If this report has multiple suite results, make a table of contents listing each suite :return:
[ "If", "this", "report", "has", "multiple", "suite", "results", "make", "a", "table", "of", "contents", "listing", "each", "suite", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L545-L559
inorton/junit2html
junit2htmlreport/parser.py
Junit.html
def html(self): """ Render the test suite as a HTML report with links to errors first. :return: """ page = self.get_html_head() page += "<body><h1>Test Report</h1>" page += self.toc() for suite in self.suites: page += suite.html() page...
python
def html(self): """ Render the test suite as a HTML report with links to errors first. :return: """ page = self.get_html_head() page += "<body><h1>Test Report</h1>" page += self.toc() for suite in self.suites: page += suite.html() page...
[ "def", "html", "(", "self", ")", ":", "page", "=", "self", ".", "get_html_head", "(", ")", "page", "+=", "\"<body><h1>Test Report</h1>\"", "page", "+=", "self", ".", "toc", "(", ")", "for", "suite", "in", "self", ".", "suites", ":", "page", "+=", "suit...
Render the test suite as a HTML report with links to errors first. :return:
[ "Render", "the", "test", "suite", "as", "a", "HTML", "report", "with", "links", "to", "errors", "first", ".", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/parser.py#L561-L574
inorton/junit2html
junit2htmlreport/runner.py
run
def run(args): """ Run this tool :param args: :return: """ (opts, args) = PARSER.parse_args(args) if args else PARSER.parse_args() if not len(args): PARSER.print_usage() sys.exit(1) outfilename = args[0] + ".html" if len(args) > 1: outfilename = args[1] ...
python
def run(args): """ Run this tool :param args: :return: """ (opts, args) = PARSER.parse_args(args) if args else PARSER.parse_args() if not len(args): PARSER.print_usage() sys.exit(1) outfilename = args[0] + ".html" if len(args) > 1: outfilename = args[1] ...
[ "def", "run", "(", "args", ")", ":", "(", "opts", ",", "args", ")", "=", "PARSER", ".", "parse_args", "(", "args", ")", "if", "args", "else", "PARSER", ".", "parse_args", "(", ")", "if", "not", "len", "(", "args", ")", ":", "PARSER", ".", "print_...
Run this tool :param args: :return:
[ "Run", "this", "tool", ":", "param", "args", ":", ":", "return", ":" ]
train
https://github.com/inorton/junit2html/blob/73ff9d84c41b60148e86ce597ef605a0f1976d4b/junit2htmlreport/runner.py#L14-L33
tompollard/tableone
tableone.py
TableOne._generate_remark_str
def _generate_remark_str(self, end_of_line = '\n'): """ Generate a series of remarks that the user should consider when interpreting the summary statistics. """ warnings = {} msg = '{}'.format(end_of_line) # generate warnings for continuous variables if s...
python
def _generate_remark_str(self, end_of_line = '\n'): """ Generate a series of remarks that the user should consider when interpreting the summary statistics. """ warnings = {} msg = '{}'.format(end_of_line) # generate warnings for continuous variables if s...
[ "def", "_generate_remark_str", "(", "self", ",", "end_of_line", "=", "'\\n'", ")", ":", "warnings", "=", "{", "}", "msg", "=", "'{}'", ".", "format", "(", "end_of_line", ")", "# generate warnings for continuous variables", "if", "self", ".", "_continuous", ":", ...
Generate a series of remarks that the user should consider when interpreting the summary statistics.
[ "Generate", "a", "series", "of", "remarks", "that", "the", "user", "should", "consider", "when", "interpreting", "the", "summary", "statistics", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L200-L235
tompollard/tableone
tableone.py
TableOne._detect_categorical_columns
def _detect_categorical_columns(self,data): """ Detect categorical columns if they are not specified. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- likely_cat : list List of va...
python
def _detect_categorical_columns(self,data): """ Detect categorical columns if they are not specified. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- likely_cat : list List of va...
[ "def", "_detect_categorical_columns", "(", "self", ",", "data", ")", ":", "# assume all non-numerical and date columns are categorical", "numeric_cols", "=", "set", "(", "data", ".", "_get_numeric_data", "(", ")", ".", "columns", ".", "values", ")", "date_cols", "=", ...
Detect categorical columns if they are not specified. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- likely_cat : list List of variables that appear to be categorical.
[ "Detect", "categorical", "columns", "if", "they", "are", "not", "specified", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L237-L261
tompollard/tableone
tableone.py
TableOne._std
def _std(self,x): """ Compute standard deviation with ddof degrees of freedom """ return np.nanstd(x.values,ddof=self._ddof)
python
def _std(self,x): """ Compute standard deviation with ddof degrees of freedom """ return np.nanstd(x.values,ddof=self._ddof)
[ "def", "_std", "(", "self", ",", "x", ")", ":", "return", "np", ".", "nanstd", "(", "x", ".", "values", ",", "ddof", "=", "self", ".", "_ddof", ")" ]
Compute standard deviation with ddof degrees of freedom
[ "Compute", "standard", "deviation", "with", "ddof", "degrees", "of", "freedom" ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L275-L279
tompollard/tableone
tableone.py
TableOne._tukey
def _tukey(self,x,threshold): """ Count outliers according to Tukey's rule. Where Q1 is the lower quartile and Q3 is the upper quartile, an outlier is an observation outside of the range: [Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)] k = 1.5 indicates an outlier k = 3.0 i...
python
def _tukey(self,x,threshold): """ Count outliers according to Tukey's rule. Where Q1 is the lower quartile and Q3 is the upper quartile, an outlier is an observation outside of the range: [Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)] k = 1.5 indicates an outlier k = 3.0 i...
[ "def", "_tukey", "(", "self", ",", "x", ",", "threshold", ")", ":", "vals", "=", "x", ".", "values", "[", "~", "np", ".", "isnan", "(", "x", ".", "values", ")", "]", "try", ":", "q1", ",", "q3", "=", "np", ".", "percentile", "(", "vals", ",",...
Count outliers according to Tukey's rule. Where Q1 is the lower quartile and Q3 is the upper quartile, an outlier is an observation outside of the range: [Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)] k = 1.5 indicates an outlier k = 3.0 indicates an outlier that is "far out"
[ "Count", "outliers", "according", "to", "Tukey", "s", "rule", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L311-L332
tompollard/tableone
tableone.py
TableOne._outliers
def _outliers(self,x): """ Compute number of outliers """ outliers = self._tukey(x, threshold = 1.5) return np.size(outliers)
python
def _outliers(self,x): """ Compute number of outliers """ outliers = self._tukey(x, threshold = 1.5) return np.size(outliers)
[ "def", "_outliers", "(", "self", ",", "x", ")", ":", "outliers", "=", "self", ".", "_tukey", "(", "x", ",", "threshold", "=", "1.5", ")", "return", "np", ".", "size", "(", "outliers", ")" ]
Compute number of outliers
[ "Compute", "number", "of", "outliers" ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L334-L339
tompollard/tableone
tableone.py
TableOne._far_outliers
def _far_outliers(self,x): """ Compute number of "far out" outliers """ outliers = self._tukey(x, threshold = 3.0) return np.size(outliers)
python
def _far_outliers(self,x): """ Compute number of "far out" outliers """ outliers = self._tukey(x, threshold = 3.0) return np.size(outliers)
[ "def", "_far_outliers", "(", "self", ",", "x", ")", ":", "outliers", "=", "self", ".", "_tukey", "(", "x", ",", "threshold", "=", "3.0", ")", "return", "np", ".", "size", "(", "outliers", ")" ]
Compute number of "far out" outliers
[ "Compute", "number", "of", "far", "out", "outliers" ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L341-L346
tompollard/tableone
tableone.py
TableOne._t1_summary
def _t1_summary(self,x): """ Compute median [IQR] or mean (Std) for the input series. Parameters ---------- x : pandas Series Series of values to be summarised. """ # set decimal places if isinstance(self._decimals,int): n ...
python
def _t1_summary(self,x): """ Compute median [IQR] or mean (Std) for the input series. Parameters ---------- x : pandas Series Series of values to be summarised. """ # set decimal places if isinstance(self._decimals,int): n ...
[ "def", "_t1_summary", "(", "self", ",", "x", ")", ":", "# set decimal places", "if", "isinstance", "(", "self", ".", "_decimals", ",", "int", ")", ":", "n", "=", "self", ".", "_decimals", "elif", "isinstance", "(", "self", ".", "_decimals", ",", "dict", ...
Compute median [IQR] or mean (Std) for the input series. Parameters ---------- x : pandas Series Series of values to be summarised.
[ "Compute", "median", "[", "IQR", "]", "or", "mean", "(", "Std", ")", "for", "the", "input", "series", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L348-L376
tompollard/tableone
tableone.py
TableOne._create_cont_describe
def _create_cont_describe(self,data): """ Describe the continuous data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cont : pandas DataFrame Summarise the continuous variab...
python
def _create_cont_describe(self,data): """ Describe the continuous data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cont : pandas DataFrame Summarise the continuous variab...
[ "def", "_create_cont_describe", "(", "self", ",", "data", ")", ":", "aggfuncs", "=", "[", "pd", ".", "Series", ".", "count", ",", "np", ".", "mean", ",", "np", ".", "median", ",", "self", ".", "_std", ",", "self", ".", "_q25", ",", "self", ".", "...
Describe the continuous data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cont : pandas DataFrame Summarise the continuous variables.
[ "Describe", "the", "continuous", "data", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L378-L432
tompollard/tableone
tableone.py
TableOne._create_cat_describe
def _create_cat_describe(self,data): """ Describe the categorical data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cat : pandas DataFrame Summarise the categorical variab...
python
def _create_cat_describe(self,data): """ Describe the categorical data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cat : pandas DataFrame Summarise the categorical variab...
[ "def", "_create_cat_describe", "(", "self", ",", "data", ")", ":", "group_dict", "=", "{", "}", "for", "g", "in", "self", ".", "_groupbylvls", ":", "if", "self", ".", "_groupby", ":", "d_slice", "=", "data", ".", "loc", "[", "data", "[", "self", ".",...
Describe the categorical data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cat : pandas DataFrame Summarise the categorical variables.
[ "Describe", "the", "categorical", "data", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L443-L516
tompollard/tableone
tableone.py
TableOne._create_significance_table
def _create_significance_table(self,data): """ Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. Re...
python
def _create_significance_table(self,data): """ Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. Re...
[ "def", "_create_significance_table", "(", "self", ",", "data", ")", ":", "# list features of the variable e.g. matched, paired, n_expected", "df", "=", "pd", ".", "DataFrame", "(", "index", "=", "self", ".", "_continuous", "+", "self", ".", "_categorical", ",", "col...
Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df : pandas DataFrame ...
[ "Create", "a", "table", "containing", "p", "-", "values", "for", "significance", "tests", ".", "Add", "features", "of", "the", "distributions", "and", "the", "p", "-", "values", "to", "the", "dataframe", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L518-L572
tompollard/tableone
tableone.py
TableOne._create_cont_table
def _create_cont_table(self,data): """ Create tableone for continuous data. Returns ---------- table : pandas DataFrame A table summarising the continuous variables. """ # remove the t1_summary level table = self.cont_describe[['t1_summary']]....
python
def _create_cont_table(self,data): """ Create tableone for continuous data. Returns ---------- table : pandas DataFrame A table summarising the continuous variables. """ # remove the t1_summary level table = self.cont_describe[['t1_summary']]....
[ "def", "_create_cont_table", "(", "self", ",", "data", ")", ":", "# remove the t1_summary level", "table", "=", "self", ".", "cont_describe", "[", "[", "'t1_summary'", "]", "]", ".", "copy", "(", ")", "table", ".", "columns", "=", "table", ".", "columns", ...
Create tableone for continuous data. Returns ---------- table : pandas DataFrame A table summarising the continuous variables.
[ "Create", "tableone", "for", "continuous", "data", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L642-L673
tompollard/tableone
tableone.py
TableOne._create_cat_table
def _create_cat_table(self,data): """ Create table one for categorical data. Returns ---------- table : pandas DataFrame A table summarising the categorical variables. """ table = self.cat_describe['t1_summary'].copy() # add the total count of...
python
def _create_cat_table(self,data): """ Create table one for categorical data. Returns ---------- table : pandas DataFrame A table summarising the categorical variables. """ table = self.cat_describe['t1_summary'].copy() # add the total count of...
[ "def", "_create_cat_table", "(", "self", ",", "data", ")", ":", "table", "=", "self", ".", "cat_describe", "[", "'t1_summary'", "]", ".", "copy", "(", ")", "# add the total count of null values across all levels", "isnull", "=", "data", "[", "self", ".", "_categ...
Create table one for categorical data. Returns ---------- table : pandas DataFrame A table summarising the categorical variables.
[ "Create", "table", "one", "for", "categorical", "data", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L675-L700
tompollard/tableone
tableone.py
TableOne._create_tableone
def _create_tableone(self,data): """ Create table 1 by combining the continuous and categorical tables. Returns ---------- table : pandas DataFrame The complete table one. """ if self._continuous and self._categorical: # support pandas<=0...
python
def _create_tableone(self,data): """ Create table 1 by combining the continuous and categorical tables. Returns ---------- table : pandas DataFrame The complete table one. """ if self._continuous and self._categorical: # support pandas<=0...
[ "def", "_create_tableone", "(", "self", ",", "data", ")", ":", "if", "self", ".", "_continuous", "and", "self", ".", "_categorical", ":", "# support pandas<=0.22", "try", ":", "table", "=", "pd", ".", "concat", "(", "[", "self", ".", "cont_table", ",", "...
Create table 1 by combining the continuous and categorical tables. Returns ---------- table : pandas DataFrame The complete table one.
[ "Create", "table", "1", "by", "combining", "the", "continuous", "and", "categorical", "tables", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L702-L834
tompollard/tableone
tableone.py
TableOne._create_row_labels
def _create_row_labels(self): """ Take the original labels for rows. Rename if alternative labels are provided. Append label suffix if label_suffix is True. Returns ---------- labels : dictionary Dictionary, keys are original column name, values are final la...
python
def _create_row_labels(self): """ Take the original labels for rows. Rename if alternative labels are provided. Append label suffix if label_suffix is True. Returns ---------- labels : dictionary Dictionary, keys are original column name, values are final la...
[ "def", "_create_row_labels", "(", "self", ")", ":", "# start with the original column names", "labels", "=", "{", "}", "for", "c", "in", "self", ".", "_columns", ":", "labels", "[", "c", "]", "=", "c", "# replace column names with alternative names if provided", "if...
Take the original labels for rows. Rename if alternative labels are provided. Append label suffix if label_suffix is True. Returns ---------- labels : dictionary Dictionary, keys are original column name, values are final label.
[ "Take", "the", "original", "labels", "for", "rows", ".", "Rename", "if", "alternative", "labels", "are", "provided", ".", "Append", "label", "suffix", "if", "label_suffix", "is", "True", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L836-L867
tompollard/tableone
modality.py
dip_pval_tabinterpol
def dip_pval_tabinterpol(dip, N): ''' dip - dip value computed from dip_from_cdf N - number of observations ''' # if qDiptab_df is None: # raise DataError("Tabulated p-values not available. See installation instructions.") if np.isnan(N) or N < 10: return ...
python
def dip_pval_tabinterpol(dip, N): ''' dip - dip value computed from dip_from_cdf N - number of observations ''' # if qDiptab_df is None: # raise DataError("Tabulated p-values not available. See installation instructions.") if np.isnan(N) or N < 10: return ...
[ "def", "dip_pval_tabinterpol", "(", "dip", ",", "N", ")", ":", "# if qDiptab_df is None:", "# raise DataError(\"Tabulated p-values not available. See installation instructions.\")", "if", "np", ".", "isnan", "(", "N", ")", "or", "N", "<", "10", ":", "return", "np", ...
dip - dip value computed from dip_from_cdf N - number of observations
[ "dip", "-", "dip", "value", "computed", "from", "dip_from_cdf", "N", "-", "number", "of", "observations" ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/modality.py#L127-L713
tompollard/tableone
modality.py
dip_and_closest_unimodal_from_cdf
def dip_and_closest_unimodal_from_cdf(xF, yF, plotting=False, verbose=False, eps=1e-12): ''' Dip computed as distance between empirical distribution function (EDF) and cumulative distribution function for the unimodal distribution with smallest such distance. The optimal unimodal distributio...
python
def dip_and_closest_unimodal_from_cdf(xF, yF, plotting=False, verbose=False, eps=1e-12): ''' Dip computed as distance between empirical distribution function (EDF) and cumulative distribution function for the unimodal distribution with smallest such distance. The optimal unimodal distributio...
[ "def", "dip_and_closest_unimodal_from_cdf", "(", "xF", ",", "yF", ",", "plotting", "=", "False", ",", "verbose", "=", "False", ",", "eps", "=", "1e-12", ")", ":", "## TODO! Preprocess xF and yF so that yF increasing and xF does", "## not have more than two copies of each x-...
Dip computed as distance between empirical distribution function (EDF) and cumulative distribution function for the unimodal distribution with smallest such distance. The optimal unimodal distribution is found by the algorithm presented in Hartigan (1985): Computation of the dip sta...
[ "Dip", "computed", "as", "distance", "between", "empirical", "distribution", "function", "(", "EDF", ")", "and", "cumulative", "distribution", "function", "for", "the", "unimodal", "distribution", "with", "smallest", "such", "distance", ".", "The", "optimal", "uni...
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/modality.py#L719-L942
tompollard/tableone
modality.py
bandwidth_factor
def bandwidth_factor(nbr_data_pts, deriv_order=0): ''' Scale factor for one-dimensional plug-in bandwidth selection. ''' if deriv_order == 0: return (3.0*nbr_data_pts/4)**(-1.0/5) if deriv_order == 2: return (7.0*nbr_data_pts/4)**(-1.0/9) raise ValueError('Not implemented f...
python
def bandwidth_factor(nbr_data_pts, deriv_order=0): ''' Scale factor for one-dimensional plug-in bandwidth selection. ''' if deriv_order == 0: return (3.0*nbr_data_pts/4)**(-1.0/5) if deriv_order == 2: return (7.0*nbr_data_pts/4)**(-1.0/9) raise ValueError('Not implemented f...
[ "def", "bandwidth_factor", "(", "nbr_data_pts", ",", "deriv_order", "=", "0", ")", ":", "if", "deriv_order", "==", "0", ":", "return", "(", "3.0", "*", "nbr_data_pts", "/", "4", ")", "**", "(", "-", "1.0", "/", "5", ")", "if", "deriv_order", "==", "2...
Scale factor for one-dimensional plug-in bandwidth selection.
[ "Scale", "factor", "for", "one", "-", "dimensional", "plug", "-", "in", "bandwidth", "selection", "." ]
train
https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/modality.py#L1011-L1021
Pylons/paginate
paginate/__init__.py
make_html_tag
def make_html_tag(tag, text=None, **params): """Create an HTML tag string. tag The HTML tag to use (e.g. 'a', 'span' or 'div') text The text to enclose between opening and closing tag. If no text is specified then only the opening tag is returned. Example:: make_html_t...
python
def make_html_tag(tag, text=None, **params): """Create an HTML tag string. tag The HTML tag to use (e.g. 'a', 'span' or 'div') text The text to enclose between opening and closing tag. If no text is specified then only the opening tag is returned. Example:: make_html_t...
[ "def", "make_html_tag", "(", "tag", ",", "text", "=", "None", ",", "*", "*", "params", ")", ":", "params_string", "=", "\"\"", "# Parameters are passed. Turn the dict into a string like \"a=1 b=2 c=3\" string.", "for", "key", ",", "value", "in", "sorted", "(", "para...
Create an HTML tag string. tag The HTML tag to use (e.g. 'a', 'span' or 'div') text The text to enclose between opening and closing tag. If no text is specified then only the opening tag is returned. Example:: make_html_tag('a', text="Hello", href="/another/page") ...
[ "Create", "an", "HTML", "tag", "string", "." ]
train
https://github.com/Pylons/paginate/blob/07e6f62c00a731839ca2da32e6d6a37b31a13d4f/paginate/__init__.py#L828-L863
Pylons/paginate
paginate/__init__.py
Page.pager
def pager( self, format="~2~", url=None, show_if_single_page=False, separator=" ", symbol_first="&lt;&lt;", symbol_last="&gt;&gt;", symbol_previous="&lt;", symbol_next="&gt;", link_attr=None, curpage_attr=None, dotdot_attr=N...
python
def pager( self, format="~2~", url=None, show_if_single_page=False, separator=" ", symbol_first="&lt;&lt;", symbol_last="&gt;&gt;", symbol_previous="&lt;", symbol_next="&gt;", link_attr=None, curpage_attr=None, dotdot_attr=N...
[ "def", "pager", "(", "self", ",", "format", "=", "\"~2~\"", ",", "url", "=", "None", ",", "show_if_single_page", "=", "False", ",", "separator", "=", "\" \"", ",", "symbol_first", "=", "\"&lt;&lt;\"", ",", "symbol_last", "=", "\"&gt;&gt;\"", ",", "symbol_pre...
Return string with links to other pages (e.g. '1 .. 5 6 7 [8] 9 10 11 .. 50'). format: Format string that defines how the pager is rendered. The string can contain the following $-tokens that are substituted by the string.Template module: - $first_page: number o...
[ "Return", "string", "with", "links", "to", "other", "pages", "(", "e", ".", "g", ".", "1", "..", "5", "6", "7", "[", "8", "]", "9", "10", "11", "..", "50", ")", "." ]
train
https://github.com/Pylons/paginate/blob/07e6f62c00a731839ca2da32e6d6a37b31a13d4f/paginate/__init__.py#L336-L513
Pylons/paginate
paginate/__init__.py
Page.link_map
def link_map( self, format="~2~", url=None, show_if_single_page=False, separator=" ", symbol_first="&lt;&lt;", symbol_last="&gt;&gt;", symbol_previous="&lt;", symbol_next="&gt;", link_attr=None, curpage_attr=None, dotdot_att...
python
def link_map( self, format="~2~", url=None, show_if_single_page=False, separator=" ", symbol_first="&lt;&lt;", symbol_last="&gt;&gt;", symbol_previous="&lt;", symbol_next="&gt;", link_attr=None, curpage_attr=None, dotdot_att...
[ "def", "link_map", "(", "self", ",", "format", "=", "\"~2~\"", ",", "url", "=", "None", ",", "show_if_single_page", "=", "False", ",", "separator", "=", "\" \"", ",", "symbol_first", "=", "\"&lt;&lt;\"", ",", "symbol_last", "=", "\"&gt;&gt;\"", ",", "symbol_...
Return map with links to other pages if default pager() function is not suitable solution. format: Format string that defines how the pager would be normally rendered rendered. Uses same arguments as pager() method, but returns a simple dictionary in form of: {'current_page':...
[ "Return", "map", "with", "links", "to", "other", "pages", "if", "default", "pager", "()", "function", "is", "not", "suitable", "solution", ".", "format", ":", "Format", "string", "that", "defines", "how", "the", "pager", "would", "be", "normally", "rendered"...
train
https://github.com/Pylons/paginate/blob/07e6f62c00a731839ca2da32e6d6a37b31a13d4f/paginate/__init__.py#L515-L771
Pylons/paginate
paginate/__init__.py
Page._range
def _range(self, link_map, radius): """ Return range of linked pages to substiture placeholder in pattern """ leftmost_page = max(self.first_page, (self.page - radius)) rightmost_page = min(self.last_page, (self.page + radius)) nav_items = [] # Create a link to ...
python
def _range(self, link_map, radius): """ Return range of linked pages to substiture placeholder in pattern """ leftmost_page = max(self.first_page, (self.page - radius)) rightmost_page = min(self.last_page, (self.page + radius)) nav_items = [] # Create a link to ...
[ "def", "_range", "(", "self", ",", "link_map", ",", "radius", ")", ":", "leftmost_page", "=", "max", "(", "self", ".", "first_page", ",", "(", "self", ".", "page", "-", "radius", ")", ")", "rightmost_page", "=", "min", "(", "self", ".", "last_page", ...
Return range of linked pages to substiture placeholder in pattern
[ "Return", "range", "of", "linked", "pages", "to", "substiture", "placeholder", "in", "pattern" ]
train
https://github.com/Pylons/paginate/blob/07e6f62c00a731839ca2da32e6d6a37b31a13d4f/paginate/__init__.py#L773-L799
Pylons/paginate
paginate/__init__.py
Page.default_link_tag
def default_link_tag(item): """ Create an A-HREF tag that points to another page. """ text = item["value"] target_url = item["href"] if not item["href"] or item["type"] in ("span", "current_page"): if item["attrs"]: text = make_html_tag("span"...
python
def default_link_tag(item): """ Create an A-HREF tag that points to another page. """ text = item["value"] target_url = item["href"] if not item["href"] or item["type"] in ("span", "current_page"): if item["attrs"]: text = make_html_tag("span"...
[ "def", "default_link_tag", "(", "item", ")", ":", "text", "=", "item", "[", "\"value\"", "]", "target_url", "=", "item", "[", "\"href\"", "]", "if", "not", "item", "[", "\"href\"", "]", "or", "item", "[", "\"type\"", "]", "in", "(", "\"span\"", ",", ...
Create an A-HREF tag that points to another page.
[ "Create", "an", "A", "-", "HREF", "tag", "that", "points", "to", "another", "page", "." ]
train
https://github.com/Pylons/paginate/blob/07e6f62c00a731839ca2da32e6d6a37b31a13d4f/paginate/__init__.py#L813-L825
sloria/textblob-aptagger
textblob_aptagger/taggers.py
PerceptronTagger.tag
def tag(self, corpus, tokenize=True): '''Tags a string `corpus`.''' # Assume untokenized corpus has \n between sentences and ' ' between words s_split = SentenceTokenizer().tokenize if tokenize else lambda t: t.split('\n') w_split = WordTokenizer().tokenize if tokenize else lambda s: s.s...
python
def tag(self, corpus, tokenize=True): '''Tags a string `corpus`.''' # Assume untokenized corpus has \n between sentences and ' ' between words s_split = SentenceTokenizer().tokenize if tokenize else lambda t: t.split('\n') w_split = WordTokenizer().tokenize if tokenize else lambda s: s.s...
[ "def", "tag", "(", "self", ",", "corpus", ",", "tokenize", "=", "True", ")", ":", "# Assume untokenized corpus has \\n between sentences and ' ' between words", "s_split", "=", "SentenceTokenizer", "(", ")", ".", "tokenize", "if", "tokenize", "else", "lambda", "t", ...
Tags a string `corpus`.
[ "Tags", "a", "string", "corpus", "." ]
train
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/taggers.py#L38-L59
sloria/textblob-aptagger
textblob_aptagger/taggers.py
PerceptronTagger.train
def train(self, sentences, save_loc=None, nr_iter=5): '''Train a model from sentences, and save it at ``save_loc``. ``nr_iter`` controls the number of Perceptron training iterations. :param sentences: A list of (words, tags) tuples. :param save_loc: If not ``None``, saves a pickled mode...
python
def train(self, sentences, save_loc=None, nr_iter=5): '''Train a model from sentences, and save it at ``save_loc``. ``nr_iter`` controls the number of Perceptron training iterations. :param sentences: A list of (words, tags) tuples. :param save_loc: If not ``None``, saves a pickled mode...
[ "def", "train", "(", "self", ",", "sentences", ",", "save_loc", "=", "None", ",", "nr_iter", "=", "5", ")", ":", "self", ".", "_make_tagdict", "(", "sentences", ")", "self", ".", "model", ".", "classes", "=", "self", ".", "classes", "for", "iter_", "...
Train a model from sentences, and save it at ``save_loc``. ``nr_iter`` controls the number of Perceptron training iterations. :param sentences: A list of (words, tags) tuples. :param save_loc: If not ``None``, saves a pickled model in this location. :param nr_iter: Number of training it...
[ "Train", "a", "model", "from", "sentences", "and", "save", "it", "at", "save_loc", ".", "nr_iter", "controls", "the", "number", "of", "Perceptron", "training", "iterations", "." ]
train
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/taggers.py#L61-L95
sloria/textblob-aptagger
textblob_aptagger/taggers.py
PerceptronTagger.load
def load(self, loc): '''Load a pickled model.''' try: w_td_c = pickle.load(open(loc, 'rb')) except IOError: msg = ("Missing trontagger.pickle file.") raise MissingCorpusError(msg) self.model.weights, self.tagdict, self.classes = w_td_c self.mod...
python
def load(self, loc): '''Load a pickled model.''' try: w_td_c = pickle.load(open(loc, 'rb')) except IOError: msg = ("Missing trontagger.pickle file.") raise MissingCorpusError(msg) self.model.weights, self.tagdict, self.classes = w_td_c self.mod...
[ "def", "load", "(", "self", ",", "loc", ")", ":", "try", ":", "w_td_c", "=", "pickle", ".", "load", "(", "open", "(", "loc", ",", "'rb'", ")", ")", "except", "IOError", ":", "msg", "=", "(", "\"Missing trontagger.pickle file.\"", ")", "raise", "Missing...
Load a pickled model.
[ "Load", "a", "pickled", "model", "." ]
train
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/taggers.py#L97-L106
sloria/textblob-aptagger
textblob_aptagger/taggers.py
PerceptronTagger._normalize
def _normalize(self, word): '''Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str ''' if '-' in word and word[0] != '-': re...
python
def _normalize(self, word): '''Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str ''' if '-' in word and word[0] != '-': re...
[ "def", "_normalize", "(", "self", ",", "word", ")", ":", "if", "'-'", "in", "word", "and", "word", "[", "0", "]", "!=", "'-'", ":", "return", "'!HYPHEN'", "elif", "word", ".", "isdigit", "(", ")", "and", "len", "(", "word", ")", "==", "4", ":", ...
Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str
[ "Normalization", "used", "in", "pre", "-", "processing", "." ]
train
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/taggers.py#L108-L124
sloria/textblob-aptagger
textblob_aptagger/taggers.py
PerceptronTagger._get_features
def _get_features(self, i, word, context, prev, prev2): '''Map tokens into a feature representation, implemented as a {hashable: float} dict. If the features change, a new model must be trained. ''' def add(name, *args): features[' '.join((name,) + tuple(args))] += 1 ...
python
def _get_features(self, i, word, context, prev, prev2): '''Map tokens into a feature representation, implemented as a {hashable: float} dict. If the features change, a new model must be trained. ''' def add(name, *args): features[' '.join((name,) + tuple(args))] += 1 ...
[ "def", "_get_features", "(", "self", ",", "i", ",", "word", ",", "context", ",", "prev", ",", "prev2", ")", ":", "def", "add", "(", "name", ",", "*", "args", ")", ":", "features", "[", "' '", ".", "join", "(", "(", "name", ",", ")", "+", "tuple...
Map tokens into a feature representation, implemented as a {hashable: float} dict. If the features change, a new model must be trained.
[ "Map", "tokens", "into", "a", "feature", "representation", "implemented", "as", "a", "{", "hashable", ":", "float", "}", "dict", ".", "If", "the", "features", "change", "a", "new", "model", "must", "be", "trained", "." ]
train
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/taggers.py#L126-L151
sloria/textblob-aptagger
textblob_aptagger/taggers.py
PerceptronTagger._make_tagdict
def _make_tagdict(self, sentences): '''Make a tag dictionary for single-tag words.''' counts = defaultdict(lambda: defaultdict(int)) for words, tags in sentences: for word, tag in zip(words, tags): counts[word][tag] += 1 self.classes.add(tag) f...
python
def _make_tagdict(self, sentences): '''Make a tag dictionary for single-tag words.''' counts = defaultdict(lambda: defaultdict(int)) for words, tags in sentences: for word, tag in zip(words, tags): counts[word][tag] += 1 self.classes.add(tag) f...
[ "def", "_make_tagdict", "(", "self", ",", "sentences", ")", ":", "counts", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "int", ")", ")", "for", "words", ",", "tags", "in", "sentences", ":", "for", "word", ",", "tag", "in", "zip", "(", ...
Make a tag dictionary for single-tag words.
[ "Make", "a", "tag", "dictionary", "for", "single", "-", "tag", "words", "." ]
train
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/taggers.py#L153-L168
sloria/textblob-aptagger
textblob_aptagger/_perceptron.py
train
def train(nr_iter, examples): '''Return an averaged perceptron model trained on ``examples`` for ``nr_iter`` iterations. ''' model = AveragedPerceptron() for i in range(nr_iter): random.shuffle(examples) for features, class_ in examples: scores = model.predict(features) ...
python
def train(nr_iter, examples): '''Return an averaged perceptron model trained on ``examples`` for ``nr_iter`` iterations. ''' model = AveragedPerceptron() for i in range(nr_iter): random.shuffle(examples) for features, class_ in examples: scores = model.predict(features) ...
[ "def", "train", "(", "nr_iter", ",", "examples", ")", ":", "model", "=", "AveragedPerceptron", "(", ")", "for", "i", "in", "range", "(", "nr_iter", ")", ":", "random", ".", "shuffle", "(", "examples", ")", "for", "features", ",", "class_", "in", "examp...
Return an averaged perceptron model trained on ``examples`` for ``nr_iter`` iterations.
[ "Return", "an", "averaged", "perceptron", "model", "trained", "on", "examples", "for", "nr_iter", "iterations", "." ]
train
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/_perceptron.py#L85-L98
statueofmike/rtsp
scripts/rtp.py
RtpPacket.encode
def encode(self, V, P, X, CC, seqNum, M, PT, SSRC, payload): """Encode the RTP packet with header fields and payload.""" timestamp = int(time()) header = bytearray(HEADER_SIZE) # Fill the header bytearray with RTP header fields # ... header[0] = header[0] | V << 6; ...
python
def encode(self, V, P, X, CC, seqNum, M, PT, SSRC, payload): """Encode the RTP packet with header fields and payload.""" timestamp = int(time()) header = bytearray(HEADER_SIZE) # Fill the header bytearray with RTP header fields # ... header[0] = header[0] | V << 6; ...
[ "def", "encode", "(", "self", ",", "V", ",", "P", ",", "X", ",", "CC", ",", "seqNum", ",", "M", ",", "PT", ",", "SSRC", ",", "payload", ")", ":", "timestamp", "=", "int", "(", "time", "(", ")", ")", "header", "=", "bytearray", "(", "HEADER_SIZE...
Encode the RTP packet with header fields and payload.
[ "Encode", "the", "RTP", "packet", "with", "header", "fields", "and", "payload", "." ]
train
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/rtp.py#L11-L38