note: requires SPARQL 1.1
        2015-06-04: currenlty not used, inferred from above
514984
def getClassAllSubs(self, aURI):
        
        aURI = aURI
        try:
            qres = self.rdflib_graph.query("""SELECT DISTINCT ?x
                     WHERE {
                         { ?x rdfs:subClassOf+ <%s> }
                         FILTER (!isBlank(?x))
                     }
                     """ % (aURI))
        except:
            printDebug(
                "... warning: the 'getClassAllSubs' query failed (maybe missing SPARQL 1.1 support?)"
            )
            qres = []
        return list(qres)
741505
def dataset_from_rdf(graph, dataset=None, node=None):
    '''
    
    '''
    dataset = dataset or Dataset()

    if node is None:  # Assume first match is the only match
        node = graph.value(predicate=RDF.type, object=DCAT.Dataset)

    d = graph.resource(node)

    dataset.title = rdf_value(d, DCT.title)
    dataset.description = sanitize_html(d.value(DCT.description))
    dataset.frequency = frequency_from_rdf(d.value(DCT.accrualPeriodicity))

    acronym = rdf_value(d, SKOS.altLabel)
    if acronym:
        dataset.acronym = acronym

    tags = [tag.toPython() for tag in d.objects(DCAT.keyword)]
    tags += [theme.toPython() for theme in d.objects(DCAT.theme)]
    dataset.tags = list(set(tags))

    identifier = rdf_value(d, DCT.identifier)
    if identifier:
        dataset.extras['dct:identifier'] = identifier

    if isinstance(d.identifier, URIRef):
        dataset.extras['uri'] = d.identifier.toPython()

    dataset.temporal_coverage = temporal_from_rdf(d.value(DCT.temporal))

    licenses = set()
    for distrib in d.objects(DCAT.distribution | DCAT.distributions):
        resource_from_rdf(distrib, dataset)
        for predicate in DCT.license, DCT.rights:
            value = distrib.value(predicate)
            if isinstance(value, (URIRef, Literal)):
                licenses.add(value.toPython())
            elif isinstance(value, RdfResource):
                licenses.add(value.identifier.toPython())

    default_license = dataset.license or License.default()
    dataset.license = License.guess(*licenses, default=default_license)

    return dataset
221693
def GetArtifactParserDependencies(rdf_artifact):
  
  deps = set()
  processors = parser.Parser.GetClassesByArtifact(rdf_artifact.name)
  for p in processors:
    deps.update(p.knowledgebase_dependencies)
  return deps
1363265
def known(self, node):
        
        ref = node.get('type', Namespace.xsins)
        if ref is None:
            return None
        qref = qualify(ref, node, node.namespace())
        query = BlindQuery(qref)
        return query.execute(self.schema)
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)
996046
function prepareDataSources(attrNode, context) {
    Object.keys(attrNode.dataSources).forEach(dataSourceName => {
        const dataSource = attrNode.dataSources[dataSourceName];

        // DataSources with inherit="true" may have no type - so no prepare here:
        if (!dataSource.type) return;

        let dataSourceAttributes = context.dataSourceAttributes[dataSourceName];
        const dataSourceInstance = context.dataSources[dataSource.type];

        if (!dataSourceInstance) {
            throw new ImplementationError('Invalid DataSource type "' + dataSource.type + '"' + context.errorContext);
        }

        if (dataSource.joinParentKey && dataSource.joinChildKey) {
            const errorContext = context.errorContext;
            context.errorContext = ' in joinParentKey' + errorContext;
            dataSource.resolvedJoinParentKey = resolveKey(
                dataSource.joinParentKey,
                attrNode,
                {
                    neededDataSources: [dataSourceName],
                    allowMultiValued: false
                },
                context
            );
            dataSource.resolvedJoinParentKey = dataSource.resolvedJoinParentKey[dataSourceName];

            context.errorContext = ' in joinChildKey' + errorContext;
            dataSource.resolvedJoinChildKey = resolveKey(
                dataSource.joinChildKey,
                attrNode,
                {
                    neededDataSources: [dataSourceName],
                    allowMultiValued: false
                },
                context
            );
            dataSource.resolvedJoinChildKey = dataSource.resolvedJoinChildKey[dataSourceName];
            context.errorContext = errorContext;
        }

        // make attributes unique:
        dataSourceAttributes = dataSourceAttributes.filter((value, index, self) => self.indexOf(value) === index);

        try {
            dataSourceInstance.prepare(dataSource, dataSourceAttributes);
        } catch (err) {
            err.message += context.errorContext;
            throw err;
        }
    });
}
1101503
function() {
    var collection = [];
    var scope = this;
    this.each(function() {
      var p = scope.parent(this[0]);
      if(p && p[0]) collection.push(p[0]);
    });
    return new SpahQL(collection);
  }
