SPARQL query / wrapper for rdflib sparql query method
3254
def query(self, stringa):
        
        qres = self.rdflib_graph.query(stringa)
        return list(qres)
950231
def get_graph(graph, conn, **kwargs):
    
    sparql = render_without_request("sparqlGraphDataTemplate.rq",
                                    prefix=NSM.prefix(),
                                    graph=graph)
    return conn.query(sparql, **kwargs)
1309420
def select(*queries, **kwargs):
    
    def make_query(*args):
        def simple_query(nodes):
            if len(args) == 0:
                return nodes
            pred = args[0]
            results = []
            if isinstance(pred, list):
                funcs = [make_query(q) for q in pred]
                return __or(funcs, nodes)
            elif isinstance(pred, tuple):
                name, attrs = pred[0], pred[1:]
                name_pred = __make_name_pred(name)
                attrs_pred = __make_attrs_pred(attrs)
                for n in nodes:
                    if name_pred(n.name) and attrs_pred(n.attrs):
                        results.append(n)
            else:
                name_pred = __make_name_pred(pred)
                for n in nodes:
                    if name_pred(n.name):
                        results.append(n)
            return results
        if len(args) > 1:
            return __compose(make_query(*args[1:]), simple_query)
        return simple_query

    def deep_query(query, nodes):
        """ Slide the query down the branches. """
        def inner(children):
            results = []
            for c in children:
                if query([c]):
                    results.append(c)
                results.extend(inner(c.children))
            return results
        return inner(nodes)

    def unique(roots):
        seen = set()
        results = []
        for r in roots:
            if r not in seen:
                seen.add(r)
                results.append(r)
        return results

    def compiled_query(nodes):
        """
        This is the compiled query that can be run against a configuration.
        """
        query = make_query(*queries)

        roots = kwargs.get("roots", True)
        if kwargs.get("deep", False):
            results = deep_query(query, nodes)
            if roots:
                results = unique([r.root for r in results])
        elif roots:
            results = unique([n.root for n in query(nodes)])
        else:
            results = query(nodes)

        one = kwargs.get("one")
        if one is None:
            return SearchResult(children=results)
        return results[one] if results else None
    return compiled_query
1249416
protected Map<String,RDFNode> readNext() throws SparqlException {
    try {
      // read <result> or </results>
      int eventType = reader.nextTag();
      // if a closing element, then it should be </results>
      if (eventType == END_ELEMENT) {
        // already read the final result, so clean up and return nothing
        if (nameIs(RESULTS)) {
          cleanup();
          return null;
        }
        else throw new SparqlException("Bad element closure with: " + reader.getLocalName());
      }
      // we only expect a <result> here 
      testOpen(eventType, RESULT, "Expected a new result. Got :" +
          ((eventType == END_ELEMENT) ? "/" : "") + reader.getLocalName());

      Map<String,RDFNode> result = new HashMap<String,RDFNode>();
      // read <binding> list
      while ((eventType = reader.nextTag()) == START_ELEMENT && nameIs(BINDING)) {
        // get the name of the binding
        String name = reader.getAttributeValue(null, VAR_NAME);
        result.put(name, parseValue());
        testClose(reader.nextTag(), BINDING, "Single Binding not closed correctly");
      }

      // a non- <binding> was read, so it should have been a </result>
      testClose(eventType, RESULT, "Single Result not closed correctly");
      return result;
    } catch (XMLStreamException e) {
      throw new SparqlException("Error reading from XML stream", e);
    }
  }
533248
def _search(self, searchterm, pred, **args):
        
        # TODO: DRY with sparql_ontol_utils
        searchterm = searchterm.replace('%','.*')
        namedGraph = get_named_graph(self.handle)
        query = """
        prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>
        SELECT ?c WHERE {{
        GRAPH <{g}>  {{
        ?c {pred} ?l
        FILTER regex(?l,'{s}','i')
        }}
        }}
        """.format(pred=pred, s=searchterm, g=namedGraph)
        bindings = run_sparql(query)
        return [r['c']['value'] for r in bindings]
