Validate input data matches expected failure ``dict`` format.
969359
def validate(cls, data):
        """"""
        try:
            jsonschema.validate(
                data, cls.SCHEMA,
                # See: https://github.com/Julian/jsonschema/issues/148
                types={'array': (list, tuple)})
        except jsonschema.ValidationError as e:
            raise InvalidFormat("Failure data not of the"
                                " expected format: %s" % (e.message))
        else:
            # Ensure that all 'exc_type_names' originate from one of
            # base exceptions, because those are the root exceptions that
            # python mandates/provides and anything else is invalid...
            causes = collections.deque([data])
            while causes:
                cause = causes.popleft()
                try:
                    generated_on = cause['generated_on']
                    ok_bases = cls.BASE_EXCEPTIONS[generated_on[0]]
                except (KeyError, IndexError):
                    ok_bases = []
                root_exc_type = cause['exc_type_names'][-1]
                if root_exc_type not in ok_bases:
                    raise InvalidFormat(
                        "Failure data 'exc_type_names' must"
                        " have an initial exception type that is one"
                        " of %s types: '%s' is not one of those"
                        " types" % (ok_bases, root_exc_type))
                sub_cause = cause.get('cause')
                if sub_cause is not None:
                    causes.append(sub_cause)
688254
def validate_config_json(pjson):
        """"""
        # Make sure that the root json is a dict
        if type(pjson) is not dict:
            raise ParseError("Configuration file should contain a single JSON object/dictionary. Instead got a %s." 
                             % type(pjson))

        # if 'configuration' is present it should be a dict of strings and numbers.
        # The ArgumentParser will do the rest of the validation.
        configuration = pjson.get('configuration', {})
        if type(configuration) is not dict:
            raise ParseError('''"configuration" object should be a dict, got %s instead.''' 
                             % type(configuration))

        # Make sure that the 'tests' key is present 
        try:
            tests = pjson["tests"]
        except KeyError:
            raise KeyError("Configuration file requires 'tests' attribute.")

        # Verify that 'options' is a dict if present
        options = pjson.get('options', {})
        if type(options) is not dict:
            raise ParseError('"options" attribute must be a dictionary"')

        # We need to know whether --user-defined-threads option is present to do 
        # the rest of the validation.
        if '-u' in options.keys() or '--user-defined-threads' in options.keys():
            ConfigurationValidator.validate_user_threaded_json(pjson)
        else:
            ConfigurationValidator.validate_auto_threaded_json(pjson)
133633
def validate(self, instance, value):
        """"""
        if not isinstance(value, (tuple, list, np.ndarray)):
            self.error(instance, value)
        if self.coerce:
            value = self.wrapper(value)
        valid_class = (
            self.wrapper if isinstance(self.wrapper, type) else np.ndarray
        )
        if not isinstance(value, valid_class):
            self.error(instance, value)
        allowed_kinds = ''.join(TYPE_MAPPINGS[typ] for typ in self.dtype)
        if value.dtype.kind not in allowed_kinds:
            self.error(instance, value, extra='Invalid dtype.')
        if self.shape is None:
            return value
        for shape in self.shape:
            if len(shape) != value.ndim:
                continue
            for i, shp in enumerate(shape):
                if shp not in ('*', value.shape[i]):
                    break
            else:
                return value
        self.error(instance, value, extra='Invalid shape.')
103760
def validate_text(value):
    """"""
    possible_transform = ['axes', 'fig', 'data']
    validate_transform = ValidateInStrings('transform', possible_transform,
                                           True)
    tests = [validate_float, validate_float, validate_str,
             validate_transform, dict]
    if isinstance(value, six.string_types):
        xpos, ypos = rcParams['texts.default_position']
        return [(xpos, ypos, value, 'axes', {'ha': 'right'})]
    elif isinstance(value, tuple):
        value = [value]
    try:
        value = list(value)[:]
    except TypeError:
        raise ValueError("Value must be string or list of tuples!")
    for i, val in enumerate(value):
        try:
            val = tuple(val)
        except TypeError:
            raise ValueError(
                "Text must be an iterable of the form "
                "(x, y, s[, trans, params])!")
        if len(val) < 3:
            raise ValueError(
                "Text tuple must at least be like [x, y, s], with floats x, "
                "y and string s!")
        elif len(val) == 3 or isinstance(val[3], dict):
            val = list(val)
            val.insert(3, 'data')
            if len(val) == 4:
                val += [{}]
            val = tuple(val)
        if len(val) > 5:
            raise ValueError(
                "Text tuple must not be longer then length 5. It can be "
                "like (x, y, s[, trans, params])!")
        value[i] = (validate(x) for validate, x in zip(tests, val))
    return value
605450
def validate(self, instance, value):
        """"""
        value_type = type(value)
        if not isinstance(value, string_types):
            self.error(instance, value)
        if self.regex is not None and self.regex.search(value) is None:        #pylint: disable=no-member
            self.error(instance, value, extra='Regex does not match.')
        value = value.strip(self.strip)
        if self.change_case == 'upper':
            value = value.upper()
        elif self.change_case == 'lower':
            value = value.lower()
        if self.unicode:
            value = text_type(value)
        else:
            value = value_type(value)
        return value
483223
def _validate_list_data(self, expected, actual):
        """"""
        for e in expected:
            if e not in actual:
                return "expected item {} not found in actual list".format(e)
        return None
903746
def validate(cls, mapper_spec):
    """"""
    if mapper_spec.input_reader_class() != cls:
      raise errors.BadReaderParamsError("Input reader class mismatch")
    params = mapper_spec.params
    if cls.FILES_PARAM not in params:
      raise errors.BadReaderParamsError("Missing files parameter.")
