Validate searchspace content, 
       if the searchspace file is not json format or its values does not contain _type and _value which must be specified, 
       it will not be a valid searchspace file
484108
def validate_search_space_content(experiment_config):
    ''''''
    try:
        search_space_content = json.load(open(experiment_config.get('searchSpacePath'), 'r'))
        for value in search_space_content.values():
            if not value.get('_type') or not value.get('_value'):
                print_error('please use _type and _value to specify searchspace!')
                exit(1)
    except:
        print_error('searchspace file is not a valid json format!')
        exit(1)
939052
def is_data_value(searchpath, searchtree, dtype = None, empty_is_false = False):
    
    if isinstance(searchpath, (str, unicode, int)):
        searchpath = [searchpath]

    if not isinstance(searchpath, (list, tuple)):
        return False

    for d in searchpath:
        if isinstance(searchtree, dict):
            if not d in searchtree.keys():
                return False

        elif isinstance(searchtree, (list, tuple)):
            if (not isinstance(d, int) or (d >= 0 and d >= len(searchtree)) or (d < 0 and -d > len(searchtree))):
                return False

        else:
            return False

        searchtree = searchtree[d]

    if dtype == None and not (empty_is_false and searchtree == None):
        return True

    if empty_is_false and searchtree in (None, "", {}, []):
        return False

    if isinstance(dtype, tuple):
        dtype = list(dtype)

    elif not isinstance(dtype, list):
        dtype = [dtype]

    if float in dtype and not int in dtype:
        dtype.append(int)

    if str in dtype or unicode in dtype or 'string' in dtype:
        for dtp in (str, unicode, 'string'):
            while dtp in dtype:
                dtype.remove(dtp)
        dtype.extend([str, unicode])

    if list in dtype or tuple in dtype or 'list' in dtype:
        for dtp in (list, tuple, 'list'):
            while dtp in dtype:
                dtype.remove(dtp)
        dtype.extend([list, tuple])

    dtype = tuple(dtype)

    return bool(isinstance(searchtree, dtype))
340270
def validate(self, value):
        ''''''
        if self.blank and value == '':
            return True
        if URIValidator.uri_regex.match(value):
            self._choice = value
            return True
        else:
            self.error_message = '%s is not a valid URI' % value
            return False
167432
def is_valid(self, search_space):
        
        if not len(search_space) == 1:
            raise RuntimeError('BatchTuner only supprt one combined-paramreters key.')
        
        for param in search_space:
            param_type = search_space[param][TYPE]
            if not param_type == CHOICE:
                raise RuntimeError('BatchTuner only supprt one combined-paramreters type is choice.')
            else:
                if isinstance(search_space[param][VALUE], list):
                    return search_space[param][VALUE]
                raise RuntimeError('The combined-paramreters value in BatchTuner is not a list.')
        return None
1011941
def _isvalid(self, datatype):
        ''''''
        if datatype in self.meta:
            return bool(Dap._meta_valid[datatype].match(self.meta[datatype]))
        else:
            return datatype in Dap._optional_meta
978459
def validate_format(self, **kwargs):
        
        args = dict(
            dict_type=self._dict,
            allow_no_value=self._allow_no_value,
            inline_comment_prefixes=self._inline_comment_prefixes,
            strict=self._strict,
            empty_lines_in_values=self._empty_lines_in_values
        )
        args.update(kwargs)
        parser = ConfigParser(**args)
        updated_cfg = str(self)
        parser.read_string(updated_cfg)
690777
def should_validate_attachment_content_type name, options = {}
      klass   = self.name.gsub(/Test$/, '').constantize
      valid   = [options[:valid]].flatten
      invalid = [options[:invalid]].flatten
      matcher = validate_attachment_content_type(name).allowing(valid).rejecting(invalid)
      should matcher.description do
        assert_accepts(matcher, klass)
      end
    end
524622
def validate(self):
        
        from pyrocore.torrent import formatting

        super(PatternFilter, self).validate()
        self._value = self._value.lower()
        self._template = None
        self._is_regex = self._value.startswith('/') and self._value.endswith('/')
        if self._is_regex:
            self._matcher = re.compile(self._value[1:-1]).search
        elif self._value.startswith('{{') or self._value.endswith('}}'):
            def _template_globber(val, item):
                """Helper."""
                pattern = formatting.format_item(self._template, item).replace('[', '[[]')
                ##print('!!!', val, '~~~', pattern, '???')
                return fnmatch.fnmatchcase(val, pattern.lower())

            self._template = formatting.preparse(self._value)
            self._matcher = _template_globber
        else:
            self._matcher = lambda val, _: fnmatch.fnmatchcase(val, self._value)
606163
def validate_json_field(dist, attr, value):
    

    try:
        is_json_compat(value)
    except ValueError as e:
        raise DistutilsSetupError("%r %s" % (attr, e))

    return True
340859
def validate(self, ymldata=None, messages=None):
        """"""
        schema_val = self.schema_val(messages)
        if len(messages) == 0:
            content_val = self.content_val(ymldata, messages)

        return schema_val and content_val
1167341
def load_search_space(path):
    ''''''
    content = json.dumps(get_json_content(path))
    if not content:
        raise ValueError('searchSpace file should not be empty')
    return content
