Quick validation of JSON result set returned by XNAT.

    :param r: Result set data in JSON format
    :type r: dict
    :param check: Fields to check
    :type check: tuple
    :returns: Result set is valid
    :rtype: bool
354942
def __quick_validate(r, check=('ResultSet', 'Result', 'totalRecords')):
    '''
    
    '''
    if 'ResultSet' in check and 'ResultSet' not in r:
        raise ResultSetError('no ResultSet in server response')
    if 'Result' in check and 'Result' not in r['ResultSet']:
        raise ResultSetError('no Result in server response')
    if 'totalRecords' in check and 'totalRecords' not in r['ResultSet']:
        raise ResultSetError('no totalRecords in server response')
    return True
307666
def is_datafile_valid(datafile):
  

  try:
    datafile_json = json.loads(datafile)
  except:
    return False

  try:
    jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
  except:
    return False

  return True
1065196
function result(rule) {
  var r = {}

  var reserved = ['filename', 'exists', 'grep', 'jsonKeyExists']

  Object.keys(rule).forEach(function(key) {
    if (reserved.indexOf(key) !== -1) return
    r[key] = rule[key]
  })

  return r
}
932058
def validate_auto_threaded_json(pjson):
        """"""
        # pjson should be a dict or unicode
        if not type(pjson) is dict:
            raise ParseError("Expected a JSON object/dictionary or a string representing a test. Instead got %s." 
                             % pjson)

        # Make sure that the 'tests' key is present 
        try:
            tests = pjson["tests"]
        except KeyError:
            raise KeyError("Test object requires 'tests' attribute.\nObject: %s" % 
                           json.dumps(pjson))

        # Verify that tests is a list
        if type(tests) is not list:
            raise ParseError(
                "Expected 'tests' to be a list but got object of type %s.\nObject: %s" %
                (type(tests), json.dumps(tests))
            )

        # 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')

        # Verify that 'environments' is a list of dicts if present
        environments = pjson.get('environments', [])
        is_list_of_dicts = lambda ls: len(ls) == len(filter(lambda d: type(d) is dict, ls))
        if type(environments) is not list or not is_list_of_dicts(environments):
            raise ParseError('"environments" attribute must be a list of dictionaries. Instead got %s.' % environments)

        for test in tests:
            if type(test) is unicode:
                # Base case for recursion
                pass
            else:
                # Recur
                ConfigurationValidator.validate_auto_threaded_json(test)
622387
def check_error(result):
    
    return (result.value != ReturnCode.SUCCESSFUL) and (result.value < ReturnCode.WARNING)
679168
def validate(self, data):
        
        for v in self.validators:
            v(self, data)
        return data
311511
def run_validation(options):
    
    if options.files == sys.stdin:
        results = validate(options.files, options)
        return [FileValidationResults(is_valid=results.is_valid,
                                      filepath='stdin',
                                      object_results=results)]

    files = get_json_files(options.files, options.recursive)

    results = [validate_file(fn, options) for fn in files]

    return results
536026
def prepare_check(data):
    
    if not data:
        return None, {}

    if isinstance(data, str):
        return data, {}

    result = {}
    if "ID" in data:
        result["CheckID"] = data["ID"]
    for k in ("Node", "CheckID", "Name", "Notes", "Status", "ServiceID"):
        if k in data:
            result[k] = data[k]
    if list(result) == ["CheckID"]:
        return result["CheckID"], {}
    return result.get("CheckID"), result
483628
def _check_valid_data(self, data):
        
        if data.dtype.type is not np.float32 and \
           data.dtype.type is not np.float64:
            raise ValueError(
                'Illegal data type. RGB-D images only support float arrays')

        if len(data.shape) != 3 and data.shape[2] != 4:
            raise ValueError(
                'Illegal data type. RGB-D images only support four channel')

        color_data = data[:, :, :3]
        if np.any((color_data < 0) | (color_data > BINARY_IM_MAX_VAL)):
            raise ValueError(
                'Color channels must be in the range (0, BINARY_IM_MAX_VAL)')
