id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
142,748
Kitware/tangelo
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kitware_tangelo/tangelo/tangelo/pkgdata/plugin/vtkweb/web/vtkweb.py
vtkweb.VTKWebSocketAB.Protocol
class Protocol(wamp.WampClientProtocol): def onOpen(self): self.factory.register(self) def onMessage(self, msg, is_binary): relay.send(msg)
class Protocol(wamp.WampClientProtocol): def onOpen(self): pass def onMessage(self, msg, is_binary): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
2
6
1
5
3
2
0
5
3
2
1
1
0
2
142,749
Kitware/tangelo
tangelo/tangelo/__init__.py
tangelo._Redirect
class _Redirect(object): def __init__(self, path, status): self.path = path self.status = status
class _Redirect(object): def __init__(self, path, status): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
1
4
0
4
4
2
0
4
4
2
1
1
0
1
142,750
Kitware/tangelo
tangelo/tangelo/server.py
tangelo.server.AuthUpdate
class AuthUpdate(object): # A list of acceptable authentication types. allowed_auth_types = ["digest"] def __init__(self, app=None): self.app = app self.security = {} @staticmethod def parse_htaccess(filename): result = {"msg": None, "auth_type": None, "user_file": None, "realm": None, "userpass": None} # Try to open and parse the file. try: with open(filename) as f: lines = filter(lambda x: len(x) > 0, map(lambda x: x.strip().split(), f.readlines())) keys = map(lambda x: x[0], lines) values = map(lambda x: " ".join(x[1:]), lines) for i, (k, v) in enumerate(zip(keys, values)): if k == "AuthType": if v not in AuthUpdate.allowed_auth_types: allowed = ", ".join(AuthUpdate.allowed_auth_types) result["msg"] = ( "%s is not a supported " + "authentication type. The " + "supported types are: %s") % (v, allowed) return result else: result["auth_type"] = v elif k in ["AuthPasswordFile", "AuthUserFile"]: result["user_file"] = v elif k == "AuthRealm": result["realm"] = v else: result["msg"] = ( "Unknown key '%s' on " + "line %d of file '%s'") % (k, i + 1, filename) return result except IOError: result["msg"] = "Could not open file '%s'" % (filename) return result # Open the user file and parse out the username/passwords of those # users in the correct realm. recs = None if result["user_file"] is not None: try: with open(result["user_file"]) as f: recs = filter(lambda x: x[1] == result["realm"], map(lambda x: x.strip().split(":"), f.readlines())) except IOError: result["msg"] = ("Could not open user " + "password file '%s'") % (result["user_file"]) return result except IndexError: result["msg"] = ("Malformed content in user password file " + "'%s' (some line has too " + "few fields)") % (result["user_file"]) return result try: result["userpass"] = {x[0]: x[2] for x in recs} except IndexError: result["msg"] = ("Malformed content in user password file " + "'%s' (some line has too " + "few fields)") % (result["user_file"]) return result return result def htaccess(self, htfile, reqpath): changed = False if htfile is None: if reqpath in self.security: del self.security[reqpath] cfg = self.app.config[reqpath] for a in AuthUpdate.allowed_auth_types: key = "tools.auth_%s.on" % (a) if key in cfg: cfg[key] = False self.app.merge({reqpath: cfg}) changed = True else: # Get the mtime of the htfile. ht_mtime = os.stat(htfile).st_mtime if (reqpath not in self.security or ht_mtime > self.security[reqpath]): # We have either a new .htaccess file, or one that has # been modified list the last request to this path. htspec = AuthUpdate.parse_htaccess(htfile) if htspec["msg"] is not None: tangelo.log_error("TANGELO", "[AuthUpdate] Could not register %s: %s" % (reqpath, htspec["msg"])) return changed, htspec["msg"] # Create an auth config tool using the values in the htspec. toolname = "tools.auth_%s." % (htspec["auth_type"]) passdict = ( lambda realm, username: htspec["userpass"].get(username)) # TODO(choudhury): replace "deadbeef" with a nonce created # randomly in the __init__() method. auth_conf = {toolname + "on": True, toolname + "realm": htspec["realm"], toolname + "get_ha1": passdict, toolname + "key": "deadbeef"} self.app.merge({reqpath: auth_conf}) # Store the mtime in the security table. self.security[reqpath] = ht_mtime changed = True return changed, None def update(self, reqpathcomp, pathcomp): # The lengths of the lists should be equal. assert len(reqpathcomp) == len(pathcomp) # Create a list of paths to search, starting with the requested # resource and moving towards the root. paths = reversed(map(lambda i: ("/".join(reqpathcomp[:(i + 1)]) or "/", os.path.sep.join(pathcomp[:(i + 1)])), range(len(reqpathcomp)))) # Check each path that represents a directory for a .htaccess file, # then decide what to do based on the current auth state for that path. for rpath, dpath in paths: if os.path.isdir(dpath): htfile = dpath + os.path.sep + ".htaccess" if not os.path.exists(htfile): htfile = None changed, msg = self.htaccess(htfile, rpath) if msg is not None: raise cherrypy.HTTPError(401, "There was an error in the " + "HTTP authentication " + "process: %s" % (msg)) # TODO(choudhury): I really don't understand why this hack is # necessary. Basically, when the auth_* tool is installed on # the path in the htaccess() method, it doesn't seem to take # hold until the next time the page is loaded. So this hack # forces a page reload, but it would be better to simply make # the new config "take hold" instead. if changed: raise cherrypy.HTTPRedirect(cherrypy.request.path_info) # Don't bother updating the security table for higher paths - # we'll process those later, when they are requested. break
class AuthUpdate(object): def __init__(self, app=None): pass @staticmethod def parse_htaccess(filename): pass def htaccess(self, htfile, reqpath): pass def update(self, reqpathcomp, pathcomp): pass
6
0
38
4
28
6
6
0.21
1
7
0
0
3
2
4
4
160
21
115
30
109
24
82
28
77
11
1
5
25
142,751
Kitware/tangelo
tangelo/tangelo/server.py
tangelo.server.Content
class Content(object): NotFound = 1 Directory = 2 File = 3 Service = 4 def __init__(self, t, path=None, pargs=None): self.type = t self.path = path self.pargs = pargs
class Content(object): def __init__(self, t, path=None, pargs=None): pass
2
0
4
0
4
0
1
0
1
0
0
0
1
3
1
1
10
1
9
9
7
0
9
9
7
1
1
0
1
142,752
Kitware/tangelo
tangelo/tangelo/server.py
tangelo.server.Directive
class Directive(object): HTTPRedirect = 1 InternalRedirect = 2 ListPlugins = 3 def __init__(self, t, argument=None): self.type = t self.argument = argument
class Directive(object): def __init__(self, t, argument=None): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
1
8
1
7
7
5
0
7
7
5
1
1
0
1
142,753
Kitware/tangelo
tangelo/tangelo/server.py
tangelo.server.Plugins
class Plugins(object): class Plugin(object): def __init__(self, path): self.path = path self.control = None self.module = None self.apps = [] def __init__(self, base_package, config, plugin_dir): self.base_package = base_package self.plugin_dir = plugin_dir self.errors = [] self.plugins = {} self.modules = tangelo.util.ModuleCache(config=False) # Create a virtual module to hold all plugin python modules. package_parts = self.base_package.split(".") for pkg_step in range(len(package_parts)): package = ".".join(package_parts[:pkg_step + 1]) if package not in sys.modules: sys.modules[package] = imp.new_module(package) if not pkg_step: globals()[package] = sys.modules[package] else: package_root = ".".join(package_parts[:pkg_step]) setattr(sys.modules[package_root], package_parts[pkg_step], sys.modules[package]) # A null config should be treated as an empty list. if config is None: config = [] startlist = [] # Read through the list of plugin configs, extracting the info and # validating as we go. for i, entry in enumerate(config): if not isinstance(entry, dict): self.errors.append("Configuration for plugin %d is not an associative array" % (i + 1)) return name = entry.get("name") if name is None: self.errors.append("Configuration for plugin %d is missing required 'name' property" % (i + 1)) return if name in self.plugins: self.errors.append("Configuration for plugin %d uses duplicate plugin name '%s'" % (i + 1, name)) return # Copy the entry so we don't alter the config object self.plugins[name] = entry.copy() del self.plugins[name]["name"] startlist.append(name) # Load all the plugins one by one, bailing out if there are any errors. for plugin in startlist: conf = self.plugins[plugin] if "path" in conf: # Extract the plugin path. path = os.path.abspath(conf["path"]) else: # Construct the plugin path, given the name of the plugin, # and the base path of Tangelo. path = os.path.join(self.plugin_dir, plugin) if not self.load(plugin, path): self.errors.append("Plugin %s failed to load" % (plugin)) return tangelo.log_info("Plugin %s loaded" % (plugin)) def good(self): return len(self.errors) == 0 def plugin_list(self): return self.plugins.keys() def load(self, plugin_name, path): tangelo.log_info("PLUGIN", "Loading plugin %s (from %s)" % (plugin_name, path)) if not os.path.exists(path): self.errors.append("Plugin path %s does not exist" % (path)) return False plugin = Plugins.Plugin(path) # Check for a configuration file. config_file = os.path.join(path, "config.yaml") config = {} if os.path.exists(config_file): try: config = tangelo.util.yaml_safe_load(config_file) except TypeError as e: self.errors.append("Bad configuration for plugin %s (%s): %s" % (plugin_name, config_file, e)) return False except IOError: self.errors.append("Could not open configuration for plugin %s (%s)" % (plugin_name, config_file)) return False except ValueError as e: self.errors.append("Error reading configuration for plugin %s (%s): %s" % (plugin_name, config_file, e)) return False # Install the config and an empty dict as the plugin-level # config and store. cherrypy.config["plugin-config"][path] = config cherrypy.config["plugin-store"][path] = {} # Check for a "python" directory, and place all modules found # there in a virtual submodule of tangelo.plugin. python = os.path.join(path, "python") if os.path.exists(python) or os.path.exists(python + ".py"): tangelo.log_info("PLUGIN", "\t...loading python module content") try: find_mod_results = imp.find_module("python", [path]) except ImportError: self.errors.append("'python' directory of plugin %s is missing __init.py__" % (plugin_name)) return False module_name = "%s.%s" % (self.base_package, plugin_name) plugin.module = module_name try: new_module = imp.load_module(module_name, *list(find_mod_results)) except Exception: self.errors.append("Could not import python module content for plugin %s:\n%s" % (plugin_name, traceback.format_exc())) return False finally: if find_mod_results[0]: find_mod_results[0].close() setattr(sys.modules[self.base_package], plugin_name, new_module) # Check for any setup that needs to be done, including any apps # that need to be mounted. control_file = os.path.join(path, "control.py") if os.path.exists(control_file): tangelo.log_info("PLUGIN", "\t...loading plugin control module") try: control = self.modules.get(control_file) plugin.control = control except: self.errors.append("Could not import control module for plugin %s:\n%s" % (plugin_name, traceback.format_exc())) return False else: if "setup" in dir(control): tangelo.log_info("PLUGIN", "\t...running plugin setup") try: setup = control.setup(config, cherrypy.config["plugin-store"][path]) except: self.errors.append("Could not set up plugin %s:\n%s" % (plugin_name, traceback.format_exc())) return False else: for app in setup.get("apps", []): if len(app) == 2: (app_obj, mountpoint) = app app_config = {} elif len(app) == 3: (app_obj, app_config, mountpoint) = app else: self.errors.append("App mount spec for plugin %s has %d item%s (should be either 2 or 3)" % (plugin_name, len(app), "" if len(app) == 1 else "s")) return False app_path = os.path.join("/plugin", plugin_name, mountpoint) if app_path in cherrypy.tree.apps: self.errors.append("Failed to mount application for plugin %s at %s (app already mounted there)" % (plugin_name, app_path)) return False else: tangelo.log_info("PLUGIN", "\t...mounting application at %s" % (app_path)) cherrypy.tree.mount(app_obj, app_path, app_config) plugin.apps.append(app_path) self.plugins[plugin_name] = plugin return True def unload(self, plugin_name): tangelo.log_info("PLUGIN", "Unloading plugin '%s'" % (plugin_name)) plugin = self.plugins[plugin_name] if plugin.module is not None: tangelo.log_info("PLUGIN", "\t...removing module %s" % (plugin.module)) del sys.modules[plugin.module] for app_path in plugin.apps: tangelo.log_info("PLUGIN", "\t...unmounting app at %s" % (app_path)) del cherrypy.tree.apps[app_path] if "teardown" in dir(plugin.control): tangelo.log_info("PLUGIN", "\t...running teardown") try: plugin.control.teardown(cherrypy.config["plugin-config"][plugin.path], cherrypy.config["plugin-store"][plugin.path]) except: tangelo.log_warning("PLUGIN", "Could not run teardown:\n%s", (traceback.format_exc())) del self.plugins[plugin_name] tangelo.log_info("plugin %s unloaded" % (plugin_name)) def unload_all(self): for plugin_name in self.plugins.keys(): self.unload(plugin_name)
class Plugins(object): class Plugins(object): def __init__(self, path): pass def __init__(self, path): pass def good(self): pass def plugin_list(self): pass def load(self, plugin_name, path): pass def unload(self, plugin_name): pass def unload_all(self): pass
9
0
27
4
21
2
6
0.11
1
10
2
0
6
5
6
6
199
31
152
46
143
16
146
45
137
19
1
6
41
142,754
Kitware/tangelo
tangelo/tangelo/server.py
tangelo.server.Tangelo
class Tangelo(object): def __init__(self, module_cache=None, plugins=None): self.modules = tangelo.util.ModuleCache() if module_cache is None else module_cache self.auth_update = None self.plugins = plugins def invoke_service(self, module, *pargs, **kwargs): tangelo.content_type("text/plain") # Save the system path (be sure to *make a copy* using the list() # function). This will be restored to undo any modification of the path # done by the service. origpath = list(sys.path) # By default, the result should be an object with error message in if # something goes wrong; if nothing goes wrong this will be replaced # with some other object. result = {} # Store the modpath in the thread-local storage (tangelo.paths() makes # use of this per-thread data, so this is the way to get the data # across the "module boundary" properly). modpath = os.path.dirname(module) cherrypy.thread_data.modulepath = modpath cherrypy.thread_data.modulename = module # Change the current working directory to that of the service module, # saving the old one. This is so that the service function executes as # though it were a Python program invoked normally, and Tangelo can # continue running later in whatever its original CWD was. save_cwd = os.getcwd() os.chdir(modpath) try: service = self.modules.get(module) except: tangelo.http_status(500, "Service Error") tangelo.content_type("application/json") error_code = tangelo.util.generate_error_code() tangelo.util.log_traceback("SERVICE", error_code, "Could not import service module %s" % (tangelo.request_path())) result = tangelo.util.error_report(error_code) else: # Try to run the service - either it's in a function called # "run()", or else it's in a REST API consisting of at least one of # "get()", "put()", "post()", or "delete()". # # Collect the result in a variable - depending on its type, it will # be transformed in some way below (by default, to JSON, but may # also raise a cherrypy exception, log itself in a streaming table, # etc.). try: if "run" in dir(service): # Call the module's run() method, passing it the positional # and keyword args that came into this method. result = service.run(*pargs, **kwargs) else: # Reaching here means it's a REST API. Check for the # requested method, ensure that it was marked as being part # of the API, and call it; or give a 405 error. method = cherrypy.request.method restfunc = service.__dict__.get(method.lower()) if (restfunc is not None and hasattr(restfunc, "restful") and restfunc.restful): result = restfunc(*pargs, **kwargs) else: tangelo.http_status(405, "Method Not Allowed") tangelo.content_type("application/json") result = {"error": "Method '%s' is not allowed in this service" % (method)} except: tangelo.http_status(500, "Service Error") tangelo.content_type("application/json") error_code = tangelo.util.generate_error_code() tangelo.util.log_traceback("SERVICE", error_code, "Could not execute service %s" % (tangelo.request_path())) result = tangelo.util.error_report(error_code) # Restore the path to what it was originally. sys.path = origpath # Restore the CWD to what it was before the service invocation. os.chdir(save_cwd) # If the result is a redirect request, then convert it to the # appropriate CherryPy logic and continue. # # Otherwise, if it's a file service request, then serve the file using # CherryPy facilities. # # Finally, if the result is not a string, attempt to convert it to one # via JSON serialization. This allows services to return a Python # object if they wish, or to perform custom serialization (such as for # MongoDB results, etc.). if isinstance(result, tangelo._Redirect): raise cherrypy.HTTPRedirect(result.path, result.status) elif isinstance(result, tangelo._InternalRedirect): raise cherrypy.InternalRedirect(result.path) elif isinstance(result, tangelo._File): result = cherrypy.lib.static.serve_file(result.path, result.content_type) elif not isinstance(result, types.StringTypes): try: result = json.dumps(result) except TypeError as e: tangelo.http_status(400, "JSON Error") tangelo.content_type("application/json") result = {"error": "JSON type error executing service", "message": e.message} else: tangelo.content_type("application/json") return result @staticmethod def dirlisting(dirpath, reqpath): if reqpath[-1] == "/": reqpath = reqpath[:-1] files = filter(lambda x: len(x) > 0 and x[0] != ".", os.listdir(dirpath)) # filespec = ["Type", "Name", "Last modified", "Size"] filespec = [] for f in files: p = dirpath + os.path.sep + f try: s = os.stat(p) except OSError: pass else: mtime = (datetime.datetime .fromtimestamp(s.st_mtime) .strftime("%Y-%m-%d %H:%M:%S")) if os.path.isdir(p): f += "/" t = "dir" s = "-" else: t = "file" s = s.st_size filespec.append([t, "<a href=\"%s/%s\">%s</a>" % (reqpath, f, f), mtime, s]) filespec = "\n".join( map(lambda row: "<tr>" + "".join(map(lambda x: "<td>%s</td>" % x, row)) + "</tr>", filespec)) result = """<!doctype html> <title>Index of %s</title> <h1>Index of %s</h1> <table> <tr> <th>Type</th><th>Name</th><th>Last Modified</th><th>Size</th> </tr> %s </table> """ % (reqpath, reqpath, filespec) return result def execute_analysis(self, query_args): # Hide the identity/version number of the server technology in the # response headers. cherrypy.response.headers["Server"] = "" # Analyze the URL. analysis = analyze_url(cherrypy.request.path_info) directive = analysis.directive content = analysis.content # If any "directives" were found (i.e., redirections) perform them here. if directive is not None: if directive.type == Directive.HTTPRedirect: raise cherrypy.HTTPRedirect(analysis.directive.argument) elif directive.type == Directive.InternalRedirect: raise cherrypy.InternalRedirect(analysis.directive.argument) elif directive.type == Directive.ListPlugins: tangelo.content_type("application/json") plugin_list = self.plugins.plugin_list() if self.plugins else [] return json.dumps(plugin_list) else: raise RuntimeError("fatal internal error: illegal directive type code %d" % (analysis.directive.type)) # If content was actually found at the URL, perform any htaccess updates # now. do_auth = self.auth_update and content is None or content.type != Content.NotFound if do_auth: self.auth_update.update(analysis.reqpathcomp, analysis.pathcomp) # Serve content here, either by serving a static file, generating a # directory listing, executing a service, or barring the client entry. if content is not None: if content.type == Content.File: if content.path is not None: return cherrypy.lib.static.serve_file(content.path) else: raise cherrypy.HTTPError("403 Forbidden", "The requested path is forbidden") elif content.type == Content.Directory: if content.path is not None: return Tangelo.dirlisting(content.path, cherrypy.request.path_info) else: raise cherrypy.HTTPError("403 Forbidden", "Listing of this directory has been disabled") elif content.type == Content.Service: cherrypy.thread_data.pluginpath = analysis.plugin_path return self.invoke_service(content.path, *content.pargs, **query_args) elif content.type == Content.NotFound: raise cherrypy.HTTPError("404 Not Found", "The path '%s' was not found" % (content.path)) else: raise RuntimeError("fatal error: illegal content type code %d" % (content.type)) else: raise RuntimeError("fatal internal error: analyze_url() returned analysis without directive or content") @cherrypy.expose def plugin(self, *path, **args): return self.execute_analysis(args) @cherrypy.expose def default(self, *path, **args): return self.execute_analysis(args)
class Tangelo(object): def __init__(self, module_cache=None, plugins=None): pass def invoke_service(self, module, *pargs, **kwargs): pass @staticmethod def dirlisting(dirpath, reqpath): pass def execute_analysis(self, query_args): pass @cherrypy.expose def plugin(self, *path, **args): pass @cherrypy.expose def default(self, *path, **args): pass
10
0
36
4
24
8
6
0.32
1
10
3
0
5
3
6
6
223
27
149
35
139
47
110
31
103
14
1
4
33
142,755
Kitware/tangelo
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kitware_tangelo/tangelo/tangelo/pkgdata/plugin/vtkweb/web/vtkweb.py
vtkweb.post.FactoryStarted
class FactoryStarted: pass
class FactoryStarted: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
142,756
Kitware/tangelo
tangelo/tangelo/server.py
tangelo.server.UrlAnalyzer
class UrlAnalyzer(object): instance = None def __init__(self): UrlAnalyzer.instance = self def blocked(self): raise RuntimeError("You are not allowed to instantiate UrlAnalyzer") UrlAnalyzer.__init__ = blocked @staticmethod def is_python_file(path): pyfile_ext = [".py", ".pyw", ".pyc", ".pyo", ".pyd"] return len(path) > 0 and any(path.endswith(ext) for ext in pyfile_ext) @staticmethod def is_service_config_file(path): return path.endswith(".yaml") and os.path.exists(".".join(os.path.join(path.split(".")[:-1])) + ".py") def accessible(self, path): listdir = cherrypy.config.get("listdir") showpy = cherrypy.config.get("showpy") if os.path.isdir(path): return listdir elif UrlAnalyzer.is_python_file(path): config_file = ".".join(path.split(".")[:-1]) + ".yaml" if os.path.exists(config_file): try: config = tangelo.util.yaml_safe_load(config_file, dict) except (ValueError, TypeError): tangelo.log_warning("Config file %s could not be read - locking down associated web service source" % (path)) return False else: config_showpy = config.get("show-py") if config_showpy is not None: if not isinstance(config_showpy, bool): tangelo.log_warning("Config file %s has a non-boolean 'show-py' property - locking down associated web service source" % (path)) return False return config_showpy return showpy elif UrlAnalyzer.is_service_config_file(path): return False else: return True def analyze(self, raw_reqpath): webroot = cherrypy.config.get("webroot") plugins = cherrypy.config.get("plugins") reqpath = raw_reqpath analysis = UrlAnalysis() # If the request path is blank, redirect to /. if reqpath == "": analysis.directive = Directive(Directive.HTTPRedirect, argument="/") return analysis # If the request path does not begin with a /, then it is invalid. if reqpath[0] != "/": raise ValueError("request path must be absolute, i.e., begin with a slash") # If the request path is to a plugin, substitute the correct webroot # path. if reqpath.split("/")[1] == "plugin": plugin_comp = reqpath.split("/") if len(plugin_comp) < 3: analysis.directive = Directive(Directive.ListPlugins) return analysis plugin = plugin_comp[2] if plugins is None or plugin not in plugins.plugins: analysis.content = Content(Content.NotFound, path=raw_reqpath) return analysis analysis.plugin_path = plugins.plugins[plugin].path webroot = plugins.plugins[plugin].path + "/web" reqpath = "/" + "/".join(plugin_comp[3:]) # Compute "parallel" path component lists based on the web root and the disk # root. if reqpath == "/": reqpathcomp = [] pathcomp = [webroot] else: # Split the request path into path components, omitting the leading # slash. reqpathcomp = reqpath[1:].split("/") # Compute the disk path the URL corresponds to. pathcomp = [webroot] + reqpathcomp # Save the request path and disk path components, slightly modifying the # request path if it refers to an absolute path (indicated by being one # element shorter than the disk path). if len(reqpathcomp) == len(pathcomp) - 1: reqpathcomp_save = [""] + reqpathcomp elif len(reqpathcomp) == len(pathcomp): reqpathcomp_save = ["/" + reqpathcomp[0]] + reqpathcomp[1:] else: raise RuntimeError("reqpathcomp and pathcomp lengths are wonky") # If the path represents a directory and has a trailing slash, remove it # (this will make the auth update step easier). if (len(reqpathcomp_save) > 1 and reqpathcomp_save[-1] == "" or pathcomp[-1] == ""): assert reqpathcomp_save[-1] == "" and pathcomp[-1] == "" reqpathcomp_save = reqpathcomp_save[:-1] pathcomp_save = pathcomp[:-1] else: pathcomp_save = pathcomp analysis.reqpathcomp = reqpathcomp_save analysis.pathcomp = pathcomp_save # If pathcomp has more than one element, fuse the first two together. This # makes the search for a possible service below much simpler. if len(pathcomp) > 1: pathcomp = [os.path.join(pathcomp[0], pathcomp[1])] + pathcomp[2:] # Form an actual path string. path = os.path.join(*pathcomp) # If the path is a directory, check for a trailing slash. If missing, # perform a redirect to the path WITH the trailing slash. Otherwise, # check for an index.html file in that directory; if found, perform an # internal redirect to that file. Otherwise, leave the path alone - it # now represents a request for a directory listing. # # If instead the path isn't a directory, check to see if it's a regular # file. If it is, save the path in thread local storage - this will let # the handler very quickly serve the file. # # If it is not a regular file, then check to see if it is a python service. # # Finally, if it is none of the above, then indicate a 404 error. if os.path.isdir(path): if raw_reqpath[-1] != "/": analysis.directive = Directive(Directive.HTTPRedirect, argument=raw_reqpath + "/") return analysis elif os.path.exists(path + os.path.sep + "index.html"): analysis.directive = Directive(Directive.InternalRedirect, argument=raw_reqpath + "index.html") return analysis else: # Only serve a directory listing if the security policy allows it. analysis.content = Content(Content.Directory, path=path if self.accessible(path) else None) elif os.path.exists(path): # Only serve a file if the security policy allows it. analysis.content = Content(Content.File, path=path if self.accessible(path) else None) else: service_path = None pargs = None for i in range(len(pathcomp)): service_path = os.path.sep.join(pathcomp[:(i + 1)]) + ".py" if os.path.exists(service_path): pargs = pathcomp[(i + 1):] break if pargs is None: analysis.content = Content(Content.NotFound, path=raw_reqpath) else: analysis.content = Content(Content.Service, path=service_path, pargs=pargs) return analysis
class UrlAnalyzer(object): def __init__(self): pass def blocked(self): pass @staticmethod def is_python_file(path): pass @staticmethod def is_service_config_file(path): pass def accessible(self, path): pass def analyze(self, raw_reqpath): pass
9
0
27
4
18
5
5
0.29
1
9
3
0
3
0
5
5
170
28
110
30
101
32
94
28
87
20
1
4
32
142,757
Kitware/tangelo
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kitware_tangelo/tangelo/tangelo/pkgdata/plugin/vtkweb/include/vtkweb-launcher.py
vtkweb-launcher.VTKWebAppProtocol.VTKWebApp
class VTKWebApp(wamp.ServerProtocol): # Application configuration view = None authKey = "vtkweb-secret" def __init__(self): # Because the ServerProtocol constructor directly calls # initialize(), be sure to set these instance properties FIRST. self.args = args self.app = usermod wamp.ServerProtocol.__init__(self) def initialize(self): # Bring used components self.registerVtkWebProtocol(protocols.vtkWebMouseHandler()) self.registerVtkWebProtocol(protocols.vtkWebViewPort()) self.registerVtkWebProtocol( protocols.vtkWebViewPortImageDelivery()) self.registerVtkWebProtocol( protocols.vtkWebViewPortGeometryDelivery()) # Update authentication key to use self.updateSecret(VTKWebApp.authKey) if "initialize" in self.app.__dict__: self.app.initialize(self, VTKWebApp, self.args)
class VTKWebApp(wamp.ServerProtocol): def __init__(self): pass def initialize(self): pass
3
0
11
2
7
2
2
0.29
1
0
0
0
2
2
2
2
27
5
17
7
14
5
15
7
12
2
1
1
3
142,758
Kitware/tangelo
tangelo/tangelo/util.py
tangelo.util.ModuleCache
class ModuleCache(object): def __init__(self, config=True): self.config = config self.modules = {} self.config_files = {} def get(self, module): return module_cache_get(self, module)
class ModuleCache(object): def __init__(self, config=True): pass def get(self, module): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
3
2
2
8
1
7
6
4
0
7
6
4
1
1
0
2
142,759
Kitware/tangelo
tangelo/tangelo/server.py
tangelo.server.UrlAnalysis
class UrlAnalysis(object): def __init__(self): self.directive = None self.content = None self.reqpathcomp = None self.pathcomp = None self.plugin_path = None def __str__(self): import pprint d = {} for k, v in self.__dict__.iteritems(): if v is not None and k in ["content", "directive"]: d[k] = v.__dict__ else: d[k] = v return pprint.pformat(d)
class UrlAnalysis(object): def __init__(self): pass def __str__(self): pass
3
0
8
0
8
0
2
0
1
0
0
0
2
5
2
2
17
1
16
11
12
0
15
11
11
3
1
2
4
142,760
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/twitter.py
autotweet.twitter.OAuthToken
class OAuthToken(object): key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret def to_string(self): return urlencode({ 'oauth_token': self.key, 'oauth_token_secret': self.secret, }) @staticmethod def from_string(string): params = cgi.parse_qs(string, keep_blank_values=False) key = params['oauth_token'][0] secret = params['oauth_token_secret'][0] return OAuthToken(key, secret)
class OAuthToken(object): def __init__(self, key, secret): pass def to_string(self): pass @staticmethod def from_string(string): pass
5
0
4
0
4
0
1
0
1
0
0
0
2
0
3
3
20
3
17
10
12
0
13
9
9
1
1
0
3
142,761
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/telegram_bot.py
autotweet.telegram_bot.TelegramBot
class TelegramBot(object): def __init__(self, db_uri, token, threshold, learning=True, answering=True): self._make_updater(token) self.threshold = threshold self.data_collection = DataCollection(db_uri) self._init_handlers() if learning: self.enable_learning() if answering: self.enable_answering() def run(self): logger.info('Starting with {} documents.'.format( self.data_collection.get_count())) self.me = self.updater.bot.get_me() self.updater.start_polling() self.updater.idle() def learning_handler(self, bot, update): question = strip_tweet(update.message.reply_to_message.text) answer = strip_tweet(update.message.text, remove_url=False) self.data_collection.add_document(question, answer) def answering_handler(self, bot, update): question = strip_tweet(update.message.text) try: answer, ratio = self.data_collection.get_best_answer(question) if (ratio > self.threshold or self._is_necessary_to_reply(bot, update)): logger.info('{} -> {}'.format(question, answer)) update.message.reply_text(answer) except NoAnswerError: logger.debug('No answer to {}'.format(update.message.text)) if self._is_necessary_to_reply(bot, update): update.message.reply_text(r'¯\_(ツ)_/¯') def leave_handler(self, bot, update): logger.info('Leave from chat {}'.format(update.message.chat_id)) bot.leave_chat(update.message.chat_id) def enable_learning(self): logger.debug('Enabling learning handler.') self.dispatcher.add_handler( MessageHandler(Filters.reply, self.learning_handler)) def enable_answering(self): logger.debug('Enabling answer handler.') self.dispatcher.add_handler( MessageHandler(Filters.text, self.answering_handler)) def _make_updater(self, token): self.updater = Updater(token) self.dispatcher = self.updater.dispatcher def _init_handlers(self): self.dispatcher.add_handler(CommandHandler('leave', self.leave_handler)) def _is_necessary_to_reply(self, bot, update): message = update.message if message.chat.type == 'private': logger.debug('{} type private'.format(message.text)) return True matched = re.search(r'@{}\b'.format(self.me.username), message.text) result = bool(matched) if result: logger.debug('{} mentioned me.'.format(message.text)) return True return False
class TelegramBot(object): def __init__(self, db_uri, token, threshold, learning=True, answering=True): pass def run(self): pass def learning_handler(self, bot, update): pass def answering_handler(self, bot, update): pass def leave_handler(self, bot, update): pass def enable_learning(self): pass def enable_answering(self): pass def _make_updater(self, token): pass def _init_handlers(self): pass def _is_necessary_to_reply(self, bot, update): pass
11
0
6
1
6
0
2
0
1
3
2
0
10
5
10
10
73
14
59
23
48
0
55
23
44
4
1
2
17
142,762
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/telegram_bot.py
autotweet.telegram_bot.ReplyFilter
class ReplyFilter(BaseFilter): def filter(self, message): return bool(message.reply_to_message)
class ReplyFilter(BaseFilter): def filter(self, message): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
142,763
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/learning.py
autotweet.learning.NoAnswerError
class NoAnswerError(Exception): """Raises when autotweet can not found best answer to a question. :param msg: A message for the exception :type msg: :class:`str` """ def __init__(self, msg): self.msg = msg def __str__(self): return repr(self.msg)
class NoAnswerError(Exception): '''Raises when autotweet can not found best answer to a question. :param msg: A message for the exception :type msg: :class:`str` ''' def __init__(self, msg): pass def __str__(self): pass
3
1
2
0
2
0
1
0.8
1
0
0
0
2
1
2
12
13
4
5
4
2
4
5
4
2
1
3
0
2
142,764
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/learning.py
autotweet.learning.DataCollection
class DataCollection(object): def __init__(self, db_url): self.Session = get_session(db_url) def add_document(self, question, answer): """Add question answer set to DB. :param question: A question to an answer :type question: :class:`str` :param answer: An answer to a question :type answer: :class:`str` """ question = question.strip() answer = answer.strip() session = self.Session() if session.query(Document) \ .filter_by(text=question, answer=answer).count(): logger.info('Already here: {0} -> {1}'.format(question, answer)) return logger.info('add document: {0} -> {1}'.format(question, answer)) grams = self._get_grams(session, question, make=True) doc = Document(question, answer) doc.grams = list(grams) self._recalc_idfs(session, grams) session.add(doc) session.commit() def get_best_answer(self, query): """Get best answer to a question. :param query: A question to get an answer :type query: :class:`str` :returns: An answer to a question :rtype: :class:`str` :raises: :class:`NoAnswerError` when can not found answer to a question """ query = to_unicode(query) session = self.Session() grams = self._get_grams(session, query) if not grams: raise NoAnswerError('Can not found answer') documents = set([doc for gram in grams for doc in gram.documents]) self._recalc_idfs(session, grams) idfs = dict((gram.gram, gram.idf) for gram in grams) docs = dict( (doc.answer, _cosine_measure(idfs, self._get_tf_idfs(doc))) for doc in documents) docs = dict((key, val) for (key, val) in docs.items() if val) session.commit() try: max_ratio = max(docs.values()) answers = [answer for answer in docs.keys() if docs.get(answer) == max_ratio] answer = random.choice(answers) logger.debug('{0} -> {1} ({2})'.format(query, answer, max_ratio)) return (answer, max_ratio) except ValueError: raise NoAnswerError('Can not found answer') finally: session.commit() def recreate_grams(self): """Re-create grams for database. In normal situations, you never need to call this method. But after migrate DB, this method is useful. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` """ session = self.Session() for document in session.query(Document).all(): logger.info(document.text) grams = self._get_grams(session, document.text, make=True) document.grams = list(grams) broken_links = session.query(Gram) \ .filter(~Gram.documents.any()).all() for gram in broken_links: session.delete(gram) session.commit() def recalc_idfs(self, grams=None): session = self.Session() self._recalc_idfs(session, grams) session.commit() def _recalc_idfs(self, session, grams=None): """Re-calculate idfs for database. calculating idfs for gram is taking long time. So I made it calculates idfs for some grams. If you want make accuracy higher, use this with grams=None. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` :param grams: grams that you want to re-calculating idfs :type grams: A set of :class:`Gram` """ if not grams: grams = session.query(Gram) for gram in grams: orig_idf = gram.idf gram.idf = self._get_idf(session, gram) logger.debug('Recalculating {} {} -> {}'.format( gram.gram, orig_idf, gram.idf)) def get_count(self): """Get count of :class:`Document`. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` """ return self.Session.query(Document).count() def _get_grams(self, session, text, make=False): grams = set() if len(text) < GRAM_LENGTH: gram_obj = session.query(Gram).filter_by(gram=text).first() if gram_obj: grams.add(gram_obj) elif make: gram_obj = Gram(text) session.add(gram_obj) grams.add(gram_obj) else: for i in range(len(text) - GRAM_LENGTH + 1): gram = text[i:i+GRAM_LENGTH] gram_obj = session.query(Gram).filter_by(gram=gram).first() if gram_obj: grams.add(gram_obj) else: gram_obj = Gram(gram) grams.add(gram_obj) if make: session.add(gram_obj) return grams @staticmethod def _get_tf(gram, document): if isinstance(gram, Gram): gram = gram.gram gram = make_string(gram) return document.text.count(gram) + document.answer.count(gram) def _get_idf(self, session, gram): all_count = session.query(Document).count() d_count = len(gram.documents) return math.log((all_count / (1.0 + d_count)) + 1) def _get_tf_idfs(self, document): tf_idfs = dict( (gram.gram, self._get_tf(gram, document) * gram.idf) for gram in document.grams if gram.idf is not None) return tf_idfs
class DataCollection(object): def __init__(self, db_url): pass def add_document(self, question, answer): '''Add question answer set to DB. :param question: A question to an answer :type question: :class:`str` :param answer: An answer to a question :type answer: :class:`str` ''' pass def get_best_answer(self, query): '''Get best answer to a question. :param query: A question to get an answer :type query: :class:`str` :returns: An answer to a question :rtype: :class:`str` :raises: :class:`NoAnswerError` when can not found answer to a question ''' pass def recreate_grams(self): '''Re-create grams for database. In normal situations, you never need to call this method. But after migrate DB, this method is useful. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` ''' pass def recalc_idfs(self, grams=None): pass def _recalc_idfs(self, session, grams=None): '''Re-calculate idfs for database. calculating idfs for gram is taking long time. So I made it calculates idfs for some grams. If you want make accuracy higher, use this with grams=None. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` :param grams: grams that you want to re-calculating idfs :type grams: A set of :class:`Gram` ''' pass def get_count(self): '''Get count of :class:`Document`. :param session: DB session :type session: :class:`sqlalchemt.orm.Session` ''' pass def _get_grams(self, session, text, make=False): pass @staticmethod def _get_tf(gram, document): pass def _get_idf(self, session, gram): pass def _get_tf_idfs(self, document): pass
13
5
16
3
9
3
2
0.3
1
8
3
0
10
1
11
11
187
49
106
39
93
32
92
38
80
7
1
4
25
142,765
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/database.py
autotweet.database.Gram
class Gram(Base): __tablename__ = 'grams' id = Column(Integer, primary_key=True) gram = Column(String(GRAM_LENGTH), unique=True, nullable=False) idf = Column(Float) def __init__(self, gram): self.gram = gram
class Gram(Base): def __init__(self, gram): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
8
1
7
5
5
0
7
5
5
1
1
0
1
142,766
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/daemons.py
autotweet.daemons.CollectorMentionListener
class CollectorMentionListener(tweepy.streaming.StreamListener): def __init__(self, api, db_url): super(CollectorMentionListener, self).__init__() self.api = api self.data_collection = DataCollection(db_url) self.me = api.me() def on_status(self, status): if check_ignore(status): return True if status.user.id == self.me.id and status.in_reply_to_status_id: original_status = self.api.get_status( status.in_reply_to_status_id, tweet_mode='extended' ) question = strip_tweet(get_full_text(original_status)) answer = strip_tweet(get_full_text(status), remove_url=False) if question and answer: self.data_collection.add_document(question, answer) return True
class CollectorMentionListener(tweepy.streaming.StreamListener): def __init__(self, api, db_url): pass def on_status(self, status): pass
3
0
11
2
9
0
3
0
1
2
1
0
2
3
2
2
25
6
19
9
16
0
16
9
13
4
1
2
5
142,767
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/daemons.py
autotweet.daemons.AnswerMentionListener
class AnswerMentionListener(tweepy.streaming.StreamListener): threshold = DEFAULT_THRESHOLD friends_timeout = 60 friends_updated = None def __init__(self, api, db_url, threshold=None): super(AnswerMentionListener, self).__init__() self.api = api self.data_collection = DataCollection(db_url) self.me = api.me() if threshold: self.threshold = threshold def get_friends(self): if self.friends_updated is None or \ time.time() - self.friends_updated > self.friends_timeout: self.friends = get_friends(self.api) self.friends_updated = time.time() return self.friends def on_status(self, status): if hasattr(status, 'retweeted_status') or status.user.id == self.me.id: return True mentions = get_mentions(status, self.get_friends()) question = strip_tweet(get_full_text(status)) status_id = status.id try: answer, ratio = self.data_collection.get_best_answer(question) except NoAnswerError: return True if status.in_reply_to_user_id == self.me.id or ratio >= self.threshold: answer_logger.info('@{0.user.screen_name}: {0.text} -> {1}'.format( status, answer )) try: self.api.update_status( status='{0} {1}'.format(' '.join(mentions), answer), in_reply_to_status_id=status_id) except tweepy.error.TweepError as e: answer_logger.error('Failed to update status: {0}'.format( e.message ))
class AnswerMentionListener(tweepy.streaming.StreamListener): def __init__(self, api, db_url, threshold=None): pass def get_friends(self): pass def on_status(self, status): pass
4
0
14
2
12
0
3
0
1
3
2
0
3
4
3
3
48
9
39
16
35
0
32
15
28
5
1
2
9
142,768
Kjwon15/autotweet
Kjwon15_autotweet/autotweet/database.py
autotweet.database.Document
class Document(Base): __tablename__ = 'documents' __table_args__ = ( UniqueConstraint('text', 'answer'), ) id = Column(Integer, primary_key=True) text = Column(String(140), nullable=False) answer = Column(String(140), nullable=False) grams = relationship( 'Gram', secondary=association_table, backref='documents') __table_args__ = (UniqueConstraint('text', 'answer'),) def __init__(self, text, answer): self.text = text self.answer = answer
class Document(Base): def __init__(self, text, answer): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
0
1
1
16
2
14
7
12
0
11
7
9
1
1
0
1
142,769
KnightConan/sspdatatables
KnightConan_sspdatatables/src/sspdatatables/utils/enum.py
sspdatatables.utils.enum.ExtendedEnumMeta
class ExtendedEnumMeta(EnumMeta): """ Meta class to extend the EnumMeta class with several functions according to the returned result of the class method 'attr_names' in Enumeration class. It will create two kind of functions for each attr_name: 1. returns the collective results of the same attr_name from all enumerations of the same Enumeration class 2. returns the enumeration according to the given value of the specific attr_name """ def __new__(mcs, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: """ Intends to create the functions with name formats: <attr_name>s and from_<attr_name> for each attr_name in the result of class method 'attr_names' in its instance classes :param name: str: name of the instance class :param bases: tuple: base classes, its instance class inherits from :param namespace: dict: contains the attributes and functions of the instance class :return: class object """ cls = super().__new__(mcs, name, bases, namespace) func_name_and_doc = [ ("%ss", "Collective function to return the values of the attribute %s from" " all the enumerations in the Enum class.", mcs._attrs_), ("from_%s", "Returns the corresponding enumeration according to the given " "value of the attribute %s.", mcs._from_attr_) ] for attr_name in cls.attr_names(): for name, docstring, meta_func in func_name_and_doc: func_name = name % attr_name func_docstring = docstring % attr_name setattr(cls, func_name, partial(meta_func, cls, attr_name)) # override the docstring of the partial function getattr(cls, func_name).__doc__ = func_docstring return cls @classmethod def _attrs_(mcs, cls, attr_name: str) -> Tuple[Any, ...]: """ Returns a tuple containing just the value of the given attr_name of all the elements from the cls. :return: tuple of different types """ return tuple(map(lambda x: getattr(x, attr_name), list(cls))) @classmethod def _from_attr_(mcs, cls, attr_name: str, attr_value: Any) -> TypeVar: """ Returns the enumeration item regarding to the attribute name and value, or None if not found for the given cls :param attr_name: str: attribute's name :param attr_value: different values: key to search for :return: Enumeration Item """ return next(iter(filter(lambda x: getattr(x, attr_name) == attr_value, list(cls))), None)
class ExtendedEnumMeta(EnumMeta): ''' Meta class to extend the EnumMeta class with several functions according to the returned result of the class method 'attr_names' in Enumeration class. It will create two kind of functions for each attr_name: 1. returns the collective results of the same attr_name from all enumerations of the same Enumeration class 2. returns the enumeration according to the given value of the specific attr_name ''' def __new__(mcs, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ''' Intends to create the functions with name formats: <attr_name>s and from_<attr_name> for each attr_name in the result of class method 'attr_names' in its instance classes :param name: str: name of the instance class :param bases: tuple: base classes, its instance class inherits from :param namespace: dict: contains the attributes and functions of the instance class :return: class object ''' pass @classmethod def _attrs_(mcs, cls, attr_name: str) -> Tuple[Any, ...]: ''' Returns a tuple containing just the value of the given attr_name of all the elements from the cls. :return: tuple of different types ''' pass @classmethod def _from_attr_(mcs, cls, attr_name: str, attr_value: Any) -> TypeVar: ''' Returns the enumeration item regarding to the attribute name and value, or None if not found for the given cls :param attr_name: str: attribute's name :param attr_value: different values: key to search for :return: Enumeration Item ''' pass
6
4
17
1
8
8
2
1.18
1
10
0
1
1
0
3
3
66
5
28
13
21
33
15
10
11
3
1
2
5
142,770
KnightConan/sspdatatables
KnightConan_sspdatatables/example/example/apps.py
example.apps.ExampleConfig
class ExampleConfig(AppConfig): name = 'example'
class ExampleConfig(AppConfig): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
142,771
KnightConan/sspdatatables
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KnightConan_sspdatatables/example/example/datatables/datatables.py
example.datatables.datatables.BookDataTables.Meta
class Meta: serializer = BookSerializer form = BookFieldSelectForm frame = [ { "id": "actions", "serializer_key": None, "header": "Actions", "searchable": False, "orderable": False, "footer_type": None, }, { "id": "id", "serializer_key": 'id', "header": "ID", "searchable": True, "orderable": True, "footer_type": "input", }, { "id": "name", "serializer_key": 'name', "header": "Name", "searchable": True, "orderable": True, "footer_type": "input", }, { "id": "author", "serializer_key": 'author.name', "header": "Author", "searchable": True, "orderable": True, "footer_type": "input", }, { "id": "author_nationality", "serializer_key": 'author.nationality.name', "header": "Author Nationality", "searchable": True, "orderable": True, "footer_type": "select", }, { "id": "published_at", "serializer_key": 'published_at', "header": "Published At", "searchable": True, "orderable": True, "footer_type": "input", "placeholder": "YYYY-MM-DD", }, ] mapping = BookEnum
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
37
0
37
5
36
0
5
5
4
0
0
0
0
142,772
KnightConan/sspdatatables
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KnightConan_sspdatatables/example/example/datatables/forms.py
example.datatables.forms.BookFieldSelectForm.Meta
class Meta: fields = [("author_nationality", ChoiceField),]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
142,773
KnightConan/sspdatatables
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KnightConan_sspdatatables/example/example/datatables/serializers.py
example.datatables.serializers.AuthorSerializer.Meta
class Meta: model = Author fields = ('name', 'nationality')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
142,774
KnightConan/sspdatatables
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KnightConan_sspdatatables/example/example/datatables/serializers.py
example.datatables.serializers.BookSerializer.Meta
class Meta: model = Book fields = ('id', 'name', 'published_at', 'author')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
142,775
KnightConan/sspdatatables
KnightConan_sspdatatables/example/sspdatatablesExample/apps.py
sspdatatablesExample.apps.SspdatatablesExampleConfig
class SspdatatablesExampleConfig(AppConfig): name = 'sspdatatablesExample'
class SspdatatablesExampleConfig(AppConfig): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
142,776
KnightConan/sspdatatables
KnightConan_sspdatatables/src/sspdatatables/utils/enum.py
sspdatatables.utils.enum.TripleEnum
class TripleEnum(ExtendedEnum): """ Extended enumeration class: implements some methods to work with tuples formed by a key, a label and an extra information in the format: FOO = (int, foo, extra). """ @classmethod def attr_names(cls) -> List[str]: return ['key', 'label', 'extra']
class TripleEnum(ExtendedEnum): ''' Extended enumeration class: implements some methods to work with tuples formed by a key, a label and an extra information in the format: FOO = (int, foo, extra). ''' @classmethod def attr_names(cls) -> List[str]: pass
3
1
2
0
2
0
1
1.25
1
1
0
1
0
0
1
58
9
0
4
3
1
5
3
2
1
1
5
0
1
142,777
KnightConan/sspdatatables
KnightConan_sspdatatables/example/example/datatables/forms.py
example.datatables.forms.BookFieldSelectForm
class BookFieldSelectForm(AbstractFooterForm): def get_author_nationality_choices(self): return [(None, 'Select')] + list(countries.countries.items()) class Meta: fields = [("author_nationality", ChoiceField),]
class BookFieldSelectForm(AbstractFooterForm): def get_author_nationality_choices(self): pass class Meta:
3
0
2
0
2
0
1
0
1
1
0
0
1
0
1
3
6
1
5
4
2
0
5
4
2
1
2
0
1
142,778
KnightConan/sspdatatables
KnightConan_sspdatatables/example/example/migrations/0001_initial.py
example.migrations.0001_initial.Migration
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Author', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=60)), ('nationality', django_countries.fields.CountryField(max_length=2)), ], ), migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=60)), ('description', models.TextField()), ('published_at', models.DateField(auto_now=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='example.Author')), ], ), ]
class Migration(migrations.Migration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
27
3
24
4
23
0
4
4
3
0
1
0
0
142,779
KnightConan/sspdatatables
KnightConan_sspdatatables/example/example/models.py
example.models.Author
class Author(models.Model): name = models.CharField(max_length=60) nationality = CountryField()
class Author(models.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
142,780
KnightConan/sspdatatables
KnightConan_sspdatatables/src/sspdatatables/apps.py
sspdatatables.apps.SspdatatablesConfig
class SspdatatablesConfig(AppConfig): name = 'sspdatatables'
class SspdatatablesConfig(AppConfig): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
142,781
KnightConan/sspdatatables
KnightConan_sspdatatables/src/sspdatatables/datatables.py
sspdatatables.datatables.DataTables
class DataTables(metaclass=DataTablesMeta): """ This class aims to simplify the process of using datatables's serverside option in a django project. It defines a similar structure like django ModelForm, using Meta class. Inside the Meta class, the user has to define couple things: * serializer: a ModelSerializer class (using rest_framework package) * form: a normal django from, which defines the choice fields for the footer. An abstract dynamical form is provided in forms.py file. * structure: list of dict, defines the table structure in frontend * structure_for_superuser: same as above, but for superuser * mapping: TripleEnum class, which holds the mapping between column number in frontend, corresponding field name in model class and corresponding key for filtering in DB Besides the Meta class, the functions, 'get_query_dict', 'query_by_args', can be customized by the user according to some specific use cases. The other functions are not necessary to be overridden. """ serializer = property(lambda self: self.Meta.serializer) """Wrapper to render the serializer in Meta class, it provides a way to use one DataTables class with different serializers.""" form = property(lambda self: self.Meta.form) """Wrapper to render the form in Meta class, it provides a way to use one DataTables class with different forms""" frame = property(lambda self: self.Meta.frame) """wrapper to render the structure in Meta class""" mapping = property(lambda self: self.Meta.mapping) """Wrapper to render the mapping in Meta class, it provides a way to use one DataTables class with different mappings.""" def footer_form(self, *args, **kwargs): """ wrapper to render an instance of the footer form, which is the form in Meta class :param args: list: args for the footer form initialization :param kwargs: dict: args for the footer form initialization :return: form instance """ return self.form(*args, **kwargs) def get_table_frame(self, prefix="", table_id="sspdtable", *args, **kwargs): """ render the structure (or structure_for_superuser) and an instance of the footer form :param prefix: str: used for unifying the rendered parameter's name, such that the template of serverside datatables can be used in one page multiple times :param table_id: str: :param args: list: args for the footer form initialization :param kwargs: dict: args for the footer form initialization :return: dict """ if not table_id: raise ValueError("table_id parameter can not be an empty string.") table_key = prefix + "sspdtable" context = { table_key: { "id": table_id, "frame": self.frame } } if self.form: context[table_key]['footer_form'] = self.footer_form(*args, **kwargs) return context def get_query_dict(self, **kwargs): """ function to generate a filter dictionary, in which the key is the keyword used in django filter function in string form, and the value is the searched value. :param kwargs:dict: query dict sent by data tables package :return: dict: filtering dictionary """ total_cols = ensure(int, kwargs.get('total_cols', [0])[0], 0) mapping = self.mapping filter_dict = defaultdict(dict) # set up the starter, since sometimes we start the enumeration from '1' starter = mapping.keys()[0] for i in range(starter, total_cols): key = 'columns[{index}]'.format(index=i) if kwargs.get(key + '[searchable]', [0])[0] != 'true': continue search_value = kwargs.get(key + '[search][value]', [''])[0].strip() if not search_value: continue enum_item = mapping.from_key(i) filter_obj = enum_item.extra if type(filter_obj) is tuple and len(filter_obj) == 2: filter_func, filter_key = filter_obj filter_dict[filter_func][filter_key] = search_value elif type(filter_obj) is str: filter_dict['filter'][filter_obj] = search_value else: raise ValueError("Invalid filter key.") return filter_dict def get_order_key(self, **kwargs): """ function to get the order key to apply it in the filtered queryset :param kwargs: dict: query dict sent by data tables package :return: str: order key, which can be used directly in queryset's order_by function """ # get the mapping enumeration class from Meta class mapping = self.mapping # use the first element in the enumeration as default order column order_column = kwargs.get('order[0][column]', [mapping.keys()[0]])[0] order_column = ensure(int, order_column, mapping.keys()[0]) order = kwargs.get('order[0][dir]', ['asc'])[0] order_key = mapping.from_key(order_column).label # django orm '-' -> desc if order == 'desc': order_key = '-' + order_key return order_key @staticmethod def filtering(queryset, query_dict): """ function to apply the pre search condition to the queryset to narrow down the queryset's size :param queryset: Django Queryset: queryset of all objects :param query_dict: dict: contains selected_related, filter and other customized filter functions :return: queryset: result after applying the pre search condition dict """ # apply pre_search_condition for key, value in query_dict.items(): assert hasattr(queryset, key), "Parameter 'query_dict' contains"\ " non-existent attribute." if isinstance(value, list): queryset = getattr(queryset, key)(*value) elif isinstance(value, dict): queryset = getattr(queryset, key)(**value) else: queryset = getattr(queryset, key)(value) return queryset @staticmethod def slicing(queryset, **kwargs): """ function to slice the queryset according to the display length :param queryset: Django Queryset: filtered and ordered queryset result :param kwargs: dict: query dict sent by data tables package :return: queryset: result after slicing """ # if the length is -1, we need to display all the records # otherwise, just slicing the queryset length = ensure(int, kwargs.get('length', [0])[0], 0) start = ensure(int, kwargs.get('start', [0])[0], 0) if length >= 0: queryset = queryset[start:start + length] return queryset def query_by_args(self, pre_search_condition=None, **kwargs): """ intends to process the queries sent by data tables package in frontend. The model_cls indicates the model class, get_query_dict is a function implemented by you, such that it can return a query dictionary, in which the key is the query keyword in str form and the value is the queried value :param pre_search_condition: None/OrderedDict: dictionary contains filter conditions which should be processed before applying the filter dictionary from user. None, if no pre_search_condition provided. :param kwargs: QueryDict: contains query parameters :return: dict: contains total records number, queryset of the filtered instances, size of this queryset """ if pre_search_condition and not isinstance(pre_search_condition, OrderedDict): raise TypeError( "Parameter 'pre_search_condition' must be an OrderedDict.") # extract requisite parameters from kwargs draw = ensure(int, kwargs.get('draw', [0])[0], 0) # just implement the get_query_dict function query_dict = self.get_query_dict(**kwargs) order_key = self.get_order_key(**kwargs) # get the model from the serializer parameter model_class = self.serializer.Meta.model # get the objects queryset = model_class.objects # apply the pre search condition if it exists if pre_search_condition: queryset = self.filtering(queryset, pre_search_condition) else: queryset = queryset.all() # number of the total records total = queryset.count() # if the query dict not empty, then apply the query dict if query_dict: queryset = self.filtering(queryset, query_dict) # number of the records after applying the query count = queryset.count() # order the queryset queryset = queryset.order_by(order_key) # slice the queryset queryset = self.slicing(queryset, **kwargs) return {'items': queryset, 'count': count, 'total': total, 'draw': draw} def process(self, pre_search_condition=None, **kwargs): """ function to be called outside to get the footer search condition, apply the search in DB and render the serialized result. :param pre_search_condition: None/OrderedDict: pre search condition to be applied before applying the one getting from footer :param kwargs: dict: search parameters got from footer :return: dict: contains the filtered data, total number of records, number of filtered records and drawing number. """ records = self.query_by_args(pre_search_condition=pre_search_condition, **kwargs) serializer = self.serializer(records['items'], many=True) result = { 'data': serializer.data, 'draw': records['draw'], 'recordsTotal': records['total'], 'recordsFiltered': records['count'], } return result
class DataTables(metaclass=DataTablesMeta): ''' This class aims to simplify the process of using datatables's serverside option in a django project. It defines a similar structure like django ModelForm, using Meta class. Inside the Meta class, the user has to define couple things: * serializer: a ModelSerializer class (using rest_framework package) * form: a normal django from, which defines the choice fields for the footer. An abstract dynamical form is provided in forms.py file. * structure: list of dict, defines the table structure in frontend * structure_for_superuser: same as above, but for superuser * mapping: TripleEnum class, which holds the mapping between column number in frontend, corresponding field name in model class and corresponding key for filtering in DB Besides the Meta class, the functions, 'get_query_dict', 'query_by_args', can be customized by the user according to some specific use cases. The other functions are not necessary to be overridden. ''' def footer_form(self, *args, **kwargs): ''' wrapper to render an instance of the footer form, which is the form in Meta class :param args: list: args for the footer form initialization :param kwargs: dict: args for the footer form initialization :return: form instance ''' pass def get_table_frame(self, prefix="", table_id="sspdtable", *args, **kwargs): ''' render the structure (or structure_for_superuser) and an instance of the footer form :param prefix: str: used for unifying the rendered parameter's name, such that the template of serverside datatables can be used in one page multiple times :param table_id: str: :param args: list: args for the footer form initialization :param kwargs: dict: args for the footer form initialization :return: dict ''' pass def get_query_dict(self, **kwargs): ''' function to generate a filter dictionary, in which the key is the keyword used in django filter function in string form, and the value is the searched value. :param kwargs:dict: query dict sent by data tables package :return: dict: filtering dictionary ''' pass def get_order_key(self, **kwargs): ''' function to get the order key to apply it in the filtered queryset :param kwargs: dict: query dict sent by data tables package :return: str: order key, which can be used directly in queryset's order_by function ''' pass @staticmethod def filtering(queryset, query_dict): ''' function to apply the pre search condition to the queryset to narrow down the queryset's size :param queryset: Django Queryset: queryset of all objects :param query_dict: dict: contains selected_related, filter and other customized filter functions :return: queryset: result after applying the pre search condition dict ''' pass @staticmethod def slicing(queryset, **kwargs): ''' function to slice the queryset according to the display length :param queryset: Django Queryset: filtered and ordered queryset result :param kwargs: dict: query dict sent by data tables package :return: queryset: result after slicing ''' pass def query_by_args(self, pre_search_condition=None, **kwargs): ''' intends to process the queries sent by data tables package in frontend. The model_cls indicates the model class, get_query_dict is a function implemented by you, such that it can return a query dictionary, in which the key is the query keyword in str form and the value is the queried value :param pre_search_condition: None/OrderedDict: dictionary contains filter conditions which should be processed before applying the filter dictionary from user. None, if no pre_search_condition provided. :param kwargs: QueryDict: contains query parameters :return: dict: contains total records number, queryset of the filtered instances, size of this queryset ''' pass def process(self, pre_search_condition=None, **kwargs): ''' function to be called outside to get the footer search condition, apply the search in DB and render the serialized result. :param pre_search_condition: None/OrderedDict: pre search condition to be applied before applying the one getting from footer :param kwargs: dict: search parameters got from footer :return: dict: contains the filtered data, total number of records, number of filtered records and drawing number. ''' pass
11
9
25
2
12
11
3
1.06
1
9
0
1
6
0
8
22
239
29
102
44
91
108
81
42
72
6
3
2
23
142,782
KnightConan/sspdatatables
KnightConan_sspdatatables/src/sspdatatables/datatables.py
sspdatatables.datatables.DataTablesMeta
class DataTablesMeta(type): """ Simple meta class to check if a subclass of DataTables defines a nested Meta class and inside the Meta class the variables: 'serializer', 'frame', 'mapping' (perhaps 'form') are defined as desired data type. """ def __new__(mcs, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: """ Used for defining the Meta class's structure and check it when creating a subclass's instance, such that the user will be forced to follow the rules as following: 1. serializer: must be defined as a subclass of ModelSerializer 2. structure: must be defined as a list of dict, it should look like: [ { "header": "<Header to display>", "searchable": <bool value to set the columns to be searchable or not, True/False>, "orderable": <bool value to set the columns to be orderable or not, True/False>, "footer_type": type of the footer search bar, input/select, "id": "<id of this footer search bar, together with parameter 'prefix' to build the id>", "serializer_key": "<key to extract the data from the serialized data set>" } ] 3. structure_for_superuser: same as above 4. form: must be defined if there is at least one footer whose type is not 'input' 5. mapping: must be defined as the following structure: class COL_TRIPLE_ENUM(TripleEnum): A = ("<number of the column in frontend>", "<correspinding field name>", "<corresponding filter key>") It's the key to get the correct data from DB :return: class instance """ cls = super().__new__(mcs, name, bases, namespace) # the class 'DataTables' doesn't need any further checks if not bases: return cls # each subclass of class 'DataTables' must define the Meta class if "Meta" not in namespace: raise AttributeError("Class Meta isn't defined.") _meta = getattr(cls, "Meta") # make sure the Meta is a nested class if not isinstance(_meta, type): raise AttributeError("Meta isn't defined as a nested class.") # checks the Meta class contains the definitions of variables: # serializer, frame, mapping meta_attrs = {"serializer", "frame", "mapping"} missing_attrs = meta_attrs.difference(_meta.__dict__.keys()) if missing_attrs: raise AttributeError("Variable(s) %r must be defined in Meta class." % list(missing_attrs)) # checks the variables are not None for attr_name in meta_attrs: if getattr(_meta, attr_name) is None: raise AttributeError( "Variable '%s' can not be None." % attr_name) # serializer should be a subclass of ModelSerializer from rest_framework serializer = getattr(_meta, "serializer") if not issubclass(serializer, ModelSerializer): raise TypeError( "Variable 'serializer' must be a subclass of ModelSerializer.") # frame should be a list of dictionaries and in each dictionary some # keys must be contained. frame = getattr(_meta, "frame") must_have_keys = {"id", "serializer_key", "header", "searchable", "orderable", "footer_type"} if not isinstance(frame, list): raise ValueError("Variable 'frame' must be a list of dictionaries.") elif not frame: raise ValueError("Variable 'frame' must not be empty.") for item in frame: if not isinstance(item, dict): raise ValueError("Variable 'frame' must be a list of " "dictionaries.") missing_keys = must_have_keys.difference(item.keys()) if missing_keys: raise ValueError("Keys %r are missing" % list(missing_keys)) # mapping must be a subclass of TripleEnum class mapping = getattr(_meta, "mapping") if not issubclass(mapping, TripleEnum): raise ValueError("Variable 'mapping' must inherit from class " "TripleEnum.") # form can be None, if the user doesn't user footer or uses input field # as footer. Otherwise, it must be defined as a subclass of # AbstractFooterForm if not hasattr(_meta, "form"): _meta.form = None if not _meta.form: for item in frame: if item.get("footer_type") not in {"input", None}: raise ValueError( "If you don't use 'input' as your table's footer type, " "please do not leave the form as None.") elif not issubclass(_meta.form, AbstractFooterForm): raise ValueError( "Variable 'form' must be defined as a subclass of " "AbstractFooterForm or None.") cls._meta = _meta return cls
class DataTablesMeta(type): ''' Simple meta class to check if a subclass of DataTables defines a nested Meta class and inside the Meta class the variables: 'serializer', 'frame', 'mapping' (perhaps 'form') are defined as desired data type. ''' def __new__(mcs, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ''' Used for defining the Meta class's structure and check it when creating a subclass's instance, such that the user will be forced to follow the rules as following: 1. serializer: must be defined as a subclass of ModelSerializer 2. structure: must be defined as a list of dict, it should look like: [ { "header": "<Header to display>", "searchable": <bool value to set the columns to be searchable or not, True/False>, "orderable": <bool value to set the columns to be orderable or not, True/False>, "footer_type": type of the footer search bar, input/select, "id": "<id of this footer search bar, together with parameter 'prefix' to build the id>", "serializer_key": "<key to extract the data from the serialized data set>" } ] 3. structure_for_superuser: same as above 4. form: must be defined if there is at least one footer whose type is not 'input' 5. mapping: must be defined as the following structure: class COL_TRIPLE_ENUM(TripleEnum): A = ("<number of the column in frontend>", "<correspinding field name>", "<corresponding filter key>") It's the key to get the correct data from DB :return: class instance ''' pass
2
2
106
8
55
43
19
0.88
1
10
2
1
1
0
1
14
113
8
56
14
53
49
43
13
41
19
2
3
19
142,783
KnightConan/sspdatatables
KnightConan_sspdatatables/src/sspdatatables/forms.py
sspdatatables.forms.AbstractFooterForm
class AbstractFooterForm(forms.Form): """ abstract django form, which can generate the ChoiceField dynamically. Aiming is to simplify the usage of the DataTables class and reducing the duplicate code (at least code with same structure). The only thing that the user to do is define the get choice function for all the choice fields, and the name of the get choice function should be in form of 'get_<field name>_choice>'. This class will automatically find the corresponding get choice function for each choice field. """ def __new__(cls, *args, **kwargs): """ used for checking the definition of the 'fields' variable in Meta class to make sure in the subclass it must be not None and its type is list of tuples. :param args: list: arguments in order :param kwargs:: dict : keyword arguments :return: an instance """ assert (isinstance(cls.Meta.fields, list) and len(cls.Meta.fields) and all(isinstance(n, tuple) for n in cls.Meta.fields)), "'fields' must be a non-empty list of tuples." return super(AbstractFooterForm, cls).__new__(cls) def __init__(self, *args, **kwargs): """ dynamically defining the ChoiceFields according to the value of 'fields' in Meta class :param args: list: arguments in order :param kwargs:: dict : keyword arguments """ super(AbstractFooterForm, self).__init__(*args, **kwargs) for field_name, field_type in self.Meta.fields: self.fields[field_name] = field_type(required=False, choices=getattr(self, 'get_'+field_name+'_choices')) class Meta: """ :param fields: list of tuples: the form should be: [("<field_name>", <forms.ChoiceField or forms.MultiChoiceField>), ] """ fields = None
class AbstractFooterForm(forms.Form): ''' abstract django form, which can generate the ChoiceField dynamically. Aiming is to simplify the usage of the DataTables class and reducing the duplicate code (at least code with same structure). The only thing that the user to do is define the get choice function for all the choice fields, and the name of the get choice function should be in form of 'get_<field name>_choice>'. This class will automatically find the corresponding get choice function for each choice field. ''' def __new__(cls, *args, **kwargs): ''' used for checking the definition of the 'fields' variable in Meta class to make sure in the subclass it must be not None and its type is list of tuples. :param args: list: arguments in order :param kwargs:: dict : keyword arguments :return: an instance ''' pass def __init__(self, *args, **kwargs): ''' dynamically defining the ChoiceFields according to the value of 'fields' in Meta class :param args: list: arguments in order :param kwargs:: dict : keyword arguments ''' pass class Meta: ''' :param fields: list of tuples: the form should be: [("<field_name>", <forms.ChoiceField or forms.MultiChoiceField>), ] '''
4
4
12
1
4
7
2
2.55
1
4
1
1
2
0
2
2
44
5
11
6
7
28
10
6
6
2
1
1
3
142,784
KnightConan/sspdatatables
KnightConan_sspdatatables/src/sspdatatables/utils/enum.py
sspdatatables.utils.enum.ExtendedEnum
class ExtendedEnum(Enum, metaclass=ExtendedEnumMeta): """ This class was thought to work as an abstract class to simplify the definition of the enumeration classes with more than 1 attributes. """ def __init__(self, *args, **kwargs) -> None: """ Intends to assign the given values to attributes according to the order. :param args: list: values of the attributes of the enumeration item :param kwargs: dict: it should be empty """ if len(kwargs): raise ValueError("The initialization of enumeration doesn't accept " "key word arguments") attr_names = self.attr_names() if len(args) != len(attr_names): raise ValueError("The number of given values doesn't match the " "number of defined attributes") for i, attr_name in enumerate(attr_names): setattr(self, attr_name, args[i]) @classmethod def attr_names(cls) -> List[str]: """ class method for defining the names of the attributes, it's used in two places: 1. in the initial function of the class 'ExtendedEnum', the attributes will be set 2. the meta class's __new__function to generate the corresponding functions for each attribute. :return: list of list of attribute names """ return list() @classmethod def tuples(cls) -> Tuple[Tuple[Any, ...]]: """ Returns a tuple formed by attributes for all the elements inside the class :return: tuple of n-elements-tuples """ return tuple(cls._value2member_map_.keys()) def __str__(self) -> str: """ String representation of the given enumeration. By default it returns the string conversion of the first attribute from the attr_names associated to a value :return: str """ return str(getattr(self, self.attr_names()[0])) @classmethod def describe(cls) -> None: """ Prints in the console a table showing all the attributes for all the definitions inside the class :return: None """ max_lengths = [] for attr_name in cls.attr_names(): attr_func = "%ss" % attr_name attr_list = list(map(str, getattr(cls, attr_func)())) + [attr_name] max_lengths.append(max(list(map(len, attr_list)))) row_format = "{:>%d} | {:>%d} | {:>%d}" % tuple(max_lengths) headers = [attr_name.capitalize() for attr_name in cls.attr_names()] header_line = row_format.format(*headers) output = "Class: %s\n" % cls.__name__ output += header_line + "\n" output += "-"*(len(header_line)) + "\n" for item in cls: format_list = [str(getattr(item, attr_name)) for attr_name in cls.attr_names()] output += row_format.format(*format_list) + "\n" print(output)
class ExtendedEnum(Enum, metaclass=ExtendedEnumMeta): ''' This class was thought to work as an abstract class to simplify the definition of the enumeration classes with more than 1 attributes. ''' def __init__(self, *args, **kwargs) -> None: ''' Intends to assign the given values to attributes according to the order. :param args: list: values of the attributes of the enumeration item :param kwargs: dict: it should be empty ''' pass @classmethod def attr_names(cls) -> List[str]: ''' class method for defining the names of the attributes, it's used in two places: 1. in the initial function of the class 'ExtendedEnum', the attributes will be set 2. the meta class's __new__function to generate the corresponding functions for each attribute. :return: list of list of attribute names ''' pass @classmethod def tuples(cls) -> Tuple[Tuple[Any, ...]]: ''' Returns a tuple formed by attributes for all the elements inside the class :return: tuple of n-elements-tuples ''' pass def __str__(self) -> str: ''' String representation of the given enumeration. By default it returns the string conversion of the first attribute from the attr_names associated to a value :return: str ''' pass @classmethod def describe(cls) -> None: ''' Prints in the console a table showing all the attributes for all the definitions inside the class :return: None ''' pass
9
6
14
1
7
6
2
0.92
2
7
0
1
2
0
5
57
80
9
37
21
28
34
31
18
25
4
4
1
10
142,785
KnightConan/sspdatatables
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KnightConan_sspdatatables/src/sspdatatables/forms.py
sspdatatables.forms.AbstractFooterForm.Meta
class Meta: """ :param fields: list of tuples: the form should be: [("<field_name>", <forms.ChoiceField or forms.MultiChoiceField>), ] """ fields = None
class Meta: ''' :param fields: list of tuples: the form should be: [("<field_name>", <forms.ChoiceField or forms.MultiChoiceField>), ] ''' pass
1
1
0
0
0
0
0
2
0
0
0
0
0
0
0
0
6
0
2
2
1
4
2
2
1
0
0
0
0
142,786
KnightConan/sspdatatables
KnightConan_sspdatatables/example/example/models.py
example.models.Book
class Book(models.Model): name = models.CharField(max_length=60) description = models.TextField() author = models.ForeignKey(Author, on_delete=CASCADE) published_at = models.DateField(auto_now=True)
class Book(models.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
0
5
5
4
0
5
5
4
0
1
0
0
142,787
KnightConan/sspdatatables
KnightConan_sspdatatables/example/example/datatables/enums.py
example.datatables.enums.BookEnum
class BookEnum(TripleEnum): """ class to define a mapping """ ID = (1, "id", "id") NAME = (2, "name", "name__icontains") AUTHOR_NAME = (3, "author__name", "author__name__icontains") AUTHOR_NATIONALITY = (4, "author__nationality", "author__nationality") PUBLISHED_AT = (5, "published_at", "published_at")
class BookEnum(TripleEnum): ''' class to define a mapping '''
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
58
9
0
6
6
5
3
6
6
5
0
6
0
0
142,788
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.Story
class Story(object): """ Object to model a story. """ story_id = 0 story_type = '' user = None updated_at = '' self_post = False poster = None media = None substories_count = 0 substories = [] def __init__(self, story_dict): """ story_dict: a dictionary with the elements of a user object. Instalises the class and assigns all the elements to internal objects. """ self.story_id = story_dict['id'] self.user = MiniUser(story_dict['user']) self.updated_at = story_dict['updated_at'] self.story_type = story_dict['story_type'] if self.story_type == 'comment': self.self_post = story_dict['self_post'] self.poster = MiniUser(story_dict['poster']) elif self.story_type == 'media_story': self.media = Anime(story_dict['media']) self.substories_count = story_dict['substories_count'] for item in range(story_dict['substories_count']): self.substories.append(Substory(story_dict['substories'][item]))
class Story(object): ''' Object to model a story. ''' def __init__(self, story_dict): ''' story_dict: a dictionary with the elements of a user object. Instalises the class and assigns all the elements to internal objects. ''' pass
2
2
19
2
13
4
4
0.3
1
4
3
0
1
0
1
1
34
4
23
12
21
7
22
12
20
4
1
1
4
142,789
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.Substory
class Substory(object): """ Object to model a substory. """ substory_id = 0 substory_type = '' created_at = '' comment = '' episode_number = 0 followed_user = None new_status = '' #service = None #Should be ignored as per API permissions = {} def __init__(self, story_dict): """ story_dict: a dictionary with the elements of a substory object. Instalises the class and assigns all the elements to internal objects. """ self.substory_id = story_dict['id'] self.substory_type = story_dict['substory_type'] if self.substory_type == 'comment': self.comment = story_dict['comment'] elif self.substory_type == 'watched_episode': self.episode_number = story_dict['episode_number'] elif self.substory_type == 'watchlist_status_update': #self.service = story_dict['service'] self.new_status = story_dict['new_status'] elif self.substory_type == 'followed': self.followed_user = MiniUser(story_dict['followed_user']) self.created_at = story_dict['created_at']
class Substory(object): ''' Object to model a substory. ''' def __init__(self, story_dict): ''' story_dict: a dictionary with the elements of a substory object. Instalises the class and assigns all the elements to internal objects. ''' pass
2
2
19
2
12
5
5
0.43
1
1
1
0
1
0
1
1
34
4
21
10
19
9
18
10
16
5
1
1
5
142,790
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.LibraryEntry
class LibraryEntry(object): """ Object to model a library entry. """ entry_id = 0 episodes_watched = 0 last_watched = '' rewatched_times = 0 notes = '' notes_present = False status = '' private = False rewatching = False anime = None rating = None def __init__(self, entry_dict): """ entry_dict: A dictionary witht he elements of a library entry struct Init the class and assigns all the elements to internal objects. notes_present determines if notes is empty or not, you can check by seeing if notes is '' also. """ self.entry_id = entry_dict['id'] self.episodes_watched = entry_dict['episodes_watched'] # The date in ISO 8601 format. self.last_watched = entry_dict['last_watched'] self.rewatched_times = entry_dict['rewatched_times'] self.notes_present = entry_dict['notes_present'] if self.notes_present is True: self.notes = entry_dict['notes'] self.status = entry_dict['status'] self.private = entry_dict['private'] self.rewatching = entry_dict['rewatching'] self.anime = Anime(entry_dict['anime']) self.rating = LibraryEntryRating(entry_dict['rating'])
class LibraryEntry(object): ''' Object to model a library entry. ''' def __init__(self, entry_dict): ''' entry_dict: A dictionary witht he elements of a library entry struct Init the class and assigns all the elements to internal objects. notes_present determines if notes is empty or not, you can check by seeing if notes is '' also. ''' pass
2
2
22
2
13
7
2
0.4
1
2
2
0
1
0
1
1
39
4
25
13
23
10
25
13
23
2
1
1
2
142,791
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.Favorite
class Favorite(object): """ Object to model a favorite anime. """ # Okay, HB's docs are wrong. This is not fun anymore. anime_id = 0 fav_id = 0 #user_id = 0 #item_id = 0 #item_type = '' #created_at = '' #updated_at = '' fav_rank = 0 # Should be ignored, as per API Docs def __init__(self, fav_dict): """ fav_dict: a dictionary with the elements of a favorite object. Instalises the class and assigns all the elements to internal objects. """ self.anime_id = fav_dict['id'] self.fav_id = fav_dict['fav_id'] #self.user_id = fav_dict['user_id'] #self.item_id = fav_dict['item_id'] #self.item_type = fav_dict['item_type'] #self.created_at = fav_dict['created_at'] #self.updated_at = fav_dict['updated_at'] self.fav_rank = fav_dict['fav_rank']
class Favorite(object): ''' Object to model a favorite anime. ''' def __init__(self, fav_dict): ''' fav_dict: a dictionary with the elements of a favorite object. Instalises the class and assigns all the elements to internal objects. ''' pass
2
2
14
1
4
10
1
2.5
1
0
0
0
1
0
1
1
29
3
8
5
6
20
8
5
6
1
1
0
1
142,792
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.Anime
class Anime(object): """ Object to model the anime structure. """ anime_id = 0 mal_id = 0 slug = '' status = '' url = '' title = '' alternate_title = '' cover_image = '' episode_count = 0 episode_length = 0 cover_image = '' synopsis = '' show_type = '' community_rating = 0 age_rating = '' started_airing = '' finished_airing = '' genres = [] def __init__(self, anime_dict): """ anime_dict: a dict with all the elements of the anime object struct Instalises the class and assigns all the elements to internal objects. genres is optional and defaults to an empty list. """ self.anime_id = anime_dict['id'] self.mal_id = anime_dict['mal_id'] self.slug = anime_dict['slug'] self.status = anime_dict['status'] self.url = anime_dict['url'] self.title = anime_dict['title'] self.alternate_title = anime_dict['alternate_title'] self.episode_count = anime_dict['episode_count'] self.episode_length = anime_dict['episode_length'] self.cover_image = anime_dict['cover_image'] self.synopsis = anime_dict['synopsis'] self.show_type = anime_dict['show_type'] self.community_rating = anime_dict['community_rating'] self.age_rating = anime_dict['age_rating'] self.started_airing = anime_dict['started_airing'] self.finished_airing = anime_dict['finished_airing'] try: self.genres = anime_dict['genres'] except KeyError: self.genres = []
class Anime(object): ''' Object to model the anime structure. ''' def __init__(self, anime_dict): ''' anime_dict: a dict with all the elements of the anime object struct Instalises the class and assigns all the elements to internal objects. genres is optional and defaults to an empty list. ''' pass
2
2
29
3
21
5
2
0.2
1
1
0
0
1
0
1
1
53
5
40
19
38
8
40
19
38
2
1
1
2
142,793
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/__init__.py
hummingbird.Hummingbird
class Hummingbird(object): """Object for the wrapper for the Hummingbird API v1""" headers = {'content-type': 'application/json'} auth_token = '' api_url = "http://hummingbird.me/api/v1" def __init__(self, username, password): """Sets up the API, tests if your auth is valid. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: None :raises: ValueError -- If the Authentication is wrong """ self.auth_token = self.authenticate(username, password) def _query_(self, path, method, params={}): """Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: Requests object -- Requires you to handle the status codes yourself. """ if method == "POST": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.post(url, data=json.dumps(params), headers=self.headers) return r elif method == "GET": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.get(url, params=params, headers=self.headers) return r def authenticate(self, username, password): """Authenticates your user and returns an auth token. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: str -- The Auth Token :raises: ValueError -- If the Authentication is wrong """ r = self._query_('/users/authenticate', 'POST', params={'username': username, 'password': password}) if r.status_code == 201: return r.text.strip('"') else: raise ValueError('Authentication invalid.') def get_anime(self, anime_id, title_language='canonical'): """Fetches the Anime Object of the given id or slug. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str title_language: The PREFERED title language can be any of `'canonical'`, `'english'`, `'romanized'` :returns: Anime Object -- The Anime you requested. """ r = self._query_('/anime/%s' % anime_id, 'GET', params={'title_language_preference': title_language}) return Anime(r.json()) def search_anime(self, query): """Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty. """ r = self._query_('/search/anime', 'GET', params={'query': query}) results = [Anime(item) for item in r.json()] return results def get_library(self, username, status=None): """Fetches a users library. :param str username: The user to get the library from. :param str status: only return the items with the supplied status. Can be one of `currently-watching`, `plan-to-watch`, `completed`, `on-hold` or `dropped`. :returns: List of Library objects. """ r = self._query_('/users/%s/library' % username, 'GET', params={'status': status}) results = [LibraryEntry(item) for item in r.json()] return results def get_user(self, username): """Get user information. :param str username: User to get info on. """ r = self._query_('/users/%s' % username, 'GET') result = User(r.json()) return result def get_feed(self, username): """Gets a user's feed. :param str username: User to fetch feed from. """ r = self._query_('/users/%s/feed' % username, 'GET') results = [Story(item) for item in r.json()] return results def get_favorites(self, username): """Get a user's favorite anime. :param str username: User to get favorites from. """ r = self._query_('/users/%s/favorite_anime' % username, 'GET') results = [Favorite(item) for item in r.json()] return results def update_entry(self, anime_id, status=None, privacy=None, rating=None, sane_rating_update=None, rewatched_times=None, notes=None, episodes_watched=None, increment_episodes=None): """Creates or updates the Library entry with the provided values. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str auth_token: User authentication token. :param str status: Can be one of `'currently-watching'`, `'plan-to-watch'`, `'completed'`, `'on-hold'`, `'dropped'`. :param str privacy: Can be one of `'public'`, `'private'`. Making an entry private will hide it from public view. :param rating: Can be one of `0`, `0.5`, `1`, `1.5`, `2`, `2.5`, `3`, `3.5`, `4`, `4.5`, `5`. Setting it to the current value or 0 will remove the rating. :type rating: str, int or float :param sane_rating_update: Can be any one of the values for rating. Setting it to 0 will remove the rating. This should be used instead of rating if you don't want to unset the rating when setting it to its current value. :type sane_rating_update: str, int or float :param int rewatched_times: Number of rewatches. Can be 0 or above. :param str notes: The personal notes for the entry. :param int episodes_watched: Number of watched episodes. Can be between 0 and the total number of episodes. If equal to total number of episodes, status should be set to completed. :param bool increment_episodes: If set to true, increments watched episodes by one. If used along with episodes_watched, provided value will be incremented. :raises: ValueError -- if Authentication Token is invalid (it shouldn't be), or if there is a `500 Internal Server Error` or if the response is `Invalid JSON Object`. """ r = self._query_('/libraries/%s' % anime_id, 'POST', { 'auth_token': self.auth_token, 'status': status, 'privacy': privacy, 'rating': rating, 'sane_rating_update': sane_rating_update, 'rewatched_times': rewatched_times, 'notes': notes, 'episodes_watched': episodes_watched, 'increment_episodes': increment_episodes}) if not (r.status_code == 200 or r.status_code == 201): raise ValueError def remove_entry(self, anime_id): """Removes an entry from the user's library. :param anime_id: The Anime ID or slug. """ r = self._query_('libraries/%s/remove' % anime_id, 'POST') if not r.status_code == 200: raise ValueError
class Hummingbird(object): '''Object for the wrapper for the Hummingbird API v1''' def __init__(self, username, password): '''Sets up the API, tests if your auth is valid. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: None :raises: ValueError -- If the Authentication is wrong ''' pass def _query_(self, path, method, params={}): '''Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: Requests object -- Requires you to handle the status codes yourself. ''' pass def authenticate(self, username, password): '''Authenticates your user and returns an auth token. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: str -- The Auth Token :raises: ValueError -- If the Authentication is wrong ''' pass def get_anime(self, anime_id, title_language='canonical'): '''Fetches the Anime Object of the given id or slug. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str title_language: The PREFERED title language can be any of `'canonical'`, `'english'`, `'romanized'` :returns: Anime Object -- The Anime you requested. ''' pass def search_anime(self, query): '''Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty. ''' pass def get_library(self, username, status=None): '''Fetches a users library. :param str username: The user to get the library from. :param str status: only return the items with the supplied status. Can be one of `currently-watching`, `plan-to-watch`, `completed`, `on-hold` or `dropped`. :returns: List of Library objects. ''' pass def get_user(self, username): '''Get user information. :param str username: User to get info on. ''' pass def get_feed(self, username): '''Gets a user's feed. :param str username: User to fetch feed from. ''' pass def get_favorites(self, username): '''Get a user's favorite anime. :param str username: User to get favorites from. ''' pass def update_entry(self, anime_id, status=None, privacy=None, rating=None, sane_rating_update=None, rewatched_times=None, notes=None, episodes_watched=None, increment_episodes=None): '''Creates or updates the Library entry with the provided values. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str auth_token: User authentication token. :param str status: Can be one of `'currently-watching'`, `'plan-to-watch'`, `'completed'`, `'on-hold'`, `'dropped'`. :param str privacy: Can be one of `'public'`, `'private'`. Making an entry private will hide it from public view. :param rating: Can be one of `0`, `0.5`, `1`, `1.5`, `2`, `2.5`, `3`, `3.5`, `4`, `4.5`, `5`. Setting it to the current value or 0 will remove the rating. :type rating: str, int or float :param sane_rating_update: Can be any one of the values for rating. Setting it to 0 will remove the rating. This should be used instead of rating if you don't want to unset the rating when setting it to its current value. :type sane_rating_update: str, int or float :param int rewatched_times: Number of rewatches. Can be 0 or above. :param str notes: The personal notes for the entry. :param int episodes_watched: Number of watched episodes. Can be between 0 and the total number of episodes. If equal to total number of episodes, status should be set to completed. :param bool increment_episodes: If set to true, increments watched episodes by one. If used along with episodes_watched, provided value will be incremented. :raises: ValueError -- if Authentication Token is invalid (it shouldn't be), or if there is a `500 Internal Server Error` or if the response is `Invalid JSON Object`. ''' pass def remove_entry(self, anime_id): '''Removes an entry from the user's library. :param anime_id: The Anime ID or slug. ''' pass
12
12
16
3
6
7
1
1.14
1
6
5
0
11
0
11
11
198
46
71
33
57
81
50
31
38
3
1
1
16
142,794
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.LibraryEntryRating
class LibraryEntryRating(object): """ Object to model a library entry rating. """ rating_type = '' value = '' def __init__(self, rating_dict): """ rating_dict: a dictionary with the elements of a rating object. Instalises the class and assigns all the elements to internal objects. Rating type determines if value is an int. """ self.rating_type = rating_dict['type'] self.value = rating_dict['value']
class LibraryEntryRating(object): ''' Object to model a library entry rating. ''' def __init__(self, rating_dict): ''' rating_dict: a dictionary with the elements of a rating object. Instalises the class and assigns all the elements to internal objects. Rating type determines if value is an int. ''' pass
2
2
10
2
3
5
1
1.33
1
0
0
0
1
0
1
1
18
4
6
4
4
8
6
4
4
1
1
0
1
142,795
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.MiniUser
class MiniUser(object): """ Object to model a user. """ name = '' url = '' avatar = '' avatar_small = '' nb = False def __init__(self, user_dict): """ user_dict: a dictionary with the elements of a user object. Instalises the class and assigns all the elements to internal objects. """ self.name = user_dict['name'] self.url = user_dict['url'] self.avatar = user_dict['avatar'] self.avatar_small = user_dict['avatar_small'] self.nb = user_dict['nb']
class MiniUser(object): ''' Object to model a user. ''' def __init__(self, user_dict): ''' user_dict: a dictionary with the elements of a user object. Instalises the class and assigns all the elements to internal objects. ''' pass
2
2
11
1
6
4
1
0.58
1
0
0
0
1
0
1
1
22
3
12
7
10
7
12
7
10
1
1
0
1
142,796
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/tests/__init__.py
hummingbird.tests.HummingbirdTest
class HummingbirdTest(unittest.TestCase, object): def setUp(self): self.un = 'HummingbirdpyTest' # Security through obscurity. Do you really want to get into my test # Account? self.un_pswd = str(8) * 8 self.api = hummingbird.Hummingbird(self.un, self.un_pswd) def test_get_anime_function(self): """ Test if fetching an anime object works """ anime = self.api.get_anime('neon-genesis-evangelion') self.assertEqual(anime.title, 'Neon Genesis Evangelion') def test_title_language_get_anime_function(self): """ Test if setting the prefered language works """ anime = self.api.get_anime('neon-genesis-evangelion', title_language='romanized') self.assertEqual(anime.title, 'Shinseiki Evangelion') def test_search_anime_function(self): """ Test if searching for anime works well. """ search = self.api.search_anime('evangelion') for item in search: self.assertIn(item.title, ['Petit Eva: Evangelion@School', 'Neon Genesis Evangelion', 'Neon Genesis Evangelion: The End of Evangelion', 'Evangelion: 1.0 You Are (Not) Alone', 'Evangelion: 2.0 You Can (Not) Advance', 'Evangelion: 3.0 You Can (Not) Redo ', 'Neon Genesis Evangelion: Death & Rebirth', 'Schick x Evangelion', 'Evangelion x JRA', 'Evangelion: 3.0+1.0']) def test_get_library(self): """ Test if getting a users library works """ library = self.api.get_library(self.un) for item in library: print(item.anime.title) def test_get_user(self): """ Test if getting user info works """ user = self.api.get_user('covabishop') # Shameless self-promotion print(user.waifu) def test_get_feed(self): """ Tests getting user feed """ feed = self.api.get_feed(self.un) for item in feed: print(item.story_id) def test_get_favorites(self): """ Tests getting user favorites. """ favs = self.api.get_favorites('covabishop') for fav in favs: current = self.api.get_anime(fav.anime_id) print(current.title)
class HummingbirdTest(unittest.TestCase, object): def setUp(self): pass def test_get_anime_function(self): ''' Test if fetching an anime object works ''' pass def test_title_language_get_anime_function(self): ''' Test if setting the prefered language works ''' pass def test_search_anime_function(self): ''' Test if searching for anime works well. ''' pass def test_get_library(self): ''' Test if getting a users library works ''' pass def test_get_user(self): ''' Test if getting user info works ''' pass def test_get_feed(self): ''' Tests getting user feed ''' pass def test_get_favorites(self): ''' Tests getting user favorites. ''' pass
9
7
6
0
5
1
2
0.24
2
2
1
0
8
3
8
80
57
7
41
24
32
10
31
24
22
2
2
1
12
142,797
KnightHawk3/Hummingbird
KnightHawk3_Hummingbird/hummingbird/objects.py
hummingbird.objects.User
class User(object): """ Object to model a user. """ # Favorites ommitted due to poor integration and conflicting response for # favorties when getting via get_user() and get_favorites(). Besides, no # need to duplicate getting favorites. Either get them or don't, or use # get_favorites() to populate it. name = '' waifu = '' waifu_or_husbando = '' waifu_slug = '' waifu_char_id = '' location = '' website = '' avatar = '' cover_image = '' about = '' bio = '' karma = '' life_spent_on_anime = '' show_adult_content = False title_language_preference = '' last_library_update = '' online = False following = '' #favorites = [] def __init__(self, user_dict): """ user_dict: a dictionary with the elements of a user object. Instalises the class and assigns all the elements to internal objects. """ self.name = user_dict['name'] self.waifu = user_dict['waifu'] self.waifu_or_husbando = user_dict['waifu_or_husbando'] self.waifu_slug = user_dict['waifu_slug'] self.waifu_char_id = user_dict['waifu_char_id'] self.location = user_dict['location'] self.website = user_dict['website'] self.avatar = user_dict['avatar'] self.cover_image = user_dict['cover_image'] self.about = user_dict['about'] self.bio = user_dict['bio'] self.karma = user_dict['karma'] self.life_spent_on_anime = user_dict['life_spent_on_anime'] self.show_adult_content = user_dict['show_adult_content'] self.title_language_preference = user_dict['title_language_preference'] self.last_library_update = user_dict['last_library_update'] self.following = user_dict['following']
class User(object): ''' Object to model a user. ''' def __init__(self, user_dict): ''' user_dict: a dictionary with the elements of a user object. Instalises the class and assigns all the elements to internal objects. ''' pass
2
2
23
1
18
4
1
0.32
1
0
0
0
1
0
1
1
52
3
37
20
35
12
37
20
35
1
1
0
1
142,798
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.h1
class h1(html_tag): ''' Represents the highest ranking heading. ''' pass
class h1(html_tag): ''' Represents the highest ranking heading. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,799
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.form
class form(html_tag): ''' The form element represents a collection of form-associated elements, some of which can represent editable values that can be submitted to a server for processing. ''' pass
class form(html_tag): ''' The form element represents a collection of form-associated elements, some of which can represent editable values that can be submitted to a server for processing. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
31
7
0
2
1
1
5
2
1
1
0
3
0
0
142,800
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.footer
class footer(html_tag): ''' The footer element represents a footer for its nearest ancestor sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like. ''' pass
class footer(html_tag): ''' The footer element represents a footer for its nearest ancestor sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like. ''' pass
1
1
0
0
0
0
0
3
1
0
0
0
0
0
0
31
8
0
2
1
1
6
2
1
1
0
3
0
0
142,801
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.font
class font(html_tag): ''' The font element represents the font in a html . ''' pass
class font(html_tag): ''' The font element represents the font in a html . ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,802
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.h2
class h2(html_tag): ''' Represents the second-highest ranking heading. ''' pass
class h2(html_tag): ''' Represents the second-highest ranking heading. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,803
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.h3
class h3(html_tag): ''' Represents the third-highest ranking heading. ''' pass
class h3(html_tag): ''' Represents the third-highest ranking heading. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,804
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.h4
class h4(html_tag): ''' Represents the fourth-highest ranking heading. ''' pass
class h4(html_tag): ''' Represents the fourth-highest ranking heading. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,805
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.figure
class figure(html_tag): ''' The figure element represents some flow content, optionally with a caption, that is self-contained and is typically referenced as a single unit from the main flow of the document. ''' pass
class figure(html_tag): ''' The figure element represents some flow content, optionally with a caption, that is self-contained and is typically referenced as a single unit from the main flow of the document. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
31
7
0
2
1
1
5
2
1
1
0
3
0
0
142,806
Knio/dominate
Knio_dominate/dominate/document.py
dominate.document.document
class document(tags.html): tagname = 'html' def __init__(self, title='Dominate', doctype='<!DOCTYPE html>', *a, **kw): ''' Creates a new document instance. Accepts `title` and `doctype` ''' super(document, self).__init__(*a, **kw) self.doctype = doctype self.head = super(document, self).add(tags.head()) self.body = super(document, self).add(tags.body()) if title is not None: self.title_node = self.head.add(tags.title(title)) with self.body: self.header = util.container() self.main = util.container() self.footer = util.container() self._entry = self.main def get_title(self): return self.title_node.text def set_title(self, title): if isinstance(title, basestring): self.title_node.text = title else: self.head.remove(self.title_node) self.head.add(title) self.title_node = title title = property(get_title, set_title) def add(self, *args): ''' Adding tags to a document appends them to the <body>. ''' return self._entry.add(*args) def _render(self, sb, *args, **kwargs): ''' Renders the DOCTYPE and tag tree. ''' # adds the doctype if one was set if self.doctype: sb.append(self.doctype) sb.append('\n') return super(document, self)._render(sb, *args, **kwargs) def __repr__(self): return '<dominate.document "%s">' % self.title
class document(tags.html): def __init__(self, title='Dominate', doctype='<!DOCTYPE html>', *a, **kw): ''' Creates a new document instance. Accepts `title` and `doctype` ''' pass def get_title(self): pass def set_title(self, title): pass def add(self, *args): ''' Adding tags to a document appends them to the <body>. ''' pass def _render(self, sb, *args, **kwargs): ''' Renders the DOCTYPE and tag tree. ''' pass def __repr__(self): pass
7
3
7
0
5
2
2
0.3
1
5
4
0
6
8
6
37
49
6
33
17
26
10
32
17
25
2
4
1
9
142,807
Knio/dominate
Knio_dominate/dominate/dom1core.py
dominate.dom1core.dom1core
class dom1core(object): ''' Implements the Document Object Model (Core) Level 1 http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html ''' @property def parentNode(self): ''' DOM API: Returns the parent tag of the current element. ''' return self.parent def getElementById(self, id): ''' DOM API: Returns single element with matching id value. ''' results = self.get(id=id) if len(results) > 1: raise ValueError('Multiple tags with id "%s".' % id) elif results: return results[0] return None def getElementsByTagName(self, name): ''' DOM API: Returns all tags that match name. ''' if isinstance(name, basestring): return self.get(name.lower()) return None def appendChild(self, obj): ''' DOM API: Add an item to the end of the children list. ''' self.add(obj) return self
class dom1core(object): ''' Implements the Document Object Model (Core) Level 1 http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html ''' @property def parentNode(self): ''' DOM API: Returns the parent tag of the current element. ''' pass def getElementById(self, id): ''' DOM API: Returns single element with matching id value. ''' pass def getElementsByTagName(self, name): ''' DOM API: Returns all tags that match name. ''' pass def appendChild(self, obj): ''' DOM API: Add an item to the end of the children list. ''' pass
6
5
7
0
4
3
2
0.94
1
1
0
1
4
0
4
4
39
4
18
7
12
17
16
6
11
3
1
1
7
142,808
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.h5
class h5(html_tag): ''' Represents the fifth-highest ranking heading. ''' pass
class h5(html_tag): ''' Represents the fifth-highest ranking heading. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,809
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.h6
class h6(html_tag): ''' Represents the sixth-highest ranking heading. ''' pass
class h6(html_tag): ''' Represents the sixth-highest ranking heading. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,810
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.option
class option(html_tag): ''' The option element represents an option in a select element or as part of a list of suggestions in a datalist element. ''' pass
class option(html_tag): ''' The option element represents an option in a select element or as part of a list of suggestions in a datalist element. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
31
6
0
2
1
1
4
2
1
1
0
3
0
0
142,811
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.colgroup
class colgroup(html_tag): ''' The colgroup element represents a group of one or more columns in the table that is its parent, if it has a parent and that is a table element. ''' pass
class colgroup(html_tag): ''' The colgroup element represents a group of one or more columns in the table that is its parent, if it has a parent and that is a table element. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
31
6
0
2
1
1
4
2
1
1
0
3
0
0
142,812
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.animate
class animate(svg_tag): ''' The animate SVG element is used to animate an attribute or property of an element over time. It's normally inserted inside the element or referenced by the href attribute of the target element. ''' pass
class animate(svg_tag): ''' The animate SVG element is used to animate an attribute or property of an element over time. It's normally inserted inside the element or referenced by the href attribute of the target element. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
32
6
0
2
1
1
4
2
1
1
0
4
0
0
142,813
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feFlood
class feFlood(svg_tag): pass
class feFlood(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,814
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feDistantLight
class feDistantLight(svg_tag): pass
class feDistantLight(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,815
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feDisplacementMap
class feDisplacementMap(svg_tag): pass
class feDisplacementMap(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,816
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feDiffuseLighting
class feDiffuseLighting(svg_tag): pass
class feDiffuseLighting(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,817
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feConvolveMatrix
class feConvolveMatrix(svg_tag): pass
class feConvolveMatrix(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,818
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feComposite
class feComposite(svg_tag): pass
class feComposite(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,819
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feComponentTransfer
class feComponentTransfer(svg_tag): pass
class feComponentTransfer(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,820
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.head
class head(html_tag): ''' The head element represents a collection of metadata for the document. ''' pass
class head(html_tag): ''' The head element represents a collection of metadata for the document. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,821
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feColorMatrix
class feColorMatrix(svg_tag): pass
class feColorMatrix(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,822
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.ellipse
class ellipse(svg_tag): ''' An ellipse element for svg containers ''' pass
class ellipse(svg_tag): ''' An ellipse element for svg containers ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
32
5
0
2
1
1
3
2
1
1
0
4
0
0
142,823
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.desc
class desc(svg_tag): ''' The <desc> element provides an accessible, long-text description of any SVG container element or graphics element. ''' pass
class desc(svg_tag): ''' The <desc> element provides an accessible, long-text description of any SVG container element or graphics element. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
32
5
0
2
1
1
3
2
1
1
0
4
0
0
142,824
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.defs
class defs(svg_tag): ''' The <defs> element is used to store graphical objects that will be used at a later time. Objects created inside a <defs> element are not rendered directly. To display them you have to reference them (with a <use> element for example). ''' pass
class defs(svg_tag): ''' The <defs> element is used to store graphical objects that will be used at a later time. Objects created inside a <defs> element are not rendered directly. To display them you have to reference them (with a <use> element for example). '''
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
32
7
0
2
1
1
5
2
1
1
0
4
0
0
142,825
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.clipPath
class clipPath(svg_tag): ''' The <clipPath> SVG element defines a clipping path, to be used used by the clip-path property. ''' pass
class clipPath(svg_tag): ''' The <clipPath> SVG element defines a clipping path, to be used used by the clip-path property. '''
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
32
5
0
2
1
1
3
2
1
1
0
4
0
0
142,826
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.circle
class circle(svg_tag): ''' The <circle> SVG element is an SVG basic shape, used to draw circles based on a center point and a radius. ''' pass
class circle(svg_tag): ''' The <circle> SVG element is an SVG basic shape, used to draw circles based on a center point and a radius. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
32
5
0
2
1
1
3
2
1
1
0
4
0
0
142,827
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.animateTransform
class animateTransform(svg_tag): ''' The animateTransform element animates a transformation attribute on its target element, thereby allowing animations to control translation, scaling, rotation, and/or skewing. ''' is_single = True
class animateTransform(svg_tag): ''' The animateTransform element animates a transformation attribute on its target element, thereby allowing animations to control translation, scaling, rotation, and/or skewing. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
32
6
0
2
2
1
4
2
2
1
0
4
0
0
142,828
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.animateMotion
class animateMotion(svg_tag): ''' The <animateMotion> element causes a referenced element to move along a motion path. ''' pass
class animateMotion(svg_tag): ''' The <animateMotion> element causes a referenced element to move along a motion path. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
32
5
0
2
1
1
3
2
1
1
0
4
0
0
142,829
Knio/dominate
Knio_dominate/dominate/svg.py
dominate.svg.feBlend
class feBlend(svg_tag): pass
class feBlend(svg_tag): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
2
0
2
1
1
0
2
1
1
0
4
0
0
142,830
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.header
class header(html_tag): ''' The header element represents a group of introductory or navigational aids. ''' pass
class header(html_tag): ''' The header element represents a group of introductory or navigational aids. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,831
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.html_tag
class html_tag(dom_tag, dom1core): def __init__(self, *args, **kwargs): ''' Creates a new html tag instance. ''' super(html_tag, self).__init__(*args, **kwargs)
class html_tag(dom_tag, dom1core): def __init__(self, *args, **kwargs): ''' Creates a new html tag instance. ''' pass
2
1
5
0
2
3
1
1
2
1
0
112
1
0
1
31
6
0
3
2
1
3
3
2
1
1
2
0
1
142,832
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.hr
class hr(html_tag): ''' The hr element represents a paragraph-level thematic break, e.g. a scene change in a story, or a transition to another topic within a section of a reference book. ''' is_single = True
class hr(html_tag): ''' The hr element represents a paragraph-level thematic break, e.g. a scene change in a story, or a transition to another topic within a section of a reference book. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
31
7
0
2
2
1
5
2
2
1
0
3
0
0
142,833
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.object_
class object_(html_tag): ''' The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. ''' pass
class object_(html_tag): ''' The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
31
7
0
2
1
1
5
2
1
1
0
3
0
0
142,834
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.noscript
class noscript(html_tag): ''' The noscript element represents nothing if scripting is enabled, and represents its children if scripting is disabled. It is used to present different markup to user agents that support scripting and those that don't support scripting, by affecting how the document is parsed. ''' pass
class noscript(html_tag): ''' The noscript element represents nothing if scripting is enabled, and represents its children if scripting is disabled. It is used to present different markup to user agents that support scripting and those that don't support scripting, by affecting how the document is parsed. ''' pass
1
1
0
0
0
0
0
3
1
0
0
0
0
0
0
31
8
0
2
1
1
6
2
1
1
0
3
0
0
142,835
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.nav
class nav(html_tag): ''' The nav element represents a section of a page that links to other pages or to parts within the page: a section with navigation links. ''' pass
class nav(html_tag): ''' The nav element represents a section of a page that links to other pages or to parts within the page: a section with navigation links. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
31
6
0
2
1
1
4
2
1
1
0
3
0
0
142,836
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.meter
class meter(html_tag): ''' The meter element represents a scalar measurement within a known range, or a fractional value; for example disk usage, the relevance of a query result, or the fraction of a voting population to have selected a particular candidate. ''' pass
class meter(html_tag): ''' The meter element represents a scalar measurement within a known range, or a fractional value; for example disk usage, the relevance of a query result, or the fraction of a voting population to have selected a particular candidate. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
31
7
0
2
1
1
5
2
1
1
0
3
0
0
142,837
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.meta
class meta(html_tag): ''' The meta element represents various kinds of metadata that cannot be expressed using the title, base, link, style, and script elements. ''' is_single = True
class meta(html_tag): ''' The meta element represents various kinds of metadata that cannot be expressed using the title, base, link, style, and script elements. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
31
6
0
2
2
1
4
2
2
1
0
3
0
0
142,838
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.rp
class rp(html_tag): ''' The rp element can be used to provide parentheses around a ruby text component of a ruby annotation, to be shown by user agents that don't support ruby annotations. ''' pass
class rp(html_tag): ''' The rp element can be used to provide parentheses around a ruby text component of a ruby annotation, to be shown by user agents that don't support ruby annotations. ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
31
7
0
2
1
1
5
2
1
1
0
3
0
0
142,839
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.q
class q(html_tag): ''' The q element represents some phrasing content quoted from another source. ''' pass
class q(html_tag): ''' The q element represents some phrasing content quoted from another source. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,840
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.progress
class progress(html_tag): ''' The progress element represents the completion progress of a task. The progress is either indeterminate, indicating that progress is being made but that it is not clear how much more work remains to be done before the task is complete (e.g. because the task is waiting for a remote host to respond), or the progress is a number in the range zero to a maximum, giving the fraction of work that has so far been completed. ''' pass
class progress(html_tag): ''' The progress element represents the completion progress of a task. The progress is either indeterminate, indicating that progress is being made but that it is not clear how much more work remains to be done before the task is complete (e.g. because the task is waiting for a remote host to respond), or the progress is a number in the range zero to a maximum, giving the fraction of work that has so far been completed. ''' pass
1
1
0
0
0
0
0
4
1
0
0
0
0
0
0
31
10
0
2
1
1
8
2
1
1
0
3
0
0
142,841
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.pre
class pre(html_tag): ''' The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements. ''' is_pretty = False
class pre(html_tag): ''' The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
31
6
0
2
2
1
4
2
2
1
0
3
0
0
142,842
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.param
class param(html_tag): ''' The param element defines parameters for plugins invoked by object elements. It does not represent anything on its own. ''' is_single = True
class param(html_tag): ''' The param element defines parameters for plugins invoked by object elements. It does not represent anything on its own. '''
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
31
6
0
2
2
1
4
2
2
1
0
3
0
0
142,843
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.p
class p(html_tag): ''' The p element represents a paragraph. ''' pass
class p(html_tag): ''' The p element represents a paragraph. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,844
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.output
class output(html_tag): ''' The output element represents the result of a calculation. ''' pass
class output(html_tag): ''' The output element represents the result of a calculation. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,845
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.menu
class menu(html_tag): ''' The menu element represents a list of commands. ''' pass
class menu(html_tag): ''' The menu element represents a list of commands. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
31
5
0
2
1
1
3
2
1
1
0
3
0
0
142,846
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.mark
class mark(html_tag): ''' The mark element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a quotation or other block of text referred to from the prose, it indicates a highlight that was not originally present but which has been added to bring the reader's attention to a part of the text that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its likely relevance to the user's current activity. ''' pass
class mark(html_tag): ''' The mark element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a quotation or other block of text referred to from the prose, it indicates a highlight that was not originally present but which has been added to bring the reader's attention to a part of the text that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its likely relevance to the user's current activity. ''' pass
1
1
0
0
0
0
0
6
1
0
0
0
0
0
0
31
14
0
2
1
1
12
2
1
1
0
3
0
0
142,847
Knio/dominate
Knio_dominate/dominate/tags.py
dominate.tags.map_
class map_(html_tag): ''' The map element, in conjunction with any area element descendants, defines an image map. The element represents its children. ''' pass
class map_(html_tag): ''' The map element, in conjunction with any area element descendants, defines an image map. The element represents its children. '''
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
31
6
0
2
1
1
4
2
1
1
0
3
0
0