Given a Flask response, find the rdflib Graph
344772
def get_graph(cls, response):
		
		if cls.is_graph(response):	# single graph object
			return response

		if hasattr(response, '__getitem__'):	# indexable tuple
			if len(response) > 0 and \
			   cls.is_graph(response[0]):	# graph object
				return response[0]
623335
def Parse(self, persistence, knowledge_base, download_pathtype):
    """"""
    pathspecs = []

    if isinstance(persistence, rdf_client.OSXServiceInformation):
      if persistence.program:
        pathspecs = rdf_paths.PathSpec(
            path=persistence.program, pathtype=download_pathtype)
      elif persistence.args:
        pathspecs = rdf_paths.PathSpec(
            path=persistence.args[0], pathtype=download_pathtype)

    for pathspec in pathspecs:
      yield rdf_standard.PersistenceFile(pathspec=pathspec)
361171
def grab_rdflib_graph_version(g: Graph) -> str:
        '''  '''
        version = g.subject_objects( predicate = URIRef( OWL.versionIRI ) )
        version = [o for s, o in version]
        if len(version) != 1:
            print('versioning isn\'t correct')
        else:
            version = str(version[0])
            return version
1313153
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
			return self.rdflib_graph.serialize(format=aformat)
1243421
def parse_binary(self):

		'''
		
		'''

		# derive mimetype
		self.mimetype = self.resource.rdf.graph.value(
			self.resource.uri,
			self.resource.rdf.prefixes.ebucore.hasMimeType).toPython()

		# get binary content as stremable response
		self.data = self.resource.repo.api.http_request(
			'GET',
			self.resource.uri,
			data=None,
			headers={'Content-Type':self.resource.mimetype},
			is_rdf=False,
			stream=True)
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')
1166727
def _load(self, graph, source):
        """"""
        try:
            return graph.load(source)
        except:
            pass
        try:
            return graph.load(source, format='n3')
        except:
            pass
        try:
            return graph.load(source, format='nt')
        except:
            raise Exception("Could not load {} as either RDF/XML, N3 or NTriples".format(source))
1357270
def fetch_internal(item, request):
    """"""
    # Break client dependence on Flask if internal fetches aren't being used.
    from flask import make_response
    from werkzeug.test import EnvironBuilder
    # Break circular dependencies.
    from dpxdt.server import app

    # Attempt to create a Flask environment from a urllib2.Request object.
    environ_base = {
        'REMOTE_ADDR': '127.0.0.1',
    }

    # The data object may be a generator from poster.multipart_encode, so we
    # need to convert that to raw bytes here. Unfortunately EnvironBuilder
    # only works with the whole request buffered in memory.
    data = request.get_data()
    if data and not isinstance(data, str):
        data = ''.join(list(data))

    builder = EnvironBuilder(
        path=request.get_selector(),
        base_url='%s://%s' % (request.get_type(), request.get_host()),
        method=request.get_method(),
        data=data,
        headers=request.header_items(),
        environ_base=environ_base)

    with app.request_context(builder.get_environ()):
        response = make_response(app.dispatch_request())
        LOGGER.info('"%s" %s via internal routing',
                    request.get_selector(), response.status_code)
        item.status_code = response.status_code
        item.content_type = response.mimetype
        if item.result_path:
            # TODO: Is there a better way to access the response stream?
            with open(item.result_path, 'wb') as result_file:
                for piece in response.iter_encoded():
                    result_file.write(piece)
        else:
            item.data = response.get_data()

    return item
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
620981
def getrdfdata():
	
	if not os.path.exists(RDFFILES):
		_, _ = urllib.urlretrieve(RDFURL, RDFFILES)
	with tarfile.open(RDFFILES) as archive:
		for tarinfo in archive:
			yield ElementTree.parse(archive.extractfile(tarinfo))
355914
def _parse_rdf(self, file):
        
        store = Graph()
        store.parse(file)

        print len(store)
823291
def get_paginated_response(self, data):
        
        metadata = {
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'count': self.get_result_count(),
            'num_pages': self.get_num_pages(),
        }
        if isinstance(data, dict):
            if 'results' not in data:
                raise TypeError(u'Malformed result dict')
            data['pagination'] = metadata
        else:
            data = {
                'results': data,
                'pagination': metadata,
            }
        return Response(data)
468143
def load_uri(self, uri, verbose):
        

        if verbose: printDebug("----------")
        if verbose: printDebug("Reading: <%s>" % uri)
        success = False
        for f in self.rdf_format_opts:
            if verbose: printDebug(".. trying rdf serialization: <%s>" % f)
            try:
                self.rdfgraph.parse(uri, format=f)
                if verbose: printDebug("..... success!", bold=True)
                success = True
                self.sources_valid += [uri]
                break
            except:
                if verbose: printDebug("..... failed")

        if not success == True:
            self.loading_failed(self.rdf_format_opts)
            self.sources_invalid += [uri]
85895
def query(self):
        '''  '''
        get = self.environ['bottle.get'] = FormsDict()
        pairs = _parse_qsl(self.environ.get('QUERY_STRING', ''))
        if len(pairs) > self.MAX_PARAMS:
            raise HTTPError(413, 'Too many parameters')
        for key, value in pairs:
            get[key] = value
        return get
309813
def link(g: Graph, subject: Node, predicate: URIRef) -> Tuple[Optional[URIRef], Optional[URIRef]]:
    
    link_node = g.value(subject, predicate)
    if link_node:
        l = g.value(link_node, FHIR.link)
        if l:
            typ = g.value(l, RDF.type)
            return l, typ
    return None, None
1338488
def _rdf_graph_from_ntriples_string(ntriples_string, graph=nil)
      graph ||= RDF::Graph.new
      RDF::Reader.for(:ntriples).new(ntriples_string) do |reader|
        reader.each_statement do |statement|
          graph << statement
        end
      end
      graph
    end
593076
def _construct_query_for_uris_and_graphs(uris_and_graphs)
      value_pairs = uris_and_graphs.map do |(uri, graph)|
        u = RDF::URI.new(uri).to_base
        g = graph ? RDF::URI.new(graph).to_base : 'UNDEF'
        "(#{u} #{g})"
      end
      query = "CONSTRUCT { ?uri ?p ?o . #{ self.all_triples_construct("?uri") }} WHERE { GRAPH ?g { ?uri ?p ?o . #{ self.all_triples_where("?uri") } VALUES (?uri ?g) { #{ value_pairs.join(' ') } } } }"
    end