CHECK THE DOCUMENT AGAINST IT'S SCHEMA
    
    returns: cleaned-up-document, error_list
194101
def schema_rolne_check(doc, schema):
    '''
    
    '''
    import standard_types as st
    error_list = []
    #
    # PASS ONE: FORWARD CHECK OF DOC
    #
    # this pass verifies that each entry in the document
    # has a corresponding entry in the schema
    #
    exclusive_flag = True
    if schema.list_names("#!MARDS_schema_en_1.0"):
        if schema["#!MARDS_schema_en_1.0"].get_value("exclusive")=="false":
            exclusive_flag = False
    if exclusive_flag:
        # print "jj", schema
        el = check_schema_coverage(doc, schema)
        error_list.extend(el)
    #
    # PASS TWO: REQUIREMENTS CHECK OF SCHEMA
    #
    # this pass verifies that any 'required' entries in the
    # schema are met. It auto-inserts if allowed. Otherwise,
    # it adds an error.
    el = sub_schema_requirements(doc, schema)
    error_list.extend(el)
    #
    # PASS THREE: TREATMENT CHECKS
    #
    el = sub_schema_treatments(doc, schema)
    error_list.extend(el)
    #
    # PASS FOUR: TYPE CHECKS AND NORMALIZATION
    #
    el = st.apply_schema_types(doc, schema)
    error_list.extend(el)
    #
    #
    # PASS FIVE: RAISE_ERROR CHECKS
    #
    el = sub_schema_raises(doc, schema)
    error_list.extend(el)
    #
    return doc, error_list
351127
def _validate_items(self, items, field, values):
        
        if len(items) != len(values):
            self._error(field, errors.ITEMS_LENGTH, len(items), len(values))
        else:
            schema = dict(
                (i, definition) for i, definition in enumerate(items)
            )  # noqa: E501
            validator = self._get_child_validator(
                document_crumb=field,
                schema_crumb=(field, 'items'),  # noqa: E501
                schema=schema,
            )
            if not validator(
                dict((i, value) for i, value in enumerate(values)),
                update=self.update,
                normalize=False,
            ):
                self._error(field, errors.BAD_ITEMS, validator._errors)
239044
def delete(self, **kwargs):
        
        if self.is_valid:
            if '_id' in self._document:
                to_delete = self.find_one({'_id': self._id})

                if to_delete:
                    before = self.before_delete()
                    if before:
                        return before

                    try:
                        self.delete_one({'_id': self._id})

                        self.after_delete()

                        return self._document
                    except PyMongoException as exc:
                        return PyMongoError(
                            error_message=exc.details.get(
                                'errmsg', exc.details.get(
                                    'err', 'PyMongoError.'
                                )
                            ),
                            operation='delete', collection=type(self).__name__,
                            document=self._document,
                        )
                else:
                    return DocumentNotFoundError(type(self).__name__, self._id)
            else:
                return UnidentifiedDocumentError(
                    type(self).__name__, self._document
                )
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
1194334
def reformat_schema(model):
    
    if not hasattr(model, 'schema'):
        return "Model '{}' does not have a schema".format(model)

    if 'properties' not in model.schema:
        return "Schema in unexpected format."

    ret = copy.deepcopy(model.schema['properties'])

    if 'type' in ret:
        del(ret['type'])

    for key in model.schema.get('required', []):
        if key in ret:
            ret[key]['required'] = True

    return ret
315427
def _clean_schema_fields(self, fields):
        """"""
        fields_sorted = sorted(fields, key=lambda field: field["name"])
        # Ignore mode and description when comparing schemas.
        return [
            {"name": field["name"], "type": field["type"]}
            for field in fields_sorted
        ]
652384
def clean(self):
        
        errors = {}
        cleaned = {}

        for name, validator in self.validate_schema.items():
            val = getattr(self, name, None)
            try:
                cleaned[name] = validator.to_python(val)
            except formencode.api.Invalid, err:
                errors[name] = err

        if errors:
            raise ValidationError('Invalid data', errors)
        return cleaned
