Prepare a statement into a triple ready for rdflib graph
551038
def process(source, target, rdfsonly, base=None, logger=logging):
    '''
    

    '''
    for link in source.match():
        s, p, o = link[:3]
        #SKip docheader statements
        if s == (base or '') + '@docheader': continue
        if p in RESOURCE_MAPPING: p = RESOURCE_MAPPING[p]
        if o in RESOURCE_MAPPING: o = RESOURCE_MAPPING[o]
        if p == VERSA_BASEIRI + 'refines':
            tlinks = list(source.match(s, TYPE_REL))
            if tlinks:
                if tlinks[0][TARGET] == VERSA_BASEIRI + 'Resource':
                    p = I(RDFS_NAMESPACE + 'subClassOf')
                elif tlinks[0][TARGET] == VERSA_BASEIRI + 'Property':
                    p = I(RDFS_NAMESPACE + 'subPropertyOf')
        if p == VERSA_BASEIRI + 'properties':
            suri = I(iri.absolutize(s, base)) if base else s
            target.add((URIRef(o), URIRef(RDFS_NAMESPACE + 'domain'), URIRef(suri)))
            continue
        if p == VERSA_BASEIRI + 'value':
            if o not in ['Literal', 'IRI']:
                ouri = I(iri.absolutize(o, base)) if base else o
                target.add((URIRef(s), URIRef(RDFS_NAMESPACE + 'range'), URIRef(ouri)))
                continue
        s = URIRef(s)
        #Translate v:type to rdf:type
        p = RDF.type if p == TYPE_REL else URIRef(p)
        o = URIRef(o) if isinstance(o, I) else Literal(o)
        if not rdfsonly or p.startswith(RDF_NAMESPACE) or p.startswith(RDFS_NAMESPACE):
            target.add((s, p, o))
    return
1134828
def to_triples(self, short_pred=True, properties=True):
        
        ts = []
        qs = set(self.nodeids(quantifier=True))
        for n in nodes(self):
            pred = n.pred.short_form() if short_pred else n.pred.string
            ts.append((n.nodeid, 'predicate', pred))
            if n.lnk is not None:
                ts.append((n.nodeid, 'lnk', '"{}"'.format(str(n.lnk))))
            if n.carg is not None:
                ts.append((n.nodeid, 'carg', '"{}"'.format(n.carg)))
            if properties and n.nodeid not in qs:
                for key, value in n.sortinfo.items():
                    ts.append((n.nodeid, key.lower(), value))

        for l in links(self):
            if safe_int(l.start) == LTOP_NODEID:
                ts.append((l.start, 'top', l.end))
            else:
                relation = '{}-{}'.format(l.rargname.upper(), l.post)
                ts.append((l.start, relation, l.end))
        return ts
1140164
function serializeStatements (statements) {
  var source = statements.map(function (st) { return st.toNT() })
  source = source.join('\n')
  return source
}
1120861
def describe_uris(uris)
      graph = RDF::Graph.new

      if uris.length > 0
        uris_sparql_str = uris.map{ |u| "<#{u.to_s}>" }.join(" ")

        # Do a big describe statement, and read the results into an in-memory repo
        ntriples_string = Tripod::SparqlClient::Query.query("CONSTRUCT { ?s ?p ?o } WHERE { VALUES ?s { #{uris_sparql_str} }.  ?s ?p ?o . }", Tripod.ntriples_header_str)
        graph = _rdf_graph_from_ntriples_string(ntriples_string, graph)
      end

      graph
    end
585152
def get_triples(self, subject=None, predicate=None, object_=None):
        """"""

        for triple in self.triples:

            # Filter out non-matches
            if subject is not None and triple['subject'] != subject:
                continue
            if predicate is not None and triple['predicate'] != predicate:
                continue
            if object_ is not None and triple['object'] != object_:
                continue

            yield triple
960145
def extract_statements(self):
        """"""
        for p_info in self._json:
            para = RlimspParagraph(p_info, self.doc_id_type)
            self.statements.extend(para.get_statements())
        return
257816
def preprocess(ops, nlp, rows, get_ids):
    """"""
    Xs = []
    ys = []
    for (text1, text2), label in rows:
        Xs.append((get_ids([nlp(text1)])[0], get_ids([nlp(text2)])[0]))
        ys.append(label)
    return Xs, to_categorical(ys, nb_classes=2)
36001
def execute(self, triple_map, output, **kwargs):
        
        sparql = PREFIX + triple_map.logicalSource.query.format(
            **kwargs)
        bindings = self.__get_bindings__(sparql)
        iterator = str(triple_map.logicalSource.iterator)
        for binding in bindings:
            entity_dict = binding.get(iterator)
            if isinstance(entity_dict, rdflib.term.Node):
                entity = entity_dict
            elif isinstance(entity_dict, dict):
                raw_value = entity_dict.get('value')
                if entity_dict.get('type').startswith('bnode'):
                    entity = rdflib.BNode(raw_value)
                else:
                    entity = rdflib.URIRef(raw_value)
            if triple_map.subjectMap.class_ is not None:
                output.add(
                    (entity,
                     rdflib.RDF.type,
                     triple_map.subjectMap.class_))

            sparql_query = self.__construct_compound_query__(
                triple_map).format(**kwargs)
            properties = self.__get_bindings__(sparql_query)
            for pred_obj_map in triple_map.predicateObjectMap:
                predicate = pred_obj_map.predicate
                if pred_obj_map.constant is not None:
                    output.add(
                        (entity, predicate, pred_obj_map.constant))
                    continue
                if "#" in str(predicate):
                    key = str(predicate).split("#")[-1]
                else:
                    key = str(predicate).split("/")[-1]

                for property_ in properties:
                    if key in property_.keys():
                        info = {"about": property_.get(key)}
                        object_ = __get_object__(info)
                        output.add((entity, predicate, object_))
