Converts given RDFValue to an RDFURN of a file to be downloaded.
482415
def CollectionItemToAff4Path(item, client_id=None):
  """"""
  if isinstance(item, rdf_flows.GrrMessage):
    client_id = item.source
    item = item.payload
  elif isinstance(item, rdf_flow_objects.FlowResult):
    client_id = item.client_id
    item = item.payload

  if not client_id:
    raise ValueError("Could not determine client_id.")
  elif isinstance(client_id, string_types):
    client_id = rdf_client.ClientURN(client_id)

  if isinstance(item, rdf_client_fs.StatEntry):
    return item.AFF4Path(client_id)
  elif isinstance(item, rdf_file_finder.FileFinderResult):
    return item.stat_entry.AFF4Path(client_id)
  elif isinstance(item, collectors.ArtifactFilesDownloaderResult):
    if item.HasField("downloaded_file"):
      return item.downloaded_file.AFF4Path(client_id)

  raise ItemNotExportableError(item)
1364266
public RDFDataset toRDF() throws JsonLdError {
        // TODO: make the default generateNodeMap call (i.e. without a
        // graphName) create and return the nodeMap
        final Map<String, Object> nodeMap = newMap();
        nodeMap.put(JsonLdConsts.DEFAULT, newMap());
        generateNodeMap(this.value, nodeMap);

        final RDFDataset dataset = new RDFDataset(this);

        for (final String graphName : nodeMap.keySet()) {
            // 4.1)
            if (JsonLdUtils.isRelativeIri(graphName)) {
                continue;
            }
            final Map<String, Object> graph = (Map<String, Object>) nodeMap.get(graphName);
            dataset.graphToRDF(graphName, graph);
        }

        return dataset;
    }
487386
def Graph2Pandas_converter(self):
        ''''''

        if isinstance(self.path, str) or isinstance(self.path, p):
            self.path = str(self.path)
            filetype = p(self.path).suffix
            if filetype == '.pickle':
                self.g = pickle.load(open(self.path, 'rb'))
                if isinstance(self.g, rdflib.graph.Graph):
                    return self.get_sparql_dataframe()
                else:
                    print('WARNING:: function df() wont work unless an ontology source is loaded')
                    return self.g
            elif filetype == '.ttl' or filetype == '.rdf':
                self.g = rdflib.Graph()
                self.g.parse(self.path, format='turtle')
                return self.get_sparql_dataframe()
            elif filetype == '.nt':
                self.g = rdflib.Graph()
                self.g.parse(self.path, format='nt')
                return self.get_sparql_dataframe()
            elif filetype == '.owl' or filetype == '.xrdf':
                self.g = rdflib.Graph()
                try:
                    self.g.parse(self.path, format='xml')
                except:
                    # some owl formats are more rdf than owl
                    self.g.parse(self.path, format='turtle')
                return self.get_sparql_dataframe()
            else:
                exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')
            try:
                return self.get_sparql_dataframe()
                self.path = None
            except:
                exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')

        elif isinstance(self.g, rdflib.graph.Graph):
            self.path = None
            return self.get_sparql_dataframe()

        else:
            exit('Obj given is not str, pathlib obj, or an rdflib.Graph()')
1200616
def load_from_rdf_file(self, rdf_file):
        
        self.graph = rdflib.Graph()
        self.graph.parse(os.path.abspath(rdf_file), format='nt')
        self.initialize()
