Validation:
- Mismatch between the ontology and the mapping
969980
protected void validateMapping(Optional<Ontology> ontology,
                                 MappingWithProvenance filledProvMapping) throws MappingOntologyMismatchException {
        if (ontology.isPresent()) {
            ontologyComplianceValidator.validate(filledProvMapping, ontology.get());
        }
    }
503389
function validateDeep(map) {
  if (!(map instanceof Map)) {
    throw new Error(`Invalid graph: Expected Map instead found ${typeof map}`);
  }

  map.forEach((value, key) => {
    if (typeof value === 'object' && value instanceof Map) {
      validateDeep(value);
      return;
    }

    if (typeof value !== 'number' || value <= 0) {
      throw new Error(`Values must be numbers greater than 0. Found value ${value} at ${key}`);
    }
  });
}
777094
function validateEndpointData(
  data,
  { prettyErrorMessage = 'invalid response data', includeKeys = false } = {}
) {
  return validate(
    {
      ErrorClass: InvalidResponse,
      prettyErrorMessage,
      includeKeys,
      traceErrorMessage: 'Response did not match schema',
      traceSuccessMessage: 'Response after validation',
      allowAndStripUnknownKeys: false,
    },
    data,
    endpointSchema
  )
}
454697
@Override
	protected boolean validate(int classifierID, Object value, DiagnosticChain diagnostics, Map<Object, Object> context) {
		switch (classifierID) {
			case DroolsPackage.DOCUMENT_ROOT:
				return validateDocumentRoot((DocumentRoot)value, diagnostics, context);
			case DroolsPackage.GLOBAL_TYPE:
				return validateGlobalType((GlobalType)value, diagnostics, context);
			case DroolsPackage.IMPORT_TYPE:
				return validateImportType((ImportType)value, diagnostics, context);
			case DroolsPackage.META_DATA_TYPE:
				return validateMetaDataType((MetaDataType)value, diagnostics, context);
			case DroolsPackage.ON_ENTRY_SCRIPT_TYPE:
				return validateOnEntryScriptType((OnEntryScriptType)value, diagnostics, context);
			case DroolsPackage.ON_EXIT_SCRIPT_TYPE:
				return validateOnExitScriptType((OnExitScriptType)value, diagnostics, context);
			case DroolsPackage.PACKAGE_NAME_TYPE:
				return validatePackageNameType((String)value, diagnostics, context);
			case DroolsPackage.PRIORITY_TYPE:
				return validatePriorityType((BigInteger)value, diagnostics, context);
			case DroolsPackage.RULE_FLOW_GROUP_TYPE:
				return validateRuleFlowGroupType((String)value, diagnostics, context);
			case DroolsPackage.TASK_NAME_TYPE:
				return validateTaskNameType((String)value, diagnostics, context);
			case DroolsPackage.VERSION_TYPE:
				return validateVersionType((String)value, diagnostics, context);
			default:
				return true;
		}
	}
594900
def index_ontology(self, ont):
        
        self.merged_ontology.merge([ont])
        syns = ont.all_synonyms(include_label=True)
        
        include_id = self._is_meaningful_ids()
        logging.info("Include IDs as synonyms: {}".format(include_id))
        if include_id:
            for n in ont.nodes():
                v = n
                # Get fragment
                if v.startswith('http'):
                    v = re.sub('.*/','',v)
                    v = re.sub('.*#','',v)
                syns.append(Synonym(n, val=v, pred='label'))
        
        logging.info("Indexing {} syns in {}".format(len(syns),ont))
        logging.info("Distinct lexical values: {}".format(len(self.lmap.keys())))
        for syn in syns:
            self.index_synonym(syn, ont)
        for nid in ont.nodes():
            self.id_to_ontology_map[nid].append(ont)