1287181
def GetKnowledgeBase(rdf_client_obj, allow_uninitialized=False):
  """"""
  if not allow_uninitialized:
    if rdf_client_obj is None:
      raise artifact_utils.KnowledgeBaseUninitializedError(
          "No client snapshot given.")
    if rdf_client_obj.knowledge_base is None:
      raise artifact_utils.KnowledgeBaseUninitializedError(
          "KnowledgeBase empty for %s." % rdf_client_obj.client_id)
    kb = rdf_client_obj.knowledge_base
    if not kb.os:
      raise artifact_utils.KnowledgeBaseAttributesMissingError(
          "KnowledgeBase missing OS for %s. Knowledgebase content: %s" %
          (rdf_client_obj.client_id, kb))
  if rdf_client_obj is None or rdf_client_obj.knowledge_base is None:
    return rdf_client.KnowledgeBase()

  version = rdf_client_obj.os_version.split(".")
  kb = rdf_client_obj.knowledge_base
  try:
    kb.os_major_version = int(version[0])
    if len(version) >= 1:
      kb.os_minor_version = int(version[1])
  except ValueError:
    pass

  return kb
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)
382973
def get_terms_in_subset(ont, subset):
    
    namedGraph = get_named_graph(ont)

    # note subsets have an unusual encoding
    query = """
    prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>
    SELECT ?c ? WHERE {{
    GRAPH <{g}>  {{
    ?c oboInOwl:inSubset ?s ;
       rdfs:label ?l
    FILTER regex(?s,'#{s}$','i')
    }}
    }}
    """.format(s=subset, g=namedGraph)
    bindings = run_sparql(query)
    return [(r['c']['value'],r['l']['value']) for r in bindings]
920321
function resolveRelations(attrNode, context) {
    if (attrNode.dataSources || attrNode.resource) {
        const parentResource = context.parentResource;
        let childResource = attrNode;

        context.errorContext = getErrorContext(!parentResource ? 'resource' : 'sub-resource', context);

        if (attrNode.resource) {
            if (!context.resourceConfigs[attrNode.resource]) {
                throw new ImplementationError('Unknown resource "' + attrNode.resource + '"' + context.errorContext);
            }
            childResource = context.resourceConfigs[attrNode.resource].config;
        }

        if (parentResource) {
            if (!('parentKey' in attrNode)) throw new ImplementationError('Missing parentKey' + context.errorContext);
            if (!('childKey' in attrNode)) throw new ImplementationError('Missing childKey' + context.errorContext);

            if (attrNode.parentKey === null) {
                attrNode.parentKey = _.cloneDeep(parentResource.primaryKey);
            }
            if (attrNode.childKey === null) {
                attrNode.childKey = _.cloneDeep(childResource.primaryKey);
            }

            if (attrNode.joinVia) {
                const joinViaDataSource = attrNode.dataSources[attrNode.joinVia];
                if (attrNode.parentKey.length !== joinViaDataSource.joinParentKey.length) {
                    throw new ImplementationError(
                        'Composite key length of parentKey (' +
                            attrNode.parentKey.length +
                            ') does not match joinParentKey length (' +
                            joinViaDataSource.joinParentKey.length +
                            ') ' +
                            'of DataSource "' +
                            attrNode.joinVia +
                            '"' +
                            context.errorContext
                    );
                }
                if (attrNode.childKey.length !== joinViaDataSource.joinChildKey.length) {
                    throw new ImplementationError(
                        'Composite key length of childKey (' +
                            attrNode.childKey.length +
                            ') does not match joinChildKey length (' +
                            joinViaDataSource.joinChildKey.length +
                            ') ' +
                            'of DataSource "' +
                            attrNode.joinVia +
                            '"' +
                            context.errorContext
                    );
                }
            } else if (attrNode.parentKey.length !== attrNode.childKey.length) {
                throw new ImplementationError(
                    'Composite key length of parentKey (' +
                        attrNode.parentKey.length +
                        ') does not match childKey length (' +
                        attrNode.childKey.length +
                        ')' +
                        context.errorContext
                );
            }

            const errorContext = context.errorContext;
            context.errorContext = ' in parentKey' + errorContext;
            attrNode.resolvedParentKey = resolveKey(
                attrNode.parentKey,
                parentResource,
                {
                    allowMultiValued: true
                },
                context
            );

            context.errorContext = ' in childKey' + errorContext;
            attrNode.resolvedChildKey = resolveKey(
                attrNode.childKey,
                childResource,
                {
                    neededDataSources: ['primary'],
                    allowMultiValued: false
                },
                context
            );
            context.errorContext = errorContext;
        }

        context.parentResource = attrNode;
    }

    if (attrNode.attributes) {
        Object.keys(attrNode.attributes).forEach(subAttrName => {
            const subAttrNode = attrNode.attributes[subAttrName];
            const subContext = Object.assign({}, context);
            subContext.attrPath = context.attrPath.concat([subAttrName]);

            resolveRelations(subAttrNode, subContext);
        });
    }
}
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]
1041605
private void fetchSubclassHierarchy() throws IOException {
		System.out.println("Fetching subclass relationships from SPARQL ...");
		try (InputStream response = runSparqlQuery("PREFIX ps: <http://www.wikidata.org/prop/statement/>\n"
				+ "PREFIX p: <http://www.wikidata.org/prop/>\n"
				+ "SELECT ?subC ?supC WHERE { ?subC p:P279/ps:P279 ?supC }")) {
			System.out.println("Processing subclass relationships ...");

			// DEBUG
			// BufferedReader br = new BufferedReader(new InputStreamReader(
			// response));
			// String read;
			// while ((read = br.readLine()) != null) {
			// System.out.println(read);
			// }
			// System.out.println("*** done ***");

			ObjectMapper mapper = new ObjectMapper();
			JsonNode root = mapper.readTree(response);
			JsonNode bindings = root.path("results").path("bindings");
			int count = 0;
			for (JsonNode binding : bindings) {
				count++;
				Integer subId = getNumId(binding.path("subC").path("value")
						.asText(), true);
				Integer supId = getNumId(binding.path("supC").path("value")
						.asText(), true);
				if (supId == 0 || subId == 0) {
					System.out.println("Ignoring "
							+ binding.path("subC").path("value").asText()
							+ " subClassOf "
							+ binding.path("supC").path("value").asText());
					continue;
				}
				getClassRecord(subId).directSuperClasses.add(supId);
				ClassRecord superClass = getClassRecord(supId);
				superClass.subclassCount++;
				if (count % 10000 == 0) {
					System.out.print("*");
				}
			}
			System.out.println("Found " + count
					+ " subclass relationships among "
					+ this.classRecords.size() + " Wikidata items.");

			System.out.println("Computing indirect subclass relationships ...");
			for (ClassRecord classRecord : this.classRecords.values()) {
				for (Integer superClass : classRecord.directSuperClasses) {
					addSuperClasses(superClass, classRecord);
				}
			}

			System.out.println("Computing total subclass counts ...");
			for (ClassRecord classRecord : this.classRecords.values()) {
				for (Integer superClass : classRecord.superClasses) {
					getClassRecord(superClass).allSubclassCount++;
				}
			}

			System.out.println("Preprocessing of class hierarchy complete.");
		}
	}