301702
function _typedParse(loc, type, data, callback) {
  switch(type.toLowerCase()) {
    case 'text':
    case 'plain':
    case 'text/plain':
      callback(null, data);
      break;
    case 'json':
    case 'jsonld':
    case 'json-ld':
    case 'ld+json':
    case 'application/json':
    case 'application/ld+json':
      try {
        callback(null, JSON.parse(data));
      }
      catch(ex) {
        callback({
          message: 'Error parsing JSON.',
          contentType: type,
          url: loc,
          exception: ex.toString()
        });
      }
      break;
    case 'xml':
    case 'html':
    case 'xhtml':
    case 'text/html':
    case 'application/xhtml+xml':
      if(typeof jsdom === 'undefined') {
        callback({
          message: 'jsdom module not found.',
          contentType: type,
          url: loc
        });
        break;
      }
      if(typeof RDFa === 'undefined') {
        callback({
          message: 'RDFa module not found.',
          contentType: type,
          url: loc
        });
        break;
      }
      // input is RDFa
      try {
        jsdom.env({
          html: data,
          done: function(errors, window) {
            if(errors && errors.length > 0) {
              return callback({
                message: 'DOM Errors:',
                errors: errors,
                url: loc
              });
            }

            try {
              // extract JSON-LD from RDFa
              RDFa.attach(window.document);
              jsonld.fromRDF(window.document.data,
                {format: 'rdfa-api'}, callback);
            }
            catch(ex) {
              // FIXME: expose RDFa/jsonld ex?
              callback({
                message: 'RDFa extraction error.',
                contentType: type,
                url: loc
              });
            }
          }
        });
      }
      catch(ex) {
        // FIXME: expose jsdom(?) ex?
        callback({
          message: 'jsdom error.',
          contentType: type,
          url: loc
        });
      }
      break;
    default:
      callback({
        message: 'Unknown Content-Type.',
        contentType: type,
        url: loc
      });
  }
}
675131
def fundrefxml2json(self, node):
        """"""
        doi = FundRefDOIResolver.strip_doi_host(self.get_attrib(node,
                                                'rdf:about'))
        oaf_id = FundRefDOIResolver().resolve_by_doi(
            "http://dx.doi.org/" + doi)
        name = node.find('./skosxl:prefLabel/skosxl:Label/skosxl:literalForm',
                         namespaces=self.namespaces).text
        # Extract acronyms
        acronyms = []
        for n in node.findall('./skosxl:altLabel/skosxl:Label',
                              namespaces=self.namespaces):
            usagenode = n.find('./fref:usageFlag', namespaces=self.namespaces)
            if usagenode is not None:
                if self.get_attrib(usagenode, 'rdf:resource') == \
                        ('http://data.crossref.org/fundingdata'
                         '/vocabulary/abbrevName'):
                    label = n.find('./skosxl:literalForm',
                                   namespaces=self.namespaces)
                    if label is not None:
                        acronyms.append(label.text)

        parent_node = node.find('./skos:broader', namespaces=self.namespaces)
        if parent_node is None:
            parent = {}
        else:
            parent = {
                "$ref": self.get_attrib(parent_node, 'rdf:resource'),
            }
        country_elem = node.find('./svf:country', namespaces=self.namespaces)
        country_url = self.get_attrib(country_elem, 'rdf:resource')
        country_code = self.cc_resolver.cc_from_url(country_url)
        type_ = node.find('./svf:fundingBodyType',
                          namespaces=self.namespaces).text
        subtype = node.find('./svf:fundingBodySubType',
                            namespaces=self.namespaces).text
        country_elem = node.find('./svf:country', namespaces=self.namespaces)

        modified_elem = node.find('./dct:modified', namespaces=self.namespaces)
        created_elem = node.find('./dct:created', namespaces=self.namespaces)

        json_dict = {
            '$schema': self.schema_formatter.schema_url,
            'doi': doi,
            'identifiers': {
                'oaf': oaf_id,
            },
            'name': name,
            'acronyms': acronyms,
            'parent': parent,
            'country': country_code,
            'type': type_,
            'subtype': subtype.lower(),
            'remote_created': (created_elem.text if created_elem is not None
                               else None),
            'remote_modified': (modified_elem.text if modified_elem is not None
                                else None),
        }
        return json_dict
98605
public Value createValue(final ValueFactory valueFactory, final RDFNode data, final int type)
        throws RepositoryException {
        assert (valueFactory != null);


        if (type == UNDEFINED || type == STRING) {
            return valueConverter.reverse().convert(data);
        } else if (type == REFERENCE || type == WEAKREFERENCE) {
            // reference to another node (by path)
            if (!data.isURIResource()) {
                throw new ValueFormatException("Reference properties can only refer to URIs, not literals");
            }

            try {
                final Node nodeFromGraphSubject = getJcrNode(idTranslator.convert(data.asResource()));
                return valueFactory.createValue(nodeFromGraphSubject, type == WEAKREFERENCE);
            } catch (final RepositoryRuntimeException e) {
                throw new MalformedRdfException("Unable to find referenced node", e);
            }
        } else if (data.isResource()) {
            LOGGER.debug("Using default JCR value creation for RDF resource: {}",
                    data);
            return valueFactory.createValue(data.asResource().getURI(), type);
        } else {
            LOGGER.debug("Using default JCR value creation for RDF literal: {}",
                    data);

            // If the date time stamp has a ms field which is a multiple of 10 (ie, .5 or .86) and is truncated to
            // one or two characters, then Modeshape 5.0 will incorrectly parse the timestamp
            // and pad the number incorrectly: ie. .5 ms becomes .005 ms, .86 becomes .086), thereby changing the
            // time stamp.  All this does is make the ms section 3 digits and then Modeshape behaves.
            String theValue = data.asLiteral().getString();

            if (type == DATE) {
                theValue = Instant.parse(data.asLiteral().getString()).toString();
            }
            return valueFactory.createValue(theValue, type);
        }
    }
1074936
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"
977192
def process_file(self,filename=None, format=None):
        
        rdfgraph = rdflib.Graph()
        if format is None:
            if filename.endswith(".ttl"):
                format='turtle'
            elif filename.endswith(".rdf"):
                format='xml'
        rdfgraph.parse(filename, format=format)
        return self.process_rdfgraph(rdfgraph)