772610
def nx_to_ontology(graph, source_node, output_path, base_iri):
    
    ontology = owlready.Ontology(base_iri)

    parent_lookup = {
        source_node: types.new_class(source_node, (owlready.Thing,), kwds={"ontology": ontology})
    }

    def recur(pnode):
        for neighbor in graph.neighbors(pnode):
            data = graph.node[neighbor]
            neighbor_class = types.new_class(neighbor, (parent_lookup[pnode],), kwds={"ontology": ontology})
            owlready.ANNOTATIONS[neighbor_class].add_annotation(owlready.rdfs.label, data['label'])
            recur(neighbor)

    recur(source_node)

    ontology.save(filename=output_path)
921485
def validate_version(version)
      return if SemanticPuppet::Version.valid?(version)

      err = _("version string cannot be parsed as a valid Semantic Version")
      raise ArgumentError, _("Invalid 'version' field in metadata.json: %{err}") % { err: err }
    end
1208981
def validate_sdl(
    document_ast: DocumentNode,
    schema_to_extend: GraphQLSchema = None,
    rules: Sequence[RuleType] = None,
) -> List[GraphQLError]:
    """"""
    context = SDLValidationContext(document_ast, schema_to_extend)
    if rules is None:
        rules = specified_sdl_rules
    visitors = [rule(context) for rule in rules]
    visit(document_ast, ParallelVisitor(visitors))
    return context.errors
632822
@SuppressWarnings("squid:S1643") // Strings should not be concatenated using '+' in a loop
  Hit<OntologyTerm> findTags(Attribute attribute, List<String> ontologyIds) {
    String description =
        attribute.getDescription() == null ? attribute.getLabel() : attribute.getDescription();
    Set<String> searchTerms = splitIntoTerms(description);

    if (LOG.isDebugEnabled()) {
      LOG.debug("findAttributeOntologyTerms({},{},{})", ontologyIds, searchTerms, MAX_NUM_TAGS);
    }

    List<OntologyTerm> candidates =
        ontologyService.findOntologyTerms(ontologyIds, searchTerms, MAX_NUM_TAGS);

    if (LOG.isDebugEnabled()) {
      LOG.debug("Candidates: {}", candidates);
    }

    List<Hit<OntologyTerm>> hits =
        candidates
            .stream()
            .filter(
                ontologyTerm ->
                    filterOntologyTerm(
                        splitIntoTerms(Stemmer.stemAndJoin(searchTerms)), ontologyTerm))
            .map(
                ontologyTerm ->
                    Hit.create(
                        ontologyTerm, bestMatchingSynonym(ontologyTerm, searchTerms).getScore()))
            .sorted(Ordering.natural().reverse())
            .collect(toList());

    if (LOG.isDebugEnabled()) {
      LOG.debug("Hits: {}", hits);
    }

    Hit<OntologyTerm> result = null;
    String bestMatchingSynonym = null;
    for (Hit<OntologyTerm> hit : hits) {
      String bestMatchingSynonymForHit =
          bestMatchingSynonym(hit.getResult(), searchTerms).getResult();
      if (result == null) {
        result = hit;
        bestMatchingSynonym = bestMatchingSynonymForHit;
      } else {
        Set<String> jointTerms =
            Sets.union(
                splitIntoTerms(bestMatchingSynonym), splitIntoTerms(bestMatchingSynonymForHit));
        String joinedSynonyms = String.join(" ", jointTerms);
        Hit<OntologyTerm> joinedHit =
            Hit.create(
                OntologyTerm.and(result.getResult(), hit.getResult()),
                distanceFrom(joinedSynonyms, searchTerms));
        if (joinedHit.compareTo(result) > 0) {
          result = joinedHit;
          bestMatchingSynonym = bestMatchingSynonym + " " + bestMatchingSynonymForHit;
        }
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug("result: {}", result);
      }
    }
    if (result != null && result.getScore() >= CUTOFF) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Tag {} with {}", attribute, result);
      }
      return result;
    }
    return null;
  }