812437
def validate(self, data, schema):
        '''
        '''
        try:
            return schema(data)
        except MultipleInvalid as ie:
            errors = []
            for error in ie.errors:
                if error.path:
                    field = '.'.join(str(p) for p in error.path)
                    path = error.path
                    value = data
                    while path:
                        attr = path.pop(0)
                        try:
                            if isinstance(value, (list, tuple)):
                                attr = int(attr)
                            value = value[attr]
                        except Exception:
                            value = None

                    txt = safe_unicode(error).replace('for dictionary value', '')
                    txt = txt.strip()
                    if isinstance(error, RequiredFieldInvalid):
                        msg = '[{0}] {1}'
                    else:
                        msg = '[{0}] {1}: {2}'
                    try:
                        msg = msg.format(field, txt, str(value))
                    except Exception:
                        msg = '[{0}] {1}'.format(field, txt)

                else:
                    msg = str(error)
                errors.append(msg)
            msg = '\n- '.join(['Validation error:'] + errors)
            raise HarvestValidationError(msg)
976333
def validate(self):
        """"""
        # Literals representing boolean values or None are correctly representable and supported.
        if self.value is None or self.value is True or self.value is False:
            return

        # Literal safe strings are correctly representable and supported.
        if isinstance(self.value, six.string_types):
            validate_safe_string(self.value)
            return

        # Literal ints are correctly representable and supported.
        if isinstance(self.value, int):
            return

        # Literal empty lists, and non-empty lists of safe strings, are
        # correctly representable and supported.
        if isinstance(self.value, list):
            if len(self.value) > 0:
                for x in self.value:
                    validate_safe_string(x)
            return

        raise GraphQLCompilationError(u'Cannot represent literal: {}'.format(self.value))
1026220
def _validate_inputs(self, inputdict):
        
        # Check inputdict
        try:
            parameters = inputdict.pop(self.get_linkname('parameters'))
        except KeyError:
            raise InputValidationError("No parameters specified for this "
                                       "calculation")
        if not isinstance(parameters, ParameterData):
            raise InputValidationError("parameters not of type "
                                       "ParameterData")
        # Check code
        try:
            code = inputdict.pop(self.get_linkname('code'))
        except KeyError:
            raise InputValidationError("No code specified for this "
                                       "calculation")

        # Check input files
        try:
            structure = inputdict.pop(self.get_linkname('structure'))
            if not isinstance(structure, SinglefileData):
                raise InputValidationError(
                    "structure not of type SinglefileData")
        except KeyError:
            raise InputValidationError(
                "No input structure specified for calculation")

        try:
            surface_sample = inputdict.pop(self.get_linkname('surface_sample'))
            if not isinstance(surface_sample, SinglefileData):
                raise InputValidationError(
                    "surface_sample not of type SinglefileData")
        except KeyError:
            raise InputValidationError(
                "No surface sample specified for calculation")

        # Check that nothing is left unparsed
        if inputdict:
            raise ValidationError("Unrecognized inputs: {}".format(inputdict))

        return parameters, code, structure, surface_sample
581500
def _validate_output_data(
        self, original_res, serialized_res, formatted_res, request):
        

        validator = self.representation

        # when not to validate...
        if not validator:
            return

        try:
            if isinstance(serialized_res, (list, tuple)):
                map(validator.validate, serialized_res)
            else:
                validator.validate(serialized_res)
        except ValidationError, exc:
            self._output_validation_failed(exc, serialized_res, request)
421494
def _des_dict_check(self, des_dict, req_keys, cond_name):
        """"""
        assert isinstance(des_dict, dict), '{}' \
            ' must be a dictionary. Got {}.'.format(cond_name, type(des_dict))
        if bool(des_dict) is True:
            input_keys = list(des_dict.keys())
            for key in req_keys:
                assert key in input_keys, 'Required key "{}" was not found in ' \
                    '{}'.format(key, cond_name)
240426
def validate(cls, data, name, **kwargs):
        """"""
        required = kwargs.get('required', False)
        if required and data is None:
            raise ValidationError("required", name, True)
        elif data is None:
            return
        elif kwargs.get('readonly'):
            return

        try:
            for key, value in kwargs.items():
                validator = cls.validation.get(key, lambda x, y: False)
                if validator(data, value):
                    raise ValidationError(key, name, value)
        except TypeError:
            raise ValidationError("unknown", name, "unknown")
        else:
            return data
1101139
def _validated(self, values):
        """"""
        if self.length != len(values):
            raise NotValid(
                "%r does not have exactly %d values. (Got %d.)" % (
                    values, self.length, len(values)))
        return type(self.schemas)(
            self.schemas[i].validate(v) for i, v in enumerate(values))
1265839
def validate_items(self, input_list):
        """"""
        output_list = []
        for item in input_list:
            valid = self.list_item_type.validate(item, self.item_name)
            output_list.append(valid)

            # this might lead to confusing error messages.  tbh, we need to
            # figure out a better way to do validation and error handling here,
            # but i'm brute forcing this a bit so that we have something
            # workable
        return output_list
642688
def _validated(self, value):
        """"""
        if value is None:
            return None
        if isinstance(value, uuid.UUID):
            return value
        try:
            if isinstance(value, bytes) and len(value) == 16:
                return uuid.UUID(bytes=value)
            else:
                return uuid.UUID(value)
        except (ValueError, AttributeError, TypeError):
            self.fail('invalid_uuid')
789102
def _filter_validate(filepath, location, values, validate):
    
    for value in values:
        if not isinstance(value, dict):
            warn_invalid(filepath, location, value, '(expected a dict)')
            continue
        try:
            yield validate(**value)
        except dbt.exceptions.JSONValidationException as exc:
            # we don't want to fail the full run, but we do want to fail
            # parsing this file
            warn_invalid(filepath, location, value, '- ' + exc.msg)
            continue