748887
def load_rdf(self,
                 uri_or_path=None,
                 data=None,
                 file_obj=None,
                 rdf_format="",
                 verbose=False,
                 hide_base_schemas=True,
                 hide_implicit_types=True,
                 hide_implicit_preds=True):
        """"""
        loader = RDFLoader(verbose=verbose)
        loader.load(uri_or_path, data, file_obj, rdf_format)
        self.rdflib_graph = loader.rdflib_graph
        self.sources = loader.sources_valid
        self.sparqlHelper = SparqlHelper(self.rdflib_graph)
        self.namespaces = sorted(self.rdflib_graph.namespaces())
789666
def user_to_rdf(user, graph=None):
    '''
    
    '''
    graph = graph or Graph(namespace_manager=namespace_manager)
    if user.id:
        user_url = url_for('users.show_redirect',
                           user=user.id,
                           _external=True)
        id = URIRef(user_url)
    else:
        id = BNode()
    o = graph.resource(id)
    o.set(RDF.type, FOAF.Person)
    o.set(FOAF.name, Literal(user.fullname))
    o.set(RDFS.label, Literal(user.fullname))
    if user.website:
        o.set(FOAF.homepage, URIRef(user.website))
    return o
303583
def rdf_node_from(source)
      case source
      when NilClass
        nil
      when Node
        Redland.librdf_new_node_from_node(source.rdf_node)
      else
        Redland.librdf_new_node_from_node(Node.new(source).rdf_node)
      end
    end
486684
def parse(self, xmp):
        """"""
        tree = etree.fromstring(xmp)
        rdf_tree = tree.find(RDF_NS + 'RDF')
        meta = defaultdict(dict)
        for desc in rdf_tree.findall(RDF_NS + 'Description'):
            for el in desc.getchildren():
                ns, tag = self._parse_tag(el)
                value = self._parse_value(el)
                meta[ns][tag] = value
        return dict(meta)
718629
function RDFMakeTerm(formula,val, canonicalize) {
	    if (typeof val != 'object') {   
		if (typeof val == 'string')
	            return new N3Parser.Literal(val);
		if (typeof val == 'number')
		    return new N3Parser.Literal(val); // @@ differet types
		if (typeof val == 'boolean')
		    return new N3Parser.Literal(val?"1":"0", undefined, 
					    N3Parser.Symbol.prototype.XSDboolean);
		else if (typeof val == 'number')
	            return new N3Parser.Literal(''+val);   // @@ datatypes
		else if (typeof val == 'undefined')
	            return undefined;
		else    // @@ add converting of dates and numbers
	            throw "Can't make Term from " + val + " of type " + typeof val; 
	    }
	    return val;
	}
55052
def RDFValueToBigQuerySchema(self, value):
    """"""
    fields_array = []
    for type_info in value.__class__.type_infos:
      # Nested structures are indicated by setting type "RECORD"
      if type_info.__class__.__name__ == "ProtoEmbedded":
        fields_array.append({
            "name": type_info.name,
            "type": "RECORD",
            "description": type_info.description,
            "fields": self.RDFValueToBigQuerySchema(value.Get(type_info.name))
        })
      else:
        # If we don't have a specific map use string.
        bq_type = self.RDF_BIGQUERY_TYPE_MAP.get(type_info.proto_type_name,
                                                 None) or "STRING"

        # For protos with RDF types we need to do some more checking to properly
        # covert types.
        if hasattr(type_info, "original_proto_type_name"):
          if type_info.original_proto_type_name in [
              "RDFDatetime", "RDFDatetimeSeconds"
          ]:
            bq_type = "TIMESTAMP"
          elif type_info.proto_type_name == "uint64":
            # This is to catch fields like st_mode which are stored as ints but
            # exported as more useful strings. Things which are just plain ints
            # won't have an RDF type specified and so will be exported as
            # INTEGER
            bq_type = "STRING"

        fields_array.append({
            "name": type_info.name,
            "type": bq_type,
            "description": type_info.description
        })
    return fields_array
782029
def get_string_from_rdf(src):
    
    res = src.split("/") #[:-1]
    return "".join([l.replace('"', '""') for l in res[len(res) - 1]])
1123910
private static OWLValueObject buildFromClasAndObject(OWLModel model, OWLURIClass uriClass, Object object) throws NotYetImplementedException, OWLTranslationException {
        // if object is a primitive data type:
        if (object.getClass().isPrimitive() || object instanceof String) {
            return new OWLValueObject(model, uriClass, model.createDataValue(object, uriClass.getURI()));
        }
        // if object uses jenabeans:
        if (ObjectOWLSTranslator.isJenaBean(object)) {
            try {
                return new OWLValueObject(
                        model,
                        uriClass,
                        model.createIndividual(uriClass.getURI(), new URI(ObjectOWLSTranslator.beanToJenaResource(model, object).getURI())));
            } catch (URISyntaxException ex) {
                throw new OWLTranslationException("translating to Jena: ", ex);
            }
        }
        throw new NotYetImplementedException("new " + OWLValueObject.class.toString() + " from a non-primitive object");
    }