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_documentation_string
stringlengths
1
47.2k
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...
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.
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]...
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.
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...
Check to see if user if authenticated for image requests. Must have access cookie with an appropriate value.
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...
Handler for logout button. Delete cookies and return HTML that immediately closes window
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 ...
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 ...
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...
Response to set account cookie and close window HTML/JavaScript.
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...
Set instance variables for directory and binary locations. FIXME - should accept params to set things other than defaults.
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...
Create PNM file from input image file.
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: ...
Apply region selection.
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...
Apply size scaling.
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...
Apply rotation and/or mirroring.
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...
Apply value of quality parameter.
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...
Apply format selection.
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...
Use python-magic to determine file type. Returns 'png' or 'jpg' on success, nothing on failure.
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....
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
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))
Shell call with necessary setup first.
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)
Clean up any temporary files.
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 ...
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 ...
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...
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>
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...
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.
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, ...
OAuth starts here, redirect user to Google.
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 ...
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.
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...
Make request to Google API to get token.
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...
Make request to Google API to get profile data for the user.
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. ...
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.
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...
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...
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/.")
Null implementation of region selection.
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, ...
Null implementation of rotate and/or mirror.
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:...
Null implementation of quality.
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...
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.
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...
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...
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...
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...
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...
Check and interpret rotation. Returns a truth value as to whether to mirror, and a floating point number 0 <= angle < 360 (degrees).
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...
Value of quality parameter to use in processing request. Simple substitution of 'native' or 'default' if no quality parameter is specified.
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). ...
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 ...
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) ...
Return color for a pixel.
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 (...
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.
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)
Iteration in Mandlebrot coordinate z.
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 - ...
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.
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...
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...
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 ...
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...
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): ...
Parse extra request parameters to IIIFRequest object.
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...
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.
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...
Generate static files for one source image.
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...
Generate one tile for this given region, size of this image.
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 ...
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...
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...
Setup output directory based on self.dst and self.identifier. Returns the output directory name on success, raises and exception on failure.
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 ...
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_...
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)
Helper for pulling a keyed value off various types of objects
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
Preserve unknown keys during deserialization.
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
Preserve unknown keys during deserialization.
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...
Validates headers data and creates the config objects
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...
Validates the data and creates the config objects
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)
Validate distributed experiment
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) ...
Returns an experiment spec for this group spec and the given matrix declaration.
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])
Returns a build spec for this group spec.
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...
Validates matrix data and creates the config objects
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
Generate a html anchor name :return:
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...
Render this test class as html :return:
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))
Render those properties as html :return:
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="...
Render this test case as HTML :return:
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
Return all testcases :return:
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()]
Return all the passing testcases :return:
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> ...
Return a html table of contents :return:
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]....
Render this as html. :return:
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()
Return the content of the css file :return:
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] ...
populate the report from the xml :return:
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>'....
If this report has multiple suite results, make a table of contents listing each suite :return:
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...
Render the test suite as a HTML report with links to errors first. :return:
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] ...
Run this tool :param args: :return:
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...
Generate a series of remarks that the user should consider when interpreting the summary statistics.
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...
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.
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)
Compute standard deviation with ddof degrees of freedom
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...
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"
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)
Compute number of outliers
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)
Compute number of "far out" outliers
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 ...
Compute median [IQR] or mean (Std) for the input series. Parameters ---------- x : pandas Series Series of values to be summarised.
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...
Describe the continuous data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cont : pandas DataFrame Summarise the continuous variables.
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...
Describe the categorical data. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df_cat : pandas DataFrame Summarise the categorical variables.
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...
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 ...
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']]....
Create tableone for continuous data. Returns ---------- table : pandas DataFrame A table summarising the continuous variables.
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...
Create table one for categorical data. Returns ---------- table : pandas DataFrame A table summarising the categorical variables.
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...
Create table 1 by combining the continuous and categorical tables. Returns ---------- table : pandas DataFrame The complete table one.
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...
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.
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 ...
dip - dip value computed from dip_from_cdf N - number of observations
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...
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...
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...
Scale factor for one-dimensional plug-in bandwidth selection.
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...
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") ...
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...
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...
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...
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':...
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 ...
Return range of linked pages to substiture placeholder in pattern
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"...
Create an A-HREF tag that points to another page.
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...
Tags a string `corpus`.
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...
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...
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...
Load a pickled model.
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...
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
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 ...
Map tokens into a feature representation, implemented as a {hashable: float} dict. If the features change, a new model must be trained.
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...
Make a tag dictionary for single-tag words.
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) ...
Return an averaged perceptron model trained on ``examples`` for ``nr_iter`` iterations.
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; ...
Encode the RTP packet with header fields and payload.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/rtp.py#L11-L38