673784
def validate_json_schema(self):
        """"""
        errors = []

        for work in self:
            for task in work:
                if not task.get_results().validate_json_schema():
                    errors.append(task)
            if not work.get_results().validate_json_schema():
                errors.append(work)
        if not self.get_results().validate_json_schema():
            errors.append(self)

        return errors
334712
def _validate(data, schema, ac_schema_safe=True, **options):
    
    try:
        jsonschema.validate(data, schema, **options)

    except (jsonschema.ValidationError, jsonschema.SchemaError,
            Exception) as exc:
        if ac_schema_safe:
            return (False, str(exc))  # Validation was failed.
        raise

    return (True, '')
494406
def validate_json(f):
    """"""
    @wraps(f)
    def wrapper(*args, **kw):
        instance = args[0]
        try:
            if request.get_json() is None:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.MUST_JSON)
                instance.logger.error(instance.MUST_JSON)
                return jsonify(ret_dict), 400
        except BadRequest:
            ret_dict = instance._create_ret_object(instance.FAILURE, None,
                                                   True,
                                                   instance.MUST_JSON)
            instance.logger.error(instance.MUST_JSON)
            return jsonify(ret_dict), 400
        instance.logger.debug("JSON is valid")
        return f(*args, **kw)
    return wrapper
994654
def _validated(self, data):
        """"""
        for sub in self.schemas:
            data = sub(data)
        return data
550882
def json_validate(schema, resp):
    
    # is this an error?
    try:
        json_validate_error(resp)
    except ValidationError:
        if json_is_exception(resp):
            # got a traceback 
            if BLOCKSTACK_TEST:
                log.error('\n{}'.format(resp['traceback']))

            return {'error': 'Blockstack Core encountered an exception. See `traceback` for details', 'traceback': resp['traceback'], 'http_status': 500}

        if 'error' in resp and 'http_status' not in resp:
            # bad error message
            raise 

        # not an error.
        jsonschema.validate(resp, schema)

    return resp
719336
def verify(self, **kwargs):
        
        _spec = self.c_param
        try:
            _allowed = self.c_allowed_values
        except KeyError:
            _allowed = {}

        for (attribute, (typ, required, _, _, na)) in _spec.items():
            if attribute == "*":
                continue

            try:
                val = self._dict[attribute]
            except KeyError:
                if required:
                    raise MissingRequiredAttribute("%s" % attribute)
                continue
            else:
                if typ == bool:
                    pass
                elif not val:
                    if required:
                        raise MissingRequiredAttribute("%s" % attribute)
                    continue

            try:
                _allowed_val = _allowed[attribute]
            except KeyError:
                pass
            else:
                if not self._type_check(typ, _allowed_val, val, na):
                    raise NotAllowedValue(val)

        return True
483990
def std_check_in(cls, dataset, name, allowed_vals):
        
        if name not in dataset.ncattrs():
            return 0

        ret_val = 1
        if dataset.getncattr(name) in allowed_vals:
            ret_val += 1

        return ret_val
1133008
def _perform_validation(self, path, value, results):
        
        name = path if path != None else "value"
        value = ObjectReader.get_value(value)

        super(MapSchema, self)._perform_validation(path, value, results)

        if value == None:
            return

        if isinstance(value, dict):
            for (key, value) in value.items():
                element_path = key if path == None or len(path) == 0 else path + "." + key

                self._perform_type_validation(element_path, self.key_type, key, results)
                self._perform_type_validation(element_path, self.value_type, value, results)
        else:
            results.append(
                ValidationResult(
                    path,
                    ValidationResultType.Error,
                    "VALUE_ISNOT_MAP",
                    name + " type is expected to be Map",
                    "Map",
                    type(value)
                )
            )