/*
Convert inputstream in owl/rdf format to outputsream in jsonld format
430802
public void convertToJsonld(InputStream in, OutputStream os)
			throws IOException {
		
		File inputProcessedFile = preProcessFile(in);
		LOG.info("OWl File processed successfully ");
		
		// print current time
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		LOG.info("Conversion RDF to JSONLD started "
				+ sdf.format(Calendar.getInstance().getTime()));

		// create an empty model
		Model modelJena = ModelFactory.createDefaultModel();
		InputStream internalInputStream = new FileInputStream(inputProcessedFile);
		// read the RDF/XML file
		RDFDataMgr.read(modelJena, internalInputStream, Lang.RDFXML);
		LOG.info("Read into Model finished " + sdf.format(Calendar.getInstance().getTime()));

		try { //close quietly and delete the temp. input file
			internalInputStream.close();
			inputProcessedFile.delete();
		} catch(Exception e) {}

		RDFDataMgr.write(os, modelJena, Lang.JSONLD);
		LOG.info("Conversion RDF to JSONLD finished " + sdf.format(Calendar.getInstance().getTime()));
		LOG.info(" JSONLD file " + " is written successfully.");

		try { //close, flush quietly
			os.close();
		} catch(Exception e) {}
	}
1174041
def MapByteStream(self, byte_stream, **unused_kwargs):  # pylint: disable=redundant-returns-doc
    
    raise errors.MappingError(
        'Unable to map {0:s} data type to byte stream'.format(
            self._data_type_definition.TYPE_INDICATOR))
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;
	}
497884
private static Stream<String> nodeToStringStream(final org.apache.jena.graph.Node object) {
        if (object.isURI()) {
            return of(object.getURI());
        } else if (object.isLiteral()) {
            return of(object.getLiteralValue().toString());
        } else {
            return empty();
        }
    }
782029
def get_string_from_rdf(src):
    
    res = src.split("/") #[:-1]
    return "".join([l.replace('"', '""') for l in res[len(res) - 1]])
733170
def get_stream(self, rel_path, cb=None, return_meta=False):
        """"""
        from boto.s3.key import Key
        from boto.exception import S3ResponseError

        import StringIO
        from . import MetadataFlo

        b = StringIO.StringIO()
        try:
            k = self._get_boto_key(rel_path)
            if not k:
                return None

            k.get_contents_to_file(b, cb=cb, num_cb=100)

            b.seek(0)

            if return_meta:
                d = k.metadata
                d['size'] = k.size
                d['etag'] = k.etag
            else:
                d = {}

            return MetadataFlo(b, d)

        except S3ResponseError as e:
            if e.status == 404:
                return None
            else:
                raise e
1256830
def format_sparql(item, dt_format='turtle', **kwargs):
    
    try:
        rtn_val = json.dumps(item.value)
        rtn_val = item.value
    except:
        if 'time' in item.class_type.lower() \
                or 'date' in item.class_type.lower():
            rtn_val = item.value.isoformat()
        else:
            rtn_val = str(item.value)
    if hasattr(item, "datatype"):
        if hasattr(item, "lang") and item.lang:
            rtn_val = '%s@%s' % (json.dumps(rtn_val), item.lang)
        else:
            dt = item.datatype
            if dt_format == "uri":
                dt = item.datatype.sparql_uri
            if item.datatype in ["xsd_string",
                                 "xsd_dateTime",
                                 "xsd_time",
                                 "xsd_date"]:
                rtn_val = json.dumps(rtn_val)
            else:
                rtn_val = '"%s"' % json.dumps(rtn_val)
            rtn_val = '%s^^%s' % (rtn_val, dt.sparql)
    return rtn_val
211689
function MetaCharsetReplacerStream(options) {
    options = options || {};
    this.encoding = options.encoding = 'utf8'; // this is the *output* encoding
    options.decodeStrings = false; // don't turn my strings back into a buffer!
    Transform.call(this, options);
}
1200086
def parse_rdf_payload(self, data, headers):

		'''
		
		'''

		# handle edge case for content-types not recognized by rdflib parser
		if headers['Content-Type'].startswith('text/plain'):
			logger.debug('text/plain Content-Type detected, using application/n-triples for parser')
			parse_format = 'application/n-triples'
		else:
			parse_format = headers['Content-Type']

		# clean parse format for rdf parser (see: https://www.w3.org/2008/01/rdf-media-types)
		if ';charset' in parse_format:
			parse_format = parse_format.split(';')[0]

		# parse graph
		graph = rdflib.Graph().parse(
			data=data.decode('utf-8'),
			format=parse_format)

		# return graph
		return graph
355914
def _parse_rdf(self, file):
        
        store = Graph()
        store.parse(file)

        print len(store)
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
1179606
private void readFromStream(InputStream in) throws IOException {
        document = DocumentFactory.newDocument(Json.read(in));
    }
1296657
private static List<Map<String, String>> loadWords(InputStream stream) {
    List<Map<String, String>> list = new ArrayList<>();
    try (
      InputStreamReader isr = new InputStreamReader(stream, FILE_ENCODING);
      BufferedReader br = new BufferedReader(isr);
    ) {
      String line;

      Tokenizer wordTokenizer = new Breton().getWordTokenizer();
      while ((line = br.readLine()) != null) {
        line = line.trim();
        if (line.isEmpty() || line.charAt(0) == '#') { // ignore comments
          continue;
        }
        String[] parts = line.split("=");
        if (parts.length != 2) {
          throw new IOException("Format error in file "
                  + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(FILE_NAME)
                  + ", line: " + line);
        }
        String[] wrongForms = parts[0].split("\\|"); // multiple incorrect forms
        for (String wrongForm : wrongForms) {
          int wordCount = 0;
          List<String> tokens = wordTokenizer.tokenize(wrongForm);
          for (String token : tokens) {
            if (!StringTools.isWhitespace(token)) {
              wordCount++;
            }
          }
          // grow if necessary
          for (int i = list.size(); i < wordCount; i++) {
            list.add(new HashMap<>());
          }
          list.get(wordCount - 1).put(wrongForm, parts[1]);
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    // seal the result (prevent modification from outside this class)
    List<Map<String,String>> result = new ArrayList<>();
    for (Map<String, String> map : list) {
      result.add(Collections.unmodifiableMap(map));
    }
    return Collections.unmodifiableList(result);
  }
677062
public void write(OutputStream os) throws Exception {
        try {
            JenaR2RMLMappingManager mm = JenaR2RMLMappingManager.getInstance();
            Collection<TriplesMap> tripleMaps = getTripleMaps();

            final JenaGraph jenaGraph = mm.exportMappings(tripleMaps);
            final Graph graph = new JenaRDF().asJenaGraph(jenaGraph);

            final PrefixMapping jenaPrefixMapping = graph.getPrefixMapping();
            prefixmng.getPrefixMap()
                    .forEach((s, s1) ->
                            jenaPrefixMapping.setNsPrefix(
                                    s.substring(0, s.length()-1) // remove the last ":" from the prefix
                                    , s1));
            jenaPrefixMapping.setNsPrefix("rr", "http://www.w3.org/ns/r2rml#");

            RDFWriter.create()
                    .lang(Lang.TTL)
                    .format(RDFFormat.TURTLE_PRETTY)
                    .source(graph)
                    .output(os);

            // use Jena to output pretty turtle syntax
            //RDFDataMgr.write(os, graph, org.apache.jena.riot.RDFFormat.TURTLE_PRETTY);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
543625
function jsonEncoder(input, path) {
    var output = new Stream();
    output.readable = true;
    var first = true;
    input.on("data", function (entry) {
      if (path) {
        entry.href = path + entry.name;
        var mime = entry.linkStat ? entry.linkStat.mime : entry.mime;
        if (mime && mime.match(/(directory|folder)$/)) {
          entry.href += "/";
        }
      }
      if (first) {
        output.emit("data", "[\n  " + JSON.stringify(entry));
        first = false;
      } else {
        output.emit("data", ",\n  " + JSON.stringify(entry));
      }
    });
    input.on("end", function () {
      if (first) output.emit("data", "[]");
      else output.emit("data", "\n]");
      output.emit("end");
    });
    if (input.pause) {
      output.pause = function () {
        input.pause();
      };
    }
    if (input.resume) {
      output.resume = function () {
        input.resume();
      };
    }
    return output;
  }
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)
596763
function Stream( arr, options ) {
		if ( !Array.isArray( arr ) ) {
			throw new TypeError( 'Stream()::invalid input argument. First argument must be an array.' );
		}
		if ( arguments.length < 2 ) {
			options = {};
		}
		if ( !( this instanceof Stream ) ) {
			return new Stream( arr, options );
		}
		var err = validate( options );
		if ( err ) {
			throw err;
		}
		setOptions( options );
		Readable.call( this, options );
		this._array = arr.slice();
		this._destroyed = false;
		this._enc = options.encoding;
		this._mode = options.objectMode;
		return this;
	}