966542
function(fact, ruleFact, mapping, constants, rule) {
        var localMapping = {};
    
        // Checks and update localMapping if matches     
        if (!this.factElemMatches(fact.predicate, ruleFact.predicate, mapping, localMapping)) {
            return false;
        }        
        if (!this.factElemMatches(fact.object, ruleFact.object, mapping, localMapping)) {
            return false;
        }
        if (!this.factElemMatches(fact.subject, ruleFact.subject, mapping, localMapping)) {
            return false;
        }
        
        emitter.emit('rule-fired', rule.name);        

        // If an already existing uri has been mapped...
        for (var key in localMapping) {
            if(constants.indexOf(localMapping[key]) !== -1) {
                return false;
            }
        }

        // Merges local and global mapping
        for (var mapKey in mapping) {
            if (mapKey == '__facts__') {
                localMapping[mapKey] = Utils.uniques(mapping[mapKey], [fact]);
            } else {
                for (key in localMapping) {
                    if (mapping[mapKey] == localMapping[key]) {
                        if (mapKey != key) {
                            return false;
                        }
                    }
                }
                localMapping[mapKey] = mapping[mapKey];
            }
        }

        // The new mapping is updated
        return localMapping;    
    }
982816
def _validate_schema(self, schema, field, value):
        
        if schema is None:
            return

        if isinstance(value, Sequence) and not isinstance(value, _str_type):
            self.__validate_schema_sequence(field, schema, value)
        elif isinstance(value, Mapping):
            self.__validate_schema_mapping(field, schema, value)
1161274
def map_ontologies():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    stmts_json = body.get('statements')
    stmts = stmts_from_json(stmts_json)
    om = OntologyMapper(stmts, wm_ontomap, scored=True, symmetric=False)
    om.map_statements()
    return _return_stmts(stmts)
365996
function validate (errObj, request, schema, location, allowUnknown, context) {
  if (!request || !schema) return;

  var joiOptions = {
    context: context || request,
    allowUnknown: allowUnknown,
    abortEarly: false
  };

  Joi.validate(request, schema, joiOptions, function (errors, value) {
    if (!errors || errors.details.length === 0) {
      assignIn(request, value); // joi responses are parsed into JSON
      return;
    }
    errors.details.forEach(function (error) {
      var errorExists = find(errObj, function (item) {
        if (item && item.field === error.path && item.location === location) {
          item.messages.push(error.message);
          item.types.push(error.type);
          return item;
        }
        return;
      });

      if (!errorExists) {
        errObj.push({
          field: error.path,
          location: location,
          messages: [error.message],
          types: [error.type]
        });
      }

    });
  });
}
1147108
def ontology2df(self):
        ''''''

        if isinstance(self.path, str) or isinstance(self.path, p):
            self.path = str(self.path)
            filetype = p(self.path).suffix
            if filetype == '.json':
                self.g = None
                try:
                    records = open_json(self.path)
                    return pd.DataFrame(records)
                except:
                    exit('Json file is not in records format.')
            if filetype == '.pickle':
                self.g = None
                return pickle.load(open(self.path, 'rb'))
            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()')