1060870
def _format(self, method="sparql", dt_format="turtle"):
        

        try:
            return __FORMAT_OPTIONS__[method](self, dt_format=dt_format)
        except KeyError:
            raise NotImplementedError("'{}' is not a valid format method"
                                      "".format(method))
347037
public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) {
        SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
        if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);}
        qdef.setIncludeDefaultRulesets(includeInferred);
        if (notNull(ruleset)) {qdef.setRulesets(ruleset);}
        if (notNull(getConstrainingQueryDefinition())){
        	qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());
            qdef.setDirectory(getConstrainingQueryDefinition().getDirectory());
            qdef.setCollections(getConstrainingQueryDefinition().getCollections());
            qdef.setResponseTransform(getConstrainingQueryDefinition().getResponseTransform());
            qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName());
        	}
        if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
        return sparqlManager.executeAsk(qdef,tx);
    }
72829
def _rdf2dot_reduced(g, stream):
    
    import cgi
    import collections

    import rdflib

    from rdflib.tools.rdf2dot import LABEL_PROPERTIES, NODECOLOR

    types = collections.defaultdict(set)
    fields = collections.defaultdict(set)
    nodes = {}

    def node(x):
        """Return a name of the given node."""
        return nodes.setdefault(x, 'node{0}'.format(len(nodes)))

    def label(x, g):
        """Generate a label for the node."""
        for labelProp in LABEL_PROPERTIES:
            label_ = g.value(x, labelProp)
            if label_:
                return label_

        try:
            return g.namespace_manager.compute_qname(x)[2]
        except Exception:
            return x

    def formatliteral(l, g):
        """Format and escape literal."""
        v = cgi.escape(l)
        if l.datatype:
            return '&quot;%s&quot;^^%s' % (v, qname(l.datatype, g))
        elif l.language:
            return '&quot;%s&quot;@%s' % (v, l.language)
        return '&quot;%s&quot;' % v

    def qname(x, g):
        """Compute qname."""
        try:
            q = g.compute_qname(x)
            return q[0] + ':' + q[2]
        except Exception:
            return x

    def color(p):
        """Choose node color."""
        return 'BLACK'

    for s, p, o in g:
        sn = node(s)
        if p == rdflib.RDFS.label:
            continue

        # inject the type predicate into the node itself
        if p == rdflib.RDF.type:
            types[sn].add((qname(p, g), cgi.escape(o)))
            continue
        if p == rdflib.term.URIRef('http://purl.org/dc/terms/isPartOf'):
            fields[sn].add((qname(p, g), cgi.escape(o)))
            continue
        if p == rdflib.term.URIRef('http://www.w3.org/ns/prov#wasInformedBy'):
            continue

        if isinstance(o, (rdflib.URIRef, rdflib.BNode)):
            on = node(o)
            opstr = (
                '\t%s -> %s [ color=%s, label=< <font point-size="12" '
                'color="#336633">%s</font> > ] ;\n'
            )
            stream.write(opstr % (sn, on, color(p), qname(p, g)))
        else:
            fields[sn].add((qname(p, g), formatliteral(o, g)))

    for u, n in nodes.items():
        stream.write(u"# %s %s\n" % (u, n))
        f = [
            '<tr><td align="left"><b>%s</b></td><td align="left">'
            '<b>%s</b></td></tr>' % x for x in sorted(types[n])
        ]
        f += [
            '<tr><td align="left">%s</td><td align="left">%s</td></tr>' % x
            for x in sorted(fields[n])
        ]
        opstr = (
            '%s [ shape=none, color=%s label=< <table color="#666666"'
            ' cellborder="0" cellspacing="0" border="1"><tr>'
            '<td colspan="2" bgcolor="grey"><B>%s</B></td></tr><tr>'
            '<td href="%s" bgcolor="#eeeeee" colspan="2">'
            '<font point-size="12" color="#6666ff">%s</font></td>'
            '</tr>%s</table> > ] \n'
        )
        stream.write(opstr % (n, NODECOLOR, label(u, g), u, u, ''.join(f)))

    stream.write('}\n')