364861
def _clean_doc(self, doc=None):
        """"""

        if doc is None:
            doc = self.doc

        resources = doc['Resources']

        # We don't need these anymore because all of the data written into the package is normalized.
        for arg in ['startline', 'headerlines', 'encoding']:
            for e in list(resources.args):
                if e.lower() == arg:
                    resources.args.remove(e)

        for term in resources:
            term['startline'] = None
            term['headerlines'] = None
            term['encoding'] = None

        schema = doc['Schema']

        ## FIXME! This is probably dangerous, because the section args are changing, but the children
        ## are not, so when these two are combined in the Term.properties() acessors, the values are off.
        ## Because of this, _clean_doc should be run immediately before writing the doc.
        for arg in ['altname', 'transform']:
            for e in list(schema.args):
                if e.lower() == arg:
                    schema.args.remove(e)

        for table in self.doc.find('Root.Table'):
            for col in table.find('Column'):
                try:
                    col.value = col['altname'].value
                except:
                    pass

                col['altname'] = None
                col['transform'] = None

        # Remove any DSNs

        #for dsn_t in self.doc.find('Root.Dsn'):
        #    self.doc.remove_term(dsn_t)


        return doc
1106652
function validate(doc, schema, prefix, options) {
  schema.validate(doc, prefix, options);
}
1251134
def full_clean(self):
        
        super(SuperFormMixin, self).full_clean()
        for field_name, composite in self.forms.items():
            composite.full_clean()
            if not composite.is_valid() and composite._errors:
                self._errors[field_name] = ErrorDict(composite._errors)
        for field_name, composite in self.formsets.items():
            composite.full_clean()
            if not composite.is_valid() and composite._errors:
                self._errors[field_name] = ErrorList(composite._errors)
599477
function validate(candidate) {
  if (candidate.doc_type) {
    var schema = schemasDeepCopy()[candidate.doc_type];
    validator.validate(candidate, schema);
    var errors = validator.getLastErrors();
    return errors;
  }

  return [{
    dataModel: 'the object to be validated is missing a `doc_type` property'
  }];
}
582933
def assert_valid_sdl(document_ast: DocumentNode) -> None:
    

    errors = validate_sdl(document_ast)
    if errors:
        raise TypeError("\n\n".join(error.message for error in errors))