81429
def _compile_mapping(self, schema, invalid_msg=None):
        """"""
        invalid_msg = invalid_msg or 'mapping value'

        # Keys that may be required
        all_required_keys = set(key for key in schema
                                if key is not Extra and
                                ((self.required and not isinstance(key, (Optional, Remove))) or
                                 isinstance(key, Required)))

        # Keys that may have defaults
        all_default_keys = set(key for key in schema
                               if isinstance(key, Required) or
                               isinstance(key, Optional))

        _compiled_schema = {}
        for skey, svalue in iteritems(schema):
            new_key = self._compile(skey)
            new_value = self._compile(svalue)
            _compiled_schema[skey] = (new_key, new_value)

        candidates = list(_iterate_mapping_candidates(_compiled_schema))

        # After we have the list of candidates in the correct order, we want to apply some optimization so that each
        # key in the data being validated will be matched against the relevant schema keys only.
        # No point in matching against different keys
        additional_candidates = []
        candidates_by_key = {}
        for skey, (ckey, cvalue) in candidates:
            if type(skey) in primitive_types:
                candidates_by_key.setdefault(skey, []).append((skey, (ckey, cvalue)))
            elif isinstance(skey, Marker) and type(skey.schema) in primitive_types:
                candidates_by_key.setdefault(skey.schema, []).append((skey, (ckey, cvalue)))
            else:
                # These are wildcards such as 'int', 'str', 'Remove' and others which should be applied to all keys
                additional_candidates.append((skey, (ckey, cvalue)))

        def validate_mapping(path, iterable, out):
            required_keys = all_required_keys.copy()

            # Build a map of all provided key-value pairs.
            # The type(out) is used to retain ordering in case a ordered
            # map type is provided as input.
            key_value_map = type(out)()
            for key, value in iterable:
                key_value_map[key] = value

            # Insert default values for non-existing keys.
            for key in all_default_keys:
                if not isinstance(key.default, Undefined) and \
                   key.schema not in key_value_map:
                    # A default value has been specified for this missing
                    # key, insert it.
                    key_value_map[key.schema] = key.default()

            error = None
            errors = []
            for key, value in key_value_map.items():
                key_path = path + [key]
                remove_key = False

                # Optimization. Validate against the matching key first, then fallback to the rest
                relevant_candidates = itertools.chain(candidates_by_key.get(key, []), additional_candidates)

                # compare each given key/value against all compiled key/values
                # schema key, (compiled key, compiled value)
                for skey, (ckey, cvalue) in relevant_candidates:
                    try:
                        new_key = ckey(key_path, key)
                    except er.Invalid as e:
                        if len(e.path) > len(key_path):
                            raise
                        if not error or len(e.path) > len(error.path):
                            error = e
                        continue
                    # Backtracking is not performed once a key is selected, so if
                    # the value is invalid we immediately throw an exception.
                    exception_errors = []
                    # check if the key is marked for removal
                    is_remove = new_key is Remove
                    try:
                        cval = cvalue(key_path, value)
                        # include if it's not marked for removal
                        if not is_remove:
                            out[new_key] = cval
                        else:
                            remove_key = True
                            continue
                    except er.MultipleInvalid as e:
                        exception_errors.extend(e.errors)
                    except er.Invalid as e:
                        exception_errors.append(e)

                    if exception_errors:
                        if is_remove or remove_key:
                            continue
                        for err in exception_errors:
                            if len(err.path) <= len(key_path):
                                err.error_type = invalid_msg
                            errors.append(err)
                        # If there is a validation error for a required
                        # key, this means that the key was provided.
                        # Discard the required key so it does not
                        # create an additional, noisy exception.
                        required_keys.discard(skey)
                        break

                    # Key and value okay, mark as found in case it was
                    # a Required() field.
                    required_keys.discard(skey)

                    break
                else:
                    if remove_key:
                        # remove key
                        continue
                    elif self.extra == ALLOW_EXTRA:
                        out[key] = value
                    elif self.extra != REMOVE_EXTRA:
                        errors.append(er.Invalid('extra keys not allowed', key_path))
                        # else REMOVE_EXTRA: ignore the key so it's removed from output

            # for any required keys left that weren't found and don't have defaults:
            for key in required_keys:
                msg = key.msg if hasattr(key, 'msg') and key.msg else 'required key not provided'
                errors.append(er.RequiredFieldInvalid(msg, path + [key]))
            if errors:
                raise er.MultipleInvalid(errors)

            return out

        return validate_mapping
649599
def isValidList(self, l):  # modified to flatten lists specified using [ a rdf:List; ] syntax
        
        try:
            if self.store.value(l, RDF.first) is None:
                return False
        except:
            return False
        while l:
            if l != RDF.nil:
                po = list(self.store.predicate_objects(l))
                if (RDF.type, RDF.List) in po and len(po) == 3:
                    pass
                elif len(po) != 2:
                    return False
            l = self.store.value(l, RDF.rest)
        return True
49733
private static void validateFunctions(ELNode.Nodes el, ValidateResult result, Element jspElement, HashMap prefixToUriMap )
            throws JspTranslationException {
        el.visit(new FVVisitor(jspElement, result, prefixToUriMap));
    }