451702
def url_from_rdf(rdf, prop):
    '''
    
    '''
    value = rdf.value(prop)
    if isinstance(value, (URIRef, Literal)):
        return value.toPython()
    elif isinstance(value, RdfResource):
        return value.identifier.toPython()
915710
def predicate_type(self, pred: URIRef) -> URIRef:
        
        return self._o.value(pred, RDFS.range)
761141
def _rdf2dot_simple(g, stream):
    """"""
    from itertools import chain

    import re

    path_re = re.compile(
        r'file:///(?P<type>[a-zA-Z]+)/'
        r'(?P<commit>\w+)'
        r'(?P<path>.+)?'
    )

    inputs = g.query(
        """
        SELECT ?input ?role ?activity ?comment
        WHERE {
            ?activity (prov:qualifiedUsage/prov:entity) ?input .
            ?activity prov:qualifiedUsage ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:entity ?input .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun .
            ?activity rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )
    outputs = g.query(
        """
        SELECT ?activity ?role ?output ?comment
        WHERE {
            ?output (prov:qualifiedGeneration/prov:activity) ?activity .
            ?output prov:qualifiedGeneration ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:activity ?activity .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun ;
                      rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )

    activity_nodes = {}
    artifact_nodes = {}
    for source, role, target, comment, in chain(inputs, outputs):
        # extract the pieces of the process URI
        src_path = path_re.match(source).groupdict()
        tgt_path = path_re.match(target).groupdict()

        # write the edge
        stream.write(
            '\t"{src_commit}:{src_path}" -> '
            '"{tgt_commit}:{tgt_path}" '
            '[label={role}] \n'.format(
                src_commit=src_path['commit'][:5],
                src_path=src_path.get('path') or '',
                tgt_commit=tgt_path['commit'][:5],
                tgt_path=tgt_path.get('path') or '',
                role=role
            )
        )
        if src_path.get('type') == 'commit':
            activity_nodes.setdefault(source, {'comment': comment})
            artifact_nodes.setdefault(target, {})
        if tgt_path.get('type') == 'commit':
            activity_nodes.setdefault(target, {'comment': comment})
            artifact_nodes.setdefault(source, {})

    # customize the nodes
    for node, content in activity_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[shape=box label="#{commit}:{path}:{comment}"] \n'.format(
                comment=content['comment'],
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    for node, content in artifact_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[label="#{commit}:{path}"] \n'.format(
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    stream.write('}\n')
706335
def getPropAllSubs(self, aURI):
        
        aURI = aURI
        try:
            qres = self.rdfgraph.query(
                  """SELECT DISTINCT ?x
                     WHERE {
                         { ?x rdfs:subPropertyOf+ <%s> }
                         FILTER (!isBlank(?x))
                     }
                     """ % (aURI))
        except:
            printDebug("... warning: the 'getPropAllSubs' query failed (maybe missing SPARQL 1.1 support?)")
            qres = []
        return list(qres)
950861
def transform_sparql_construct(rdf, construct_query):
    """"""

    logging.debug("performing SPARQL CONSTRUCT transformation")

    if construct_query[0] == '@':  # actual query should be read from file
        construct_query = file(construct_query[1:]).read()

    logging.debug("CONSTRUCT query: %s", construct_query)

    newgraph = Graph()
    for triple in rdf.query(construct_query):
        newgraph.add(triple)

    return newgraph
1111874
public static RDFDataset parseNQuads(String input) throws JsonLdError {
        // build RDF dataset
        final RDFDataset dataset = new RDFDataset();

        // split N-Quad input into lines
        final String[] lines = Regex.EOLN.split(input);
        int lineNumber = 0;
        for (final String line : lines) {
            lineNumber++;

            // skip empty lines
            if (Regex.EMPTY.matcher(line).matches()) {
                continue;
            }

            // parse quad
            final Matcher match = Regex.QUAD.matcher(line);
            if (!match.matches()) {
                throw new JsonLdError(JsonLdError.Error.SYNTAX_ERROR,
                        "Error while parsing N-Quads; invalid quad. line:" + lineNumber);
            }

            // get subject
            RDFDataset.Node subject;
            if (match.group(1) != null) {
                subject = new RDFDataset.IRI(unescape(match.group(1)));
            } else {
                subject = new RDFDataset.BlankNode(unescape(match.group(2)));
            }

            // get predicate
            final RDFDataset.Node predicate = new RDFDataset.IRI(unescape(match.group(3)));

            // get object
            RDFDataset.Node object;
            if (match.group(4) != null) {
                object = new RDFDataset.IRI(unescape(match.group(4)));
            } else if (match.group(5) != null) {
                object = new RDFDataset.BlankNode(unescape(match.group(5)));
            } else {
                final String language = unescape(match.group(8));
                final String datatype = match.group(7) != null ? unescape(match.group(7))
                        : match.group(8) != null ? RDF_LANGSTRING : XSD_STRING;
                final String unescaped = unescape(match.group(6));
                object = new RDFDataset.Literal(unescaped, datatype, language);
            }

            // get graph name ('@default' is used for the default graph)
            String name = "@default";
            if (match.group(9) != null) {
                name = unescape(match.group(9));
            } else if (match.group(10) != null) {
                name = unescape(match.group(10));
            }

            final RDFDataset.Quad triple = new RDFDataset.Quad(subject, predicate, object, name);

            // initialise graph in dataset
            if (!dataset.containsKey(name)) {
                final List<RDFDataset.Quad> tmp = new ArrayList<RDFDataset.Quad>();
                tmp.add(triple);
                dataset.put(name, tmp);
            }
            // add triple if unique to its graph
            else {
                final List<RDFDataset.Quad> triples = (List<RDFDataset.Quad>) dataset.get(name);
                if (!triples.contains(triple)) {
                    triples.add(triple);
                }
            }
        }

        return dataset;
    }
805398
def query(self, base, filterstr, attrlist=None):
		
		return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)