205100
@Override
    public void updateProperties(final IdentifierConverter<Resource, FedoraResource> idTranslator,
                                 final String sparqlUpdateStatement, final RdfStream originalTriples)
            throws MalformedRdfException, AccessDeniedException {

        final Model model = originalTriples.collect(toModel());

        final FedoraResource described = getDescribedResource();
        final String describedURI = idTranslator.reverse().convert(described).toString();

        final UpdateRequest request = create(sparqlUpdateStatement, describedURI);

        final Collection<ConstraintViolationException> errors = validateUpdateRequest(request);

        final NamespaceRegistry namespaceRegistry = getNamespaceRegistry(getSession());

        request.getPrefixMapping().getNsPrefixMap().forEach(
            (k,v) -> {
                try {
                    LOGGER.debug("Prefix mapping is key:{} -> value:{}", k, v);
                    if (Arrays.asList(namespaceRegistry.getPrefixes()).contains(k)
                        &&  !v.equals(namespaceRegistry.getURI(k))) {

                        final String namespaceURI = namespaceRegistry.getURI(k);
                        LOGGER.debug("Prefix has already been defined: {}:{}", k, namespaceURI);
                        throw new InvalidPrefixException("Prefix already exists as: " + k + " -> " + namespaceURI);
                   }

                } catch (final RepositoryException e) {
                    throw new RepositoryRuntimeException(e);
                }
           });

        throwConstraintErrorsIfPresent(errors);

        checkInteractionModel(request);

        final FilteringJcrPropertyStatementListener listener = new FilteringJcrPropertyStatementListener(
                idTranslator, getSession(), idTranslator.reverse().convert(described).asNode());

        model.register(listener);

        // If this resource's structural parent is an IndirectContainer, check whether the
        // ldp:insertedContentRelation property is present in the stream of changed triples.
        // If so, set the propertyChanged value to true.
        final AtomicBoolean propertyChanged = new AtomicBoolean();
        ldpInsertedContentProperty(getNode()).ifPresent(resource -> {
            model.register(new PropertyChangedListener(resource, propertyChanged));
        });

        model.setNsPrefixes(request.getPrefixMapping());
        execute(request, model);

        removeEmptyFragments();

        ensureInteractionModelDefaults(describedURI, model);

        listener.assertNoExceptions();

        try {
            touch(propertyChanged.get(), listener.getAddedCreatedDate(), listener.getAddedCreatedBy(),
                    listener.getAddedModifiedDate(), listener.getAddedModifiedBy());
        } catch (final RepositoryException e) {
            throw new RuntimeException(e);
        }
    }
1147653
def first(opts={})
      sq = Tripod::SparqlQuery.new(self.as_query(opts))
      first_sparql = sq.as_first_query_str
      self.resource_class._resources_from_sparql(first_sparql).first
    end
1031563
def Validate(self, type_names):
    """"""
    errs = [n for n in self._RDFTypes(type_names) if not self._GetClass(n)]
    if errs:
      raise DefinitionError("Undefined RDF Types: %s" % ",".join(errs))
332402
def infer_schema(self, stream, namespace=None):
    
    return self._make_request(self._infer_schema_url,
                              data={'stream': stream,
                                    'namespace': namespace or self.namespace})