Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _buildTemplates(self): # INDEX - MAIN PAGE contents = self._renderTemplate("html-multi/index.html", extraContext={"theme": self.theme, "index_page_flag" : True}) FILE_NAME = "index.html" main_url = self._save2File(contents, FILE_N...
[ "\n OVERRIDING THIS METHOD from Factory\n " ]
Please provide a description of the function:def main(argv=None): print("Ontospy " + ontospy.VERSION) ontospy.get_or_create_home_repo() if argv: print("Argument passing not implemented yet") if False: onto = Model(argv[0]) for x in onto.get_classes(): print(x) onto.buildPythonClasses() s = Sk...
[ "\n\tSeptember 18, 2014: if an arg is passed, we visualize it\n\tOtherwise a simple shell gets opened.\n\n\t", "Good morning. Ready to Turtle away. Type docs() for help." ]
Please provide a description of the function:def add(self, text="", default_continuousAdd=True): if not text and default_continuousAdd: self.continuousAdd() else: pprefix = "" for x,y in self.rdflib_graph.namespaces(): pprefix += "@prefix %s: <%s> . \n" % (x, y) # add final . if missing if tex...
[ "add some turtle text" ]
Please provide a description of the function:def rdf_source(self, aformat="turtle"): if aformat and aformat not in self.SUPPORTED_FORMATS: return "Sorry. Allowed formats are %s" % str(self.SUPPORTED_FORMATS) if aformat == "dot": return self.__serializedDot() else: # use stardard rdf serializations ...
[ "\n\t\tSerialize graph using the format required\n\t\t" ]
Please provide a description of the function:def __serializedDot(self): temp = "" for x,y,z in self.rdflib_graph.triples((None, None, None)): temp += % (self.namespace_manager.normalizeUri(x), self.namespace_manager.normalizeUri(z), self.namespace_manager.normalizeUri(y)) temp = "digraph graphname {\n%s}" ...
[ "\n\t\tDOT format:\n\t\tdigraph graphname {\n\t\t\t a -> b [label=instanceOf];\n\t\t\t b -> d [label=isA];\n\t\t }\n\t\t", "\"%s\" -> \"%s\" [label=\"%s\"];\\n" ]
Please provide a description of the function:def omnigraffle(self): temp = self.rdf_source("dot") try: # try to put in the user/tmp folder from os.path import expanduser home = expanduser("~") filename = home + "/tmp/turtle_sketch.dot" f = open(filename, "w") except: filename = "turtle_sketch....
[ " tries to open an export directly in omnigraffle " ]
Please provide a description of the function:def _get_prompt(onto="", entity=""): base_text, onto_text, entity_text = "", "", "" base_color, onto_color, entity_color = Fore.RED + Style.BRIGHT, Fore.BLACK + Style.DIM, Fore.BLACK if not onto and not entity: base_text = base_color + '[Ontospy]' +...
[ "\n Global util that changes the prompt contextually\n :return: [Ontospy]>(cidoc_crm_v5.0...)>(class:E1.CRM_Entity)>\n " ]
Please provide a description of the function:def main(): print("Ontospy " + VERSION) Shell()._clear_screen() print(Style.BRIGHT + "** Ontospy Interactive Ontology Browser " + VERSION + " **" + Style.RESET_ALL) # manager.get_or_create_home_repo() Shell().cmdloop() raise SystemExit(1)
[ " standalone line script " ]
Please provide a description of the function:def print_topics(self, header, cmds, cmdlen, maxcol): if header: if cmds: self.stdout.write("%s\n" % str(header)) if self.ruler: self.stdout.write("%s\n" % str(self.ruler * len(header))) ...
[ "Override 'print_topics' so that you can exclude EOF and shell.\n 2016-02-12: added to test, copied from\n https://github.com/xlcnd/isbntools/blob/master/isbntools/bin/repl.py\n " ]
Please provide a description of the function:def _print(self, ms, style="TIP"): styles1 = {'IMPORTANT': Style.BRIGHT, 'TIP': Style.DIM, 'URI': Style.BRIGHT, 'TEXT': Fore.GREEN, 'MAGENTA': Fore.MAGENTA, 'BLUE'...
[ " abstraction for managing color printing " ]
Please provide a description of the function:def _printM(self, messages): if len(messages) == 2: print(Style.BRIGHT + messages[0] + Style.RESET_ALL + Fore.BLUE + messages[1] + Style.RESET_ALL) else: print("Not implemented")
[ "print a list of strings - for the mom used only by stats printout" ]
Please provide a description of the function:def _joinedQnames(self, _list): try: s = "; ".join([p.qname for p in _list]) except: s = "; ".join([p for p in _list]) return s
[ "util for returning a string joinin names of entities *used only in info command*" ]
Please provide a description of the function:def _printTriples(self, entity): self._print("----------------", "TIP") self._print(unicode(entity.uri), "IMPORTANT") for x in entity.triples: self._print("=> " + unicode(x[1]), "MAGENTA") self._print(".... " + unicode...
[ " display triples " ]
Please provide a description of the function:def _print_entity_intro(self, g=None, entity=None, first_time=True): if entity: self._clear_screen() obj = entity['object'] self._print("Loaded %s: <%s>" % (entity['type'].capitalize(), str(obj.uri)), "TIP") se...
[ "after a selection, prints on screen basic info about onto or entity, plus change prompt\n 2015-10-18: removed the sound\n 2016-01-18: entity is the shell wrapper around the ontospy entity\n " ]
Please provide a description of the function:def _printStats(self, graph, hrlinetop=False): if hrlinetop: self._print("----------------", "TIP") self._print("Ontologies......: %d" % len(graph.all_ontologies), "TIP") self._print("Classes.........: %d" % len(graph.all_classes)...
[ " shotcut to pull out useful info for interactive use\n 2016-05-11: note this is a local version of graph.printStats()\n " ]
Please provide a description of the function:def _printDescription(self, hrlinetop=True): if hrlinetop: self._print("----------------") NOTFOUND = "[not found]" if self.currentEntity: obj = self.currentEntity['object'] label = obj.bestLabel() or NOTFO...
[ "generic method to print out a description" ]
Please provide a description of the function:def _printTaxonomy(self, hrlinetop=True): if not self.currentEntity: # ==> ontology level return if hrlinetop: self._print("----------------") self._print("TAXONOMY:", "IMPORTANT") x = self.currentEntity['obje...
[ "\n print(a local taxonomy for the object)\n " ]
Please provide a description of the function:def _printClassDomain(self, hrlinetop=True, print_inferred=False): if not self.currentEntity: # ==> ontology level return x = self.currentEntity['object'] if self.currentEntity['type'] == 'class': if hrlinetop: ...
[ "\n print(more informative stats about the object)\n 2016-06-14: added inferred option\n " ]
Please provide a description of the function:def _printClassRange(self, hrlinetop=True, print_inferred=False): if not self.currentEntity: # ==> ontology level return x = self.currentEntity['object'] if self.currentEntity['type'] == 'class': if hrlinetop: ...
[ "\n print(more informative stats about the object)\n 2016-06-14: added inferred option\n " ]
Please provide a description of the function:def _printPropertyDomainRange(self, hrlinetop=True): if not self.currentEntity: # ==> ontology level return x = self.currentEntity['object'] if self.currentEntity['type'] == 'property': if hrlinetop: s...
[ "\n print(more informative stats about the object)\n " ]
Please provide a description of the function:def _printInstances(self, hrlinetop=True): if not self.currentEntity: # ==> ontology level return x = self.currentEntity['object'] if self.currentEntity['type'] == 'class': if hrlinetop: self._print("-...
[ "\n print(more informative stats about the object)\n " ]
Please provide a description of the function:def _printSourceCode(self, hrlinetop=True): if not self.currentEntity: # ==> ontology level return x = self.currentEntity['object'] if hrlinetop: self._print("----------------") self._print("Source:", "IMPORT...
[ "\n print(more informative stats about the object)\n " ]
Please provide a description of the function:def _selectFromList(self, _list, using_pattern=True, objtype=None): if not _list: self._print("No matching items.", "TIP") return None if using_pattern and len(_list) == 1: # removed pass # return _lis...
[ "\n Generic method that lets users pick an item from a list via input\n *using_pattern* flag to know if we're showing all choices or not\n Note: the list items need to be Ontospy entities.\n <objtype>: if specified, it allows incremental search by keeping specifying a\n different ...
Please provide a description of the function:def _next_ontology(self): currentfile = self.current['file'] try: idx = self.all_ontologies.index(currentfile) return self.all_ontologies[idx+1] except: return self.all_ontologies[0]
[ "Dynamically retrieves the next ontology in the list" ]
Please provide a description of the function:def _load_ontology(self, filename, preview_mode=False): if not preview_mode: fullpath = self.LOCAL_MODELS + filename g = manager.get_pickled_ontology(filename) if not g: g = manager.do_pickle_ontology(filen...
[ "\n Loads an ontology\n\n Unless preview_mode=True, it is always loaded from the local repository\n note: if the ontology does not have a cached version, it is created\n\n preview_mode: used to pass a URI/path to be inspected without saving it locally\n " ]
Please provide a description of the function:def _select_ontology(self, line): try: var = int(line) # it's a string if var in range(1, len(self.all_ontologies)+1): self._load_ontology(self.all_ontologies[var-1]) except ValueError: out = [] ...
[ "try to select an ontology NP: the actual load from FS is in <_load_ontology> " ]
Please provide a description of the function:def _select_class(self, line): g = self.current['graph'] if not line: out = g.all_classes using_pattern = False else: using_pattern = True if line.isdigit(): line = int(line) ...
[ "\n try to match a class and load it from the graph\n NOTE: the g.get_class(pattern) method does the heavy lifting\n " ]
Please provide a description of the function:def _select_property(self, line): g = self.current['graph'] if not line: out = g.all_properties using_pattern = False else: using_pattern = True if line.isdigit(): line = int(lin...
[ "try to match a property and load it" ]
Please provide a description of the function:def _select_concept(self, line): g = self.current['graph'] if not line: out = g.all_skos_concepts using_pattern = False else: using_pattern = True if line.isdigit(): line = int(l...
[ "try to match a class and load it" ]
Please provide a description of the function:def _delete_file(self, line=""): if not self.all_ontologies: self._help_nofiles() else: out = [] for each in self.all_ontologies: if line in each: out += [each] cho...
[ "\tDelete an ontology\n 2016-04-11: not a direct command anymore " ]
Please provide a description of the function:def _rename_file(self, line=""): if not self.all_ontologies: self._help_nofiles() else: out = [] for each in self.all_ontologies: if line in each: out += [each] choi...
[ "Rename an ontology\n 2016-04-11: not a direct command anymore " ]
Please provide a description of the function:def do_ls(self, line): opts = self.LS_OPTS line = line.split() _pattern = "" if len(line) == 0: # default contextual behaviour [2016-03-01] if not self.current: line = ["ontologies"] ...
[ "Shows entities of a given kind." ]
Please provide a description of the function:def do_tree(self, line): opts = self.TREE_OPTS line = line.split() _pattern = "" if not self.current: self._help_noontology() return if len(line) == 0: # default contextual behaviour [2016...
[ "Shows entities of a given kind." ]
Please provide a description of the function:def do_get(self, line): line = line.split() _pattern = "" if len(line) > 1: _pattern = line[1] opts = self.GET_OPTS if (not line) or (line[0] not in opts) or (not _pattern): self.help_get() ...
[ "Finds entities matching a given string pattern. \\nOptions: [ ontologies | classes | properties | concepts ]" ]
Please provide a description of the function:def do_info(self, line): # opts = [ 'namespaces', 'description', 'overview', 'toplayer', 'parents', 'children', 'stats', 'triples' ] opts = self.INFO_OPTS if not self.current: self._help_noontology() return l...
[ "Inspect the current entity and display a nice summary of key properties" ]
Please provide a description of the function:def do_visualize(self, line): if not self.current: self._help_noontology() return line = line.split() try: # from ..viz.builder import action_visualize from ..ontodocs.builder import action_v...
[ "Visualize an ontology - ie wrapper for export command" ]
Please provide a description of the function:def do_import(self, line): line = line.split() if line and line[0] == "starter-pack": actions.action_bootstrap() elif line and line[0] == "uri": self._print( "------------------\nEnter a valid graph ...
[ "Import an ontology" ]
Please provide a description of the function:def do_file(self, line): opts = self.FILE_OPTS if not self.all_ontologies: self._help_nofiles() return line = line.split() if not line or line[0] not in opts: self.help_file() return ...
[ "PErform some file operation" ]
Please provide a description of the function:def do_serialize(self, line): opts = self.SERIALIZE_OPTS if not self.current: self._help_noontology() return line = line.split() g = self.current['graph'] if not line: line = ['turtle'] ...
[ "Serialize an entity into an RDF flavour" ]
Please provide a description of the function:def do_next(self, line): if not self.current: print("Please select an ontology first. E.g. use the 'ls ontologies' or 'get ontology <name>' commands.") elif self.currentEntity: g = self.current['graph'] if self.cur...
[ "Jump to the next entities (ontology, class or property) depending on context" ]
Please provide a description of the function:def do_back(self, line): "Go back one step. From entity => ontology; from ontology => ontospy top level." if self.currentEntity: self.currentEntity = None self.prompt = _get_prompt(self.current['file']) else: self.c...
[]
Please provide a description of the function:def do_zen(self, line): _quote = random.choice(QUOTES) # print(_quote['source']) print(Style.DIM + unicode(_quote['text'])) print(Style.BRIGHT + unicode(_quote['source']) + Style.RESET_ALL)
[ "Inspiring quotes for the working ontologist" ]
Please provide a description of the function:def _do_shell(self, line): if not line: return sp = Popen(line, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=not WINDOWS) ...
[ "Send a command to the Unix shell.\\n==> Usage: shell ls ~" ]
Please provide a description of the function:def complete_ls(self, text, line, begidx, endidx): options = self.LS_OPTS if not text: completions = options else: completions = [f for f in options if f.startswi...
[ "completion for ls command" ]
Please provide a description of the function:def complete_tree(self, text, line, begidx, endidx): options = self.TREE_OPTS if not text: completions = options else: completions = [f for f in options if f.star...
[ "completion for ls command" ]
Please provide a description of the function:def complete_get(self, text, line, begidx, endidx): options = self.GET_OPTS if not text: completions = options else: completions = [f for f in options if f.starts...
[ "completion for find command" ]
Please provide a description of the function:def complete_info(self, text, line, begidx, endidx): opts = self.INFO_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswith(te...
[ "completion for info command" ]
Please provide a description of the function:def complete_import(self, text, line, begidx, endidx): opts = self.IMPORT_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswit...
[ "completion for serialize command" ]
Please provide a description of the function:def complete_serialize(self, text, line, begidx, endidx): opts = self.SERIALIZE_OPTS if not text: completions = opts else: completions = [f for f in opts if f.sta...
[ "completion for serialize command" ]
Please provide a description of the function:def complete_visualize(self, text, line, begidx, endidx): opts = self.VISUALIZE_OPTS if not text: completions = opts else: completions = [f for f in opts if f.sta...
[ "completion for file command" ]
Please provide a description of the function:def complete_file(self, text, line, begidx, endidx): opts = self.FILE_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswith(te...
[ "completion for file command" ]
Please provide a description of the function:def build_D3treeStandard(old, MAX_DEPTH, level=1, toplayer=None): out = [] if not old: old = toplayer for x in old: d = {} # print "*" * level, x.label d['qname'] = x.qname d['name'] = x.bestLabel(quotes=False).replace...
[ "\n\t For d3s examples all we need is a json with name, children and size .. eg\n\n\t {\n\t \"name\": \"flare\",\n\t \"children\": [\n\t {\n\t \"name\": \"analytics\",\n\t \"children\": [\n\t\t{\n\t\t \"name\": \"cluster\",\n\t\t \"children\": [\n\t\t {\"name\": \"AgglomerativeCluster\", \"size\": 3938},\n\...
Please provide a description of the function:def build_D3bubbleChart(old, MAX_DEPTH, level=1, toplayer=None): out = [] if not old: old = toplayer for x in old: d = {} # print "*" * level, x.label d['qname'] = x.qname d['name'] = x.bestLabel(quotes=False).replace(...
[ "\n\t Similar to standar d3, but nodes with children need to be duplicated otherwise they are\n\t not depicted explicitly but just color coded\n\n\t\"name\": \"all\",\n\t\"children\": [\n\t\t{\"name\": \"Biological Science\", \"size\": 9000},\n\t\t {\"name\": \"Biological Science\", \"children\": [\n\t\t\t {\"na...
Please provide a description of the function:def build_D3treepie(old, MAX_DEPTH, level=1, toplayer=None): d = {} if not old: old = toplayer for x in old: label = x.bestLabel(quotes=False).replace("_", " ") if x.children() and level < MAX_DEPTH: size = len(x.children(...
[ "\n\tCreate the JSON needed by the treePie viz\n\thttp://bl.ocks.org/adewes/4710330/94a7c0aeb6f09d681dbfdd0e5150578e4935c6ae\n\n\tEg\n\n\t['origin' , [n1, n2],\n\t\t\t{ 'name1' :\n\t\t\t\t['name1', [n1, n2],\n\t\t\t\t\t{'name1-1' : ...}\n\t\t\t\t] ,\n\t\t\t} ,\n\t]\n\n\t" ]
Please provide a description of the function:def formatHTML_EntityTreeTable(treedict, element=0): # ontoFile = onto.ontologyMaskedLocation or onto.ontologyPhysicalLocation # if not treedict: # treedict = onto.ontologyClassTree() stringa = for x in treedict[element]: if x.qname == "owl...
[ " outputs an html tree representation based on the dictionary we get from the Inspector\n\tobject....\n\n\tEG:\n\t<table class=h>\n\n\t\t<tr>\n\t\t <td class=\"tc\" colspan=4><a href=\"../DataType\">DataType</a>\n\t\t </td>\n\t\t</tr>\n\t\t<tr>\n\t\t <td class=\"tc\" colspan=4><a href=\"../DataType\">DataType</a...
Please provide a description of the function:def compare(referenceOnto, somegraph): spy1 = Ontology(referenceOnto) spy2 = Ontology(somegraph) class_comparison = {} for x in spy2.allclasses: if x not in spy1.allclasses: class_comparison[x] = False else: class_comparison[x] = True prop_comparison = {}...
[ "\n\tDesc\n\t" ]
Please provide a description of the function:def printComparison(results, class_or_prop): data = [] Row = namedtuple('Row',[class_or_prop,'VALIDATED']) for k,v in sorted(results.items(), key=lambda x: x[1]): data += [Row(k, str(v))] pprinttable(data)
[ "\n\tprint(out the results of the comparison using a nice table)\n\t" ]
Please provide a description of the function:def parse_options(): parser = optparse.OptionParser(usage=USAGE, version=VERSION) parser.add_option("-o", "--ontology", action="store", type="string", default="", dest="ontology", help="Specifies which ontology to compare to.") opts, args = parser.parse_args() ...
[ "\n\tparse_options() -> opts, args\n\n\tParse any command-line options given returning both\n\tthe parsed options and arguments.\n\t" ]
Please provide a description of the function:def infer_best_title(self): if self.ontospy_graph.all_ontologies: return self.ontospy_graph.all_ontologies[0].uri elif self.ontospy_graph.sources: return self.ontospy_graph.sources[0] else: return "Untitled...
[ "Selects something usable as a title for an ontospy graph" ]
Please provide a description of the function:def build(self, output_path=""): self.output_path = self.checkOutputPath(output_path) self._buildStaticFiles() self.final_url = self._buildTemplates() printDebug("Done.", "comment") printDebug("=> %s" % (self.final_url), "com...
[ "method that should be inherited by all vis classes" ]
Please provide a description of the function:def _buildTemplates(self): # in this case we only have one contents = self._renderTemplate(self.template_name, extraContext=None) # the main url used for opening viz f = self.main_file_name main_url = self._save2File(contents...
[ "\n do all the things necessary to build the viz\n should be adapted to work for single-file viz, or multi-files etc.\n\n :param output_path:\n :return:\n " ]
Please provide a description of the function:def _buildStaticFiles(self): if not self.output_path_static: self.output_path_static = os.path.join(self.output_path, "static") # printDebug(self.output_path_static, "red") if not os.path.exists(self.output_path_static): ...
[ " move over static files so that relative imports work\n Note: if a dir is passed, it is copied with all of its contents\n If the file is a zip, it is copied and extracted too\n # By default folder name is 'static', unless *output_path_static* is passed (now allowed only in special applications...
Please provide a description of the function:def _build_basic_context(self): # printDebug(str(self.ontospy_graph.toplayer_classes)) topclasses = self.ontospy_graph.toplayer_classes[:] if len(topclasses) < 3: # massage the toplayer! for topclass in self.ontospy_graph.toplaye...
[ "\n Return a standard dict used in django as a template context\n " ]
Please provide a description of the function:def checkOutputPath(self, output_path): if not output_path: # output_path = self.output_path_DEFAULT output_path = os.path.join(self.output_path_DEFAULT, slugify(unicode(self.title))) if ...
[ "\n Create or clean up output path\n " ]
Please provide a description of the function:def highlight_code(self, ontospy_entity): try: pygments_code = highlight(ontospy_entity.rdf_source(), TurtleLexer(), HtmlFormatter()) pygments_code_css = HtmlFormatter().get_style_defs('.highlight...
[ "\n produce an html version of Turtle code with syntax highlighted\n using Pygments CSS\n " ]
Please provide a description of the function:def query(self, q, format="", convert=True): lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()] lines.extend(q.split("\n")) query = "\n".join(lines) if self.verbose: print(query, "\n\n") return self.__doQuery(query, format, convert)
[ "\n\t\tGeneric SELECT query structure. 'q' is the main body of the query.\n\n\t\tThe results passed out are not converted yet: see the 'format' method\n\t\tResults could be iterated using the idiom: for l in obj : do_something_with_line(l)\n\n\t\tIf convert is False, we return the collection of rdflib instances\n\n...
Please provide a description of the function:def describe(self, uri, format="", convert=True): lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()] if uri.startswith("http://"): lines.extend(["DESCRIBE <%s>" % uri]) else: # it's a shortened uri lines.extend(["DESCRIBE %s" % uri]) ...
[ "\n\t\tA simple DESCRIBE query with no 'where' arguments. 'uri' is the resource you want to describe.\n\n\t\tTODO: there are some errors with describe queries, due to the results being sent back\n\t\tFor the moment we're not using them much.. needs to be tested more.\n\n\t\t" ]
Please provide a description of the function:def __getFormat(self, format): if format == "XML": self.sparql.setReturnFormat(XML) self.format = "XML" elif format == "RDF": self.sparql.setReturnFormat(RDF) self.format = "RDF" else: self.sparql.setReturnFormat(JSON) self.format = "JSON"
[ "\n\t\tDefaults to JSON [ps: 'RDF' is the native rdflib representation]\n\t\t" ]
Please provide a description of the function:def __doQuery(self, query, format, convert): self.__getFormat(format) self.sparql.setQuery(query) if convert: results = self.sparql.query().convert() else: results = self.sparql.query() return results
[ "\n\t\tInner method that does the actual query\n\t\t" ]
Please provide a description of the function:def get_home_location(): config = SafeConfigParser() config_filename = ONTOSPY_LOCAL + '/config.ini' if not os.path.exists(config_filename): config_filename = 'config.ini' config.read(config_filename) try: _location = config.get('mo...
[ "Gets the path of the local library folder\n :return - a string e.g. \"/users/mac/ontospy\"\n " ]
Please provide a description of the function:def get_localontologies(pattern=""): "returns a list of file names in the ontologies folder (not the full path)" res = [] ONTOSPY_LOCAL_MODELS = get_home_location() if not os.path.exists(ONTOSPY_LOCAL_MODELS): get_or_create_home_repo() for f in os...
[]
Please provide a description of the function:def get_random_ontology(TOP_RANGE=10, pattern=""): choices = get_localontologies(pattern=pattern) try: ontouri = choices[random.randint(0, TOP_RANGE)] # [0] except: ontouri = choices[0] print("Testing with URI: %s" % ontouri) g = get...
[ "for testing purposes. Returns a random ontology/graph" ]
Please provide a description of the function:def get_pickled_ontology(filename): pickledfile = os.path.join(ONTOSPY_LOCAL_CACHE, filename + ".pickle") # pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" if GLOBAL_DISABLE_CACHE: printDebug( "WARNING: DEMO MODE cache has ...
[ " try to retrieve a cached ontology " ]
Please provide a description of the function:def do_pickle_ontology(filename, g=None): ONTOSPY_LOCAL_MODELS = get_home_location() get_or_create_home_repo() # ensure all the right folders are there pickledpath = os.path.join(ONTOSPY_LOCAL_CACHE, filename + ".pickle") # pickledpath = ONTOSPY_LOCAL_C...
[ "\n from a valid filename, generate the graph instance and pickle it too\n note: option to pass a pre-generated graph instance too\n 2015-09-17: added code to increase recursion limit if cPickle fails\n see http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-using-pythons-pick...
Please provide a description of the function:def clear_screen(): import os, platform if platform.system() == "Windows": tmp = os.system('cls') #for window else: tmp = os.system('clear') #for Linux return True
[ " http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell " ]
Please provide a description of the function:def get_default_preds(): g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base_schemas=False) classes = [(x.qname, x.bestDescription()) for x in g.all_classes] properties = [(x.qname, x.bestDescription()) for x in g.all_properties] commands...
[ "dynamically build autocomplete options based on an external file" ]
Please provide a description of the function:def _buildTemplates(self): # Ontology - MAIN PAGE contents = self._renderTemplate( "markdown/markdown_ontoinfo.md", extraContext=None) FILE_NAME = "index.md" main_url = self._save2File(contents, FILE_NAME, self.output_pat...
[ "\n OVERRIDING THIS METHOD from Factory\n " ]
Please provide a description of the function:def matcher(graph1, graph2, confidence=0.5, output_file="matching_results.csv", class_or_prop="classes", verbose=False): printDebug("----------\nNow matching...") f = open(output_file, 'wt') counter = 0 try: writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC) w...
[ "\n\ttakes two graphs and matches its classes based on qname, label etc..\n\t@todo extend to properties and skos etc..\n\t" ]
Please provide a description of the function:def main(): print("Ontospy " + ontospy.VERSION) ontospy.get_or_create_home_repo() opts, args = parse_options() if len(args) < 2: printDebug("Please provide two arguments, or use -h for more options.") sys.exit(0) var = input("Match classes or properties? [c|p,...
[ " command line script " ]
Please provide a description of the function:def _buildTemplates(self): c_mylist = build_D3treeStandard(0, 99, 1, self.ontospy_graph.toplayer_classes) p_mylist = build_D3treeStandard(0, 99, 1, self.ontospy_graph.to...
[ "\n OVERRIDING THIS METHOD from Factory\n " ]
Please provide a description of the function:def hello(): click.clear() click.secho('Hello World!', fg='green') click.secho('Some more text', bg='blue', fg='white') click.secho('ATTENTION', blink=True, bold=True) click.echo('Continue? [yn] ', nl=False) c = click.getchar() click.echo() ...
[ "\"http://click.pocoo.org/5/\n http://click.pocoo.org/5/api/\n " ]
Please provide a description of the function:def safe_str(u, errors="replace"): s = u.encode(sys.stdout.encoding or "utf-8", errors) return s
[ "Safely print the given string.\n\n If you want to see the code points for unprintable characters then you\n can use `errors=\"xmlcharrefreplace\"`.\n http://code.activestate.com/recipes/576602-safe-print/\n " ]
Please provide a description of the function:def list_chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i + n]
[ "Yield successive n-sized chunks from l.\n\n import pprint\n pprint.pprint(list(chunks(range(10, 75), 10)))\n [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],\n [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],\n [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],\n [50,...
Please provide a description of the function:def split_list(alist, wanted_parts=1): length = len(alist) return [ alist[i * length // wanted_parts:(i + 1) * length // wanted_parts] for i in range(wanted_parts) ]
[ "\n A = [0,1,2,3,4,5,6,7,8,9]\n\n print split_list(A, wanted_parts=1)\n print split_list(A, wanted_parts=2)\n print split_list(A, wanted_parts=8)\n " ]
Please provide a description of the function:def remove_duplicates(seq, idfun=None): # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) # in old Python versions: # if seen.has_key(...
[ " removes duplicates from a list, order preserving, as found in\n http://www.peterbe.com/plog/uniqifiers-benchmark\n " ]
Please provide a description of the function:def printDebug(text, mystyle="", **kwargs): if mystyle == "comment": click.secho(text, dim=True, err=True) elif mystyle == "important": click.secho(text, bold=True, err=True) elif mystyle == "normal": click.secho(text, reset=True, er...
[ "\n util for printing in colors using click.secho()\n\n :kwargs = you can do printDebug(\"s\", bold=True)\n\n 2018-12-06: by default print to standard error (err=True)\n\n Styling output:\n <http://click.pocoo.org/5/api/#click.style>\n Styles a text with ANSI styles and returns the new string. By ...
Please provide a description of the function:def OLD_printDebug(s, style=None): if style == "comment": s = Style.DIM + s + Style.RESET_ALL elif style == "important": s = Style.BRIGHT + s + Style.RESET_ALL elif style == "normal": s = Style.RESET_ALL + s + Style.RESET_ALL elif...
[ "\n util for printing in colors to sys.stderr stream\n " ]
Please provide a description of the function:def pprint2columns(llist, max_length=60): if len(llist) == 0: return None col_width = max(len(word) for word in llist) + 2 # padding # llist length must be even, otherwise splitting fails if not len(llist) % 2 == 0: llist += [' '] # a...
[ "\n llist = a list of strings\n max_length = if a word is longer than that, for single col display\n\n > prints a list in two columns, taking care of alignment too\n " ]
Please provide a description of the function:def save_anonymous_gist(title, files): try: from github3 import create_gist except: print("github3 library not found (pip install github3)") raise SystemExit(1) gist = create_gist(title, files) urls = { 'gist': ...
[ "\n October 21, 2015\n title = the gist title\n files = {\n 'spam.txt' : {\n 'content': 'What... is the air-speed velocity of an unladen swallow?'\n }\n # ..etc...\n }\n\n works also in blocks eg from\n https://gist.github.com/anonymous/b839e3a4d596b2152...
Please provide a description of the function:def _clear_screen(): if platform.system() == "Windows": tmp = os.system('cls') #for window else: tmp = os.system('clear') #for Linux return True
[ " http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell " ]
Please provide a description of the function:def playSound(folder, name=""): try: if not name: onlyfiles = [ f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f)) ] name = random.choice(onlyfiles) subprocess....
[ " as easy as that " ]
Please provide a description of the function:def truncate(data, l=20): "truncate a string" info = (data[:l] + '..') if len(data) > l else data return info
[]
Please provide a description of the function:def inferMainPropertyType(uriref): if uriref: if uriref == rdflib.OWL.DatatypeProperty: return uriref elif uriref == rdflib.OWL.AnnotationProperty: return uriref elif uriref == rdflib.RDF.Property: return u...
[ "\n Attempt to reduce the property types to 4 main types\n (without the OWL ontology - which would be the propert way)\n\n In [3]: for x in g.all_properties:\n ...:\t\tprint x.rdftype\n ...:\n http://www.w3.org/2002/07/owl#FunctionalProperty\n http://www.w3.org/2002/07/owl#FunctionalPrope...
Please provide a description of the function:def printGenericTree(element, level=0, showids=True, labels=False, showtype=True, TYPE_MARGIN=18): ID_MARGIN = 5 SHORT_TYPES = { "rdf:Property": "r...
[ "\n Print nicely into stdout the taxonomical tree of an ontology.\n\n Works irrespectively of whether it's a class or property.\n\n Note: indentation is made so that ids up to 3 digits fit in, plus a space.\n [123]1--\n [1]123--\n [12]12--\n\n <TYPE_MARGIN> is parametrized so that classes and p...
Please provide a description of the function:def firstStringInList(literalEntities, prefLanguage="en"): match = "" if len(literalEntities) == 1: match = literalEntities[0] elif len(literalEntities) > 1: for x in literalEntities: if getattr(x, 'language') and getattr(x, ...
[ "\n from a list of literals, returns the one in prefLanguage\n if no language specification is available, return first element\n " ]
Please provide a description of the function:def joinStringsInList(literalEntities, prefLanguage="en"): match = [] if len(literalEntities) == 1: return literalEntities[0] elif len(literalEntities) > 1: for x in literalEntities: if getattr(x, 'language') and getattr(x, ...
[ "\n from a list of literals, returns the ones in prefLanguage joined up.\n if the desired language specification is not available, join all up\n " ]
Please provide a description of the function:def sortByNamespacePrefix(urisList, nsList): exit = [] urisList = sort_uri_list_by_name(urisList) for ns in nsList: innerexit = [] for uri in urisList: if str(uri).startswith(str(ns)): innerexit += [uri] ex...
[ "\n Given an ordered list of namespaces prefixes, order a list of uris based on that.\n Eg\n\n In [7]: ll\n Out[7]:\n [rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),\n rdflib.term.URIRef(u'printGenericTreeorg/2000/01/rdf-schema#comment'),\n ...
Please provide a description of the function:def sort_uri_list_by_name(uri_list, bypassNamespace=False): def get_last_bit(uri_string): try: x = uri_string.split("#")[1] except: x = uri_string.split("/")[-1] return x try: if bypassNamespace: ...
[ "\n Sorts a list of uris\n\n bypassNamespace:\n based on the last bit (usually the name after the namespace) of a uri\n It checks whether the last bit is specified using a # or just a /, eg:\n rdflib.URIRef('http://purl.org/ontology/mo/Vinyl'),\n rdflib.URIRef('http://p...
Please provide a description of the function:def guess_fileformat(aUri): if aUri.endswith(".xml"): return "xml" elif aUri.endswith(".nt"): return "nt" elif aUri.endswith(".n3") or aUri.endswith(".ttl"): return "n3" elif aUri.endswith(".trix"): return "trix" elif ...
[ "\n Simple file format guessing (using rdflib format types) based on the suffix\n\n see rdflib.parse [https://rdflib.readthedocs.org/en/latest/using_graphs.html]\n\n " ]
Please provide a description of the function:def inferNamespacePrefix(aUri): stringa = aUri.__str__() try: prefix = stringa.replace("#", "").split("/")[-1] except: prefix = "" return prefix
[ "\n From a URI returns the last bit and simulates a namespace prefix when rendering the ontology.\n\n eg from <'http://www.w3.org/2008/05/skos#'>\n it returns the 'skos' string\n " ]