1162739
def rdf_source(self, format="turtle"):
        
        s = self.rdflib_graph.serialize(format=format)
        if isinstance(s, bytes):
            s = s.decode('utf-8')
        return s
892704
def prepare(self, statement):
        
        self._check_closed()
        self._column_types = None
        statement_id = params_metadata = result_metadata_part = None

        request = RequestMessage.new(
            self.connection,
            RequestSegment(
                message_types.PREPARE,
                Command(statement)
            )
        )
        response = self.connection.send_request(request)

        for part in response.segments[0].parts:
            if part.kind == part_kinds.STATEMENTID:
                statement_id = part.statement_id
            elif part.kind == part_kinds.PARAMETERMETADATA:
                params_metadata = part.values
            elif part.kind == part_kinds.RESULTSETMETADATA:
                result_metadata_part = part

        # Check that both variables have been set in previous loop, we need them:
        assert statement_id is not None
        assert params_metadata is not None
        # cache statement:
        self._prepared_statements[statement_id] = PreparedStatement(self.connection, statement_id,
                                                                    params_metadata, result_metadata_part)
        return statement_id
512587
def matchesExpr(cntxt: Context, T: RDFGraph, expr: ShExJ.tripleExpr, _: DebugContext) -> bool:
    

    if isinstance(expr, ShExJ.OneOf):
        return matchesOneOf(cntxt, T, expr)
    elif isinstance(expr, ShExJ.EachOf):
        return matchesEachOf(cntxt, T, expr)
    elif isinstance(expr, ShExJ.TripleConstraint):
        return matchesCardinality(cntxt, T, expr)
    elif isinstance_(expr, ShExJ.tripleExprLabel):
        return matchesTripleExprRef(cntxt, T, expr)
    else:
        raise Exception("Unknown expression")
1355113
def to_indra_statements(graph):
    
    from indra.sources.bel import process_pybel_graph

    pbp = process_pybel_graph(graph)
    return pbp.statements
1012835
def dump(self,format='ttl'):

		'''
		
		'''

		return self.rdf.graph.serialize(format=format).decode('utf-8')
1301139
def parse_object_like_triples(self):

		'''
		
		'''

		# parse triples as object-like attributes in self.rdf.triples
		self.rdf.triples = SimpleNamespace() # prepare triples
		for s,p,o in self.rdf.graph:

			# get ns info
			ns_prefix, ns_uri, predicate = self.rdf.graph.compute_qname(p)

			# if prefix as list not yet added, add
			if not hasattr(self.rdf.triples, ns_prefix):
				setattr(self.rdf.triples, ns_prefix, SimpleNamespace())

			# same for predicate
			if not hasattr(getattr(self.rdf.triples, ns_prefix), predicate):
				setattr(getattr(self.rdf.triples, ns_prefix), predicate, [])

			# append object for this prefix
			getattr(getattr(self.rdf.triples, ns_prefix), predicate).append(o)
468405
def preprocess(ops, nlp, rows, get_ids):
    """"""
    Xs = []
    ys = []
    for (text1, text2), label in rows:
        Xs.append((get_ids([nlp(text1)])[0], get_ids([nlp(text2)])[0]))
        ys.append(label)
    return Xs, ops.asarray(ys, dtype="float32")
824807
def p_iteration_statement_3(self, p):
        
        def wrap(node, key):
            if node is None:
                # work around bug with yacc tracking of empty elements
                # by using the previous token, and increment the
                # positions
                node = self.asttypes.EmptyStatement(';')
                node.setpos(p, key - 1)
                node.lexpos += 1
                node.colno += 1
            else:
                node = self.asttypes.ExprStatement(expr=node)
                node.setpos(p, key)
            return node

        if len(p) == 10:
            p[0] = self.asttypes.For(
                init=wrap(p[3], 3), cond=wrap(p[5], 5),
                count=p[7], statement=p[9])
        else:
            init = self.asttypes.VarStatement(p[4])
            init.setpos(p, 3)
            p[0] = self.asttypes.For(
                init=init, cond=wrap(p[6], 6), count=p[8], statement=p[10])
        p[0].setpos(p)
713459
private Tuple3<ReadOnlyStyledDocument<PS, SEG, S>, RichTextChange<PS, SEG, S>, MaterializedListModification<Paragraph<PS, SEG, S>>> replace(
            BiIndex start, BiIndex end, UnaryOperator<ReadOnlyStyledDocument<PS, SEG, S>> f) {
        int pos = tree.getSummaryBetween(0, start.major).map(s -> s.length() + 1).orElse(0) + start.minor;

        List<Paragraph<PS, SEG, S>> removedPars =
                getParagraphs().subList(start.major, end.major + 1);

        return end.map(this::split).map((l0, r) -> {
            return start.map(l0::split).map((l, removed) -> {
                ReadOnlyStyledDocument<PS, SEG, S> replacement = f.apply(removed);
                ReadOnlyStyledDocument<PS, SEG, S> doc = l.concatR(replacement).concat(r);
                RichTextChange<PS, SEG, S> change = new RichTextChange<>(pos, removed, replacement);
                List<Paragraph<PS, SEG, S>> addedPars = doc.getParagraphs().subList(start.major, start.major + replacement.getParagraphCount());
                MaterializedListModification<Paragraph<PS, SEG, S>> parChange =
                        MaterializedListModification.create(start.major, removedPars, addedPars);
                return t(doc, change, parChange);
            });
        });
    }