75495
def validate(document, schema, log_qualifier = True):
    
    if isinstance(schema, ValidatorNode):
        if not validate(document, schema.content):
            return False
        if not schema.validator(document, schema.content):
            if log_qualifier:
                LOG.error("%r failed to validate with qualifier %s", document, schema.validator.__name__)
            return False
        return True
    elif isinstance(schema, dict):
        if not isinstance(document, dict):
            LOG.error("wanted a dictionary, got a %s", document.__class__.__name__)
            return False
        generic = []
        optional = {}
        optionalnull = {}
        mandatory = []
        for key, schema_val in schema.iteritems():
            if isinstance(key, ValidatorNode):
                if key.mode == 'mandatory':
                    mandatory.append((key, schema_val))
                else:
                    generic.append((key, schema_val))
            elif isinstance(schema_val, Optional):
                optional[key] = schema_val
            elif isinstance(schema_val, OptionalNull):
                optional[key] = schema_val
                optionalnull[key] = True
            else:
                mandatory.append((key, schema_val))

        doc_copy = document.copy()

        for key, schema_val in mandatory:
            if isinstance(key, ValidatorNode):
                nb = 0
                rm = []
                for doc_key, doc_val in doc_copy.iteritems():
                    if not validate(doc_key, key, False):
                        continue

                    nb += 1

                    if validate(doc_val, schema_val):
                        rm.append(doc_key)
                    else:
                        return False

                if nb == 0:
                    LOG.error("missing document %r for qualifier: %r", key.content, key.validator.__name__)
                    return False
                elif key.min is not None and nb < key.min:
                    LOG.error("no enough document %r for qualifier: %r (min: %r, found: %r)", key.content, key.validator.__name__, key.min, nb)
                    return False
                elif key.max is not None and nb > key.max:
                    LOG.error("too many document %r for qualifier: %r (max: %r, found: %r)", key.content, key.validator.__name__, key.max, nb)
                    return False
                else:
                    for x in rm:
                        del doc_copy[x]
                    continue

            doc_val = doc_copy.get(key, Nothing)
            if doc_val is Nothing:
                LOG.error("missing key %r in document", key)
                return False

            if helpers.is_scalar(schema_val):
                if not validate(doc_val, schema_val):
                    return False
                del doc_copy[key]
                continue

            if schema_val.modifier:
                for modname in schema_val.modifier:
                    if modname in _modifiers:
                        document[key] = _modifiers[modname](document[key])
                        doc_val = _modifiers[modname](doc_val)
                    elif hasattr(doc_val, modname):
                        document[key] = getattr(document[key], modname)()
                        doc_val = getattr(doc_val, modname)()

            if _valid_len(key, doc_val, schema_val.min_len, schema_val.max_len) is False:
                return False
            if not validate(doc_val, schema_val.content):
                return False
            del doc_copy[key]

        for key, schema_val in generic:
            nb = 0
            rm = []

            for doc_key, doc_val in doc_copy.iteritems():
                if not validate(doc_key, key, False):
                    continue

                nb += 1

                if validate(doc_val, schema_val):
                    rm.append(doc_key)
                else:
                    return False

            if key.min is not None and nb < key.min:
                LOG.error("no enough document %r for qualifier: %r (min: %r, found: %r)", key.content, key.validator.__name__, key.min, nb)
                return False
            elif key.max is not None and nb > key.max:
                LOG.error("too many document %r for qualifier: %r (max: %r, found: %r)", key.content, key.validator.__name__, key.max, nb)
                return False
            else:
                for x in rm:
                    del doc_copy[x]
                continue

        for key, doc_val in doc_copy.iteritems():
            schema_val = optional.get(key, Nothing)
            if schema_val is Nothing:
                LOG.error("forbidden key %s in document", key)
                return False
            elif optionalnull.has_key(key) and doc_val is None:
                continue
            elif schema_val.min_len == 0 and doc_val is "":
                continue

            if schema_val.modifier:
                for modname in schema_val.modifier:
                    if modname in _modifiers:
                        document[key] = _modifiers[modname](document[key])
                        doc_val = _modifiers[modname](doc_val)
                    elif hasattr(doc_val, modname):
                        document[key] = getattr(document[key], modname)()
                        doc_val = getattr(doc_val, modname)()
                if optionalnull.has_key(key) and doc_val is None:
                    continue
                elif schema_val.min_len == 0 and doc_val is "":
                    continue

            if _valid_len(key, doc_val, schema_val.min_len, schema_val.max_len) is False:
                return False
            if not validate(doc_val, schema_val.content):
                return False
        return True
    elif isinstance(schema, list):
        if not isinstance(document, list):
            LOG.error("wanted a list, got a %s", document.__class__.__name__)
        for elt in document:
            # XXX: give a meaning when there are multiple element in a sequence of a schema?
            if len(schema) < 2:
                if not validate(elt, schema[0]):
                    return False
            elif isinstance(schema[0], dict):
                tmp = {}
                for x in schema:
                    for key, val in x.iteritems():
                        tmp[key] = val
                if not validate(elt, tmp):
                    return False
            else:
                if not validate(elt, schema[0]):
                    return False
        return True
    elif isinstance(schema, Any):
        return True
    elif isinstance(schema, Scalar):
        return helpers.is_scalar(document)
    else: # scalar
        if isinstance(schema, str):
            schema = unicode(schema)
        if isinstance(document, str):
            document = unicode(document, 'utf8')
        if schema.__class__ != document.__class__:
            LOG.error("wanted a %s, got a %s", schema.__class__.__name__, document.__class__.__name__)
            return False
        return True
1205904
def validate(self, value, add_comments=False, schema_name="map"):
        
        validator = self.get_schema_validator(schema_name)

        error_messages = []

        if isinstance(value, list):
            for d in value:
                error_messages += self._validate(d, validator, add_comments, schema_name)
        else:
            error_messages = self._validate(value, validator, add_comments, schema_name)

        return error_messages
569873
def validate_schema(sconf):
    

    # verify session_name
    if 'session_name' not in sconf:
        raise exc.ConfigError('config requires "session_name"')

    if 'windows' not in sconf:
        raise exc.ConfigError('config requires list of "windows"')

    for window in sconf['windows']:
        if 'window_name' not in window:
            raise exc.ConfigError('config window is missing "window_name"')

        if 'panes' not in window:
            raise exc.ConfigError(
                'config window %s requires list of panes' % window['window_name']
            )

    return True
461387
def validate_schema(schema_name):
    """"""
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            instance = args[0]
            try:
                instance.validator(instance.schemas[schema_name]).validate(request.get_json())
            except ValidationError, e:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.BAD_SCHEMA,
                                                       e.message)
                instance.logger.error("Invalid Schema", ret_dict)
                return jsonify(ret_dict), 400
            instance.logger.debug("Schema is valid")
            return f(*args, **kw)
        return wrapper
    return decorator
311227
def validate(data):
        
        try:
            return Schema(Validator.SCHEMA).validate(data)
        except SchemaError as exception:
            logging.getLogger(__name__).error(exception)
            return None