863385
def find_reachable(rdf, res):
    

    starttime = time.time()

    # This is almost a non-recursive breadth-first search algorithm, but a set
    # is used as the "open" set instead of a FIFO, and an arbitrary element of
    # the set is searched. This is slightly faster than DFS (using a stack)
    # and much faster than BFS (using a FIFO).
    seen = set()			# used as the "closed" set
    to_search = set([res])  # used as the "open" set

    while len(to_search) > 0:
        res = to_search.pop()
        if res in seen:
            continue
        seen.add(res)
        # res as subject
        for p, o in rdf.predicate_objects(res):
            if isinstance(p, URIRef) and p not in seen:
                to_search.add(p)
            if isinstance(o, URIRef) and o not in seen:
                to_search.add(o)
        # res as predicate
        for s, o in rdf.subject_objects(res):
            if isinstance(s, URIRef) and s not in seen:
                to_search.add(s)
            if isinstance(o, URIRef) and o not in seen:
                to_search.add(o)
        # res as object
        for s, p in rdf.subject_predicates(res):
            if isinstance(s, URIRef) and s not in seen:
                to_search.add(s)
            if isinstance(p, URIRef) and p not in seen:
                to_search.add(p)

    endtime = time.time()
    logging.debug("find_reachable took %f seconds", (endtime - starttime))

    return seen
98448
def _one_to_many_query(cls, query_obj, search4, model_attrib):
        
        model = model_attrib.parent.class_

        already_joined_tables = [mapper.class_ for mapper in query_obj._join_entities]

        if isinstance(search4, (str, int, Iterable)) and model not in already_joined_tables:
            query_obj = query_obj.join(model)

        if isinstance(search4, str):
            query_obj = query_obj.filter(model_attrib.like(search4))

        elif isinstance(search4, int):
            query_obj = query_obj.filter(model_attrib == search4)

        elif isinstance(search4, Iterable):
            query_obj = query_obj.filter(model_attrib.in_(search4))

        return query_obj