698455
def validate_annotation_content(experiment_config, spec_key, builtin_name):
    '''
    
    '''
    if experiment_config.get('useAnnotation'):
        if experiment_config.get('searchSpacePath'):
            print_error('If you set useAnnotation=true, please leave searchSpacePath empty')
            exit(1)
    else:
        # validate searchSpaceFile
        if experiment_config[spec_key].get(builtin_name) == 'NetworkMorphism':
            return
        if experiment_config[spec_key].get(builtin_name):
            if experiment_config.get('searchSpacePath') is None:
                print_error('Please set searchSpacePath!')
                exit(1)
            validate_search_space_content(experiment_config)
1212184
def validate_before(self, content, file_to_handle):
        
        logger.debug('Looking for required strings: %s', self.must_include)
        included = True
        for string in self.must_include:
            if not re.search(r'{0}'.format(string), content):
                logger.error('Required string `%s` not found in %s',
                             string, file_to_handle)
                included = False
        if not included:
            logger.debug('Required strings not found')
            return False
        logger.debug('Required strings found')
        return True
14735
private static void checkContentType(String contentType, String accept, String ext, boolean strict) throws PageException {

	if (!StringUtil.isEmpty(ext, true)) {
	    ext = ext.trim().toLowerCase();
	    if (ext.startsWith("*.")) ext = ext.substring(2);
	    if (ext.startsWith(".")) ext = ext.substring(1);

		String blacklistedTypes = SystemUtil.getSystemPropOrEnvVar(
				SystemUtil.SETTING_UPLOAD_EXT_BLACKLIST, SystemUtil.DEFAULT_UPLOAD_EXT_BLACKLIST
		).toLowerCase();
		Array blacklist = ListUtil.listToArrayRemoveEmpty(blacklistedTypes, ',');

		for (int i=blacklist.size(); i > 0; i--) {
			if (ext.equals(Caster.toString(blacklist.getE(i)).trim())){
				throw new ApplicationException("Upload of files with extension [" + ext + "] is not permitted.  "
						+ "You can configure the "
						+ SystemUtil.SETTING_UPLOAD_EXT_BLACKLIST
						+ " System property or the "
						+ SystemUtil.convertSystemPropToEnvVar(SystemUtil.SETTING_UPLOAD_EXT_BLACKLIST)
						+ " Environment variable to allow that file type."
				);
			}
		}
	}
	else ext = null;

	if (StringUtil.isEmpty(accept, true)) return;

	MimeType mt = MimeType.getInstance(contentType), sub;

	Array whishedTypes = ListUtil.listToArrayRemoveEmpty(accept, ',');
	int len = whishedTypes.size();
	for (int i = 1; i <= len; i++) {
	    String whishedType = Caster.toString(whishedTypes.getE(i)).trim().toLowerCase();
	    if (whishedType.equals("*")) return;
	    // check mimetype
	    if (ListUtil.len(whishedType, "/", true) == 2) {
		sub = MimeType.getInstance(whishedType);
		if (mt.match(sub)) return;
	    }

	    // check extension
	    if (ext != null && !strict) {
		if (whishedType.startsWith("*.")) whishedType = whishedType.substring(2);
		if (whishedType.startsWith(".")) whishedType = whishedType.substring(1);
		if (ext.equals(whishedType)) return;
	    }
	}
	throw new ApplicationException("The MIME type of the uploaded file [" + contentType + "] was not accepted by the server.",
		"only this [" + accept + "] mime type are accepted");
    }
665751
def check_not_empty?(yaml_data, errors_array)
      if yaml_data.empty?
        errors_array << 'The YAML should not be an empty string'
        false
      elsif yaml_data.strip.empty?
        errors_array << 'The YAML should not just be spaces'
        false
      else
        true
      end
    end
1084324
def Validate(self):
    """"""
    self.pathspec.Validate()

    if (self.HasField("start_time") and self.HasField("end_time") and
        self.start_time > self.end_time):
      raise ValueError("Start time must be before end time.")

    if not self.path_regex and not self.data_regex and not self.path_glob:
      raise ValueError("A Find specification can not contain both an empty "
                       "path regex and an empty data regex")
829741
def _validate(self):
        
        # A JP2 file must contain certain boxes.  The 2nd box must be a file
        # type box.
        if not isinstance(self.box[1], FileTypeBox):
            msg = "{filename} does not contain a valid File Type box."
            msg = msg.format(filename=self.filename)
            raise IOError(msg)

        # A jp2-branded file cannot contain an "any ICC profile
        ftyp = self.box[1]
        if ftyp.brand == 'jp2 ':
            jp2h = [box for box in self.box if box.box_id == 'jp2h'][0]
            colrs = [box for box in jp2h.box if box.box_id == 'colr']
            for colr in colrs:
                if colr.method not in (core.ENUMERATED_COLORSPACE,
                                       core.RESTRICTED_ICC_PROFILE):
                    msg = ("Color Specification box method must specify "
                           "either an enumerated colorspace or a restricted "
                           "ICC profile if the file type box brand is 'jp2 '.")
                    warnings.warn(msg, UserWarning)