Validates submission.

    Args:
      filename: submission filename

    Returns:
      submission metadata or None if submission is invalid
509006
def validate_submission(self, filename):
    
    self._prepare_temp_dir()
    # Convert filename to be absolute path, relative path might cause problems
    # with mounting directory in Docker
    filename = os.path.abspath(filename)
    # extract submission
    if not self._extract_submission(filename):
      return None
    # verify submission size
    if not self._verify_submission_size():
      return None
    # Load metadata
    metadata = self._load_and_verify_metadata()
    if not metadata:
      return None
    submission_type = metadata['type']
    # verify docker container size
    if not self._verify_docker_image_size(metadata['container_gpu']):
      return None
    # Try to run submission on sample data
    self._prepare_sample_data(submission_type)
    if not self._run_submission(metadata):
      logging.error('Failure while running submission')
      return None
    if not self._verify_output(submission_type):
      logging.warning('Some of the outputs of your submission are invalid or '
                      'missing. You submission still will be evaluation '
                      'but you might get lower score.')
    return metadata
1197759
def verify(conf, input_requirements_filename):
    
    exit_if_file_not_exists(input_requirements_filename, conf)

    cireqs.check_if_requirements_are_up_to_date(
        requirements_filename=input_requirements_filename,
        **conf._asdict())
    click.echo(click.style('✓', fg='green') + " {} has been verified".format(input_requirements_filename))
734685
def allowance (self, filename):
        
        for line in self.rulelines:
            log.debug(LOG_CHECK, "%s %s %s", filename, str(line), line.allowance)
            if line.applies_to(filename):
                log.debug(LOG_CHECK, " ... rule line %s", line)
                return line.allowance
        log.debug(LOG_CHECK, " ... no rule lines of %s applied to %s; allowed.", self.useragents, filename)
        return True
808867
def validate_metadata(target_dir, metadata):
    
    if not os.path.isdir(target_dir):
        print("Error: " + target_dir + " is not a directory")
        return False
    file_list = os.listdir(target_dir)
    for filename in file_list:
        if filename not in metadata:
            print("Error: " + filename + " present at" + target_dir +
                  " not found in metadata file")
            return False
    for filename in metadata:
        if filename not in file_list:
            print("Error: " + filename + " present in metadata file " +
                  " not found on disk at: " + target_dir)
            return False
    return True
346652
def load(fileobj):
        
        with gzip.GzipFile(fileobj=fileobj, mode='r') as z:
            submission = Submission(metadata=json.loads(z.readline()))

            for line in z:
                token_id, token = json.loads(line)
                submission['tokens'][token_id] = token

        return submission
1097015
async def validate(self, request: web.Request):
        
        parameters = {}
        files = {}
        errors = self.errors_factory()
        body = None

        if request.method in request.POST_METHODS:
            try:
                body = await self._content_receiver.receive(request)
            except ValueError as e:
                errors[request.content_type].add(str(e))
            except TypeError:
                errors[request.content_type].add('Not supported content type')

        for name, param in self._parameters.items():
            where = param['in']
            schema = param.get('schema', param)
            vtype = schema['type']
            is_array = vtype == 'array'

            if where == 'query':
                source = request.query
            elif where == 'header':
                source = request.headers
            elif where == 'path':
                source = request.match_info
            elif body is None:
                source = ()
            elif where == 'formData':
                source = body
            elif where == 'body':
                if isinstance(body, BaseException):
                    errors[name].add(str(body))
                else:
                    parameters[name] = body
                continue
            else:
                raise ValueError(where)

            if is_array and hasattr(source, 'getall'):
                collection_format = param.get('collectionFormat')
                default = param.get('default', [])
                value = get_collection(source, name,
                                       collection_format, default)
                if param.get('minItems') and not value \
                        and name not in self._required:
                    continue
            elif isinstance(source, Mapping) and name in source and (
                vtype not in ('number', 'integer') or source[name] != ''
            ):
                value = source[name]
            elif 'default' in param:
                parameters[name] = param['default']
                continue
            elif name in self._required:
                errors[name].add('Required')
                if isinstance(source, BaseException):
                    errors[name].add(str(body))
                continue
            else:
                continue

            if is_array:
                vtype = schema['items']['type']
                vformat = schema['items'].get('format')
            else:
                vformat = schema.get('format')

            if source is body and isinstance(body, dict):
                pass
            elif vtype not in ('string', 'file'):
                value = convert(name, value, vtype, vformat, errors)

            if vtype == 'file':
                files[name] = value
            else:
                parameters[name] = value

        parameters = self._validate(parameters, errors)
        parameters.update(files)
        return parameters, errors
117966
def _validate_mets_file_group_names(self):
        
        for fileGrp in self.mets.file_groups:
            if not fileGrp.startswith(FILE_GROUP_PREFIX):
                self.report.add_notice("fileGrp USE does not begin with '%s': %s" % (FILE_GROUP_PREFIX, fileGrp))
            else:
                # OCR-D-FOO-BAR -> ('FOO', 'BAR')
                # \____/\_/ \_/
                #   |    |   |
                # Prefix |  Name
                #     Category
                category = fileGrp[len(FILE_GROUP_PREFIX):]
                name = None
                if '-' in category:
                    category, name = category.split('-', 1)
                if category not in FILE_GROUP_CATEGORIES:
                    self.report.add_error("Unspecified USE category '%s' in fileGrp '%s'" % (category, fileGrp))
                if name is not None and not re.match(r'^[A-Z0-9-]{3,}$', name):
                    self.report.add_error("Invalid USE name '%s' in fileGrp '%s'" % (name, fileGrp))
1309831
def validate(filename):
    
    import HTMLParser
    from py_w3c.validators.html.validator import HTMLValidator

    h = HTMLParser.HTMLParser()  # for unescaping WC3 messages

    vld = HTMLValidator()
    LOG.info("Validating: {0}".format(filename))

    # call w3c webservice
    vld.validate_file(filename)

    # display errors and warning
    for err in vld.errors:
        LOG.error(u'line: {0}; col: {1}; message: {2}'.
                  format(err['line'], err['col'], h.unescape(err['message']))
                  )
    for err in vld.warnings:
        LOG.warning(u'line: {0}; col: {1}; message: {2}'.
                    format(err['line'], err['col'], h.unescape(err['message']))
                    )
908037
def check_infile(filename):
    
    if os.path.isfile(filename):
        domain = os.path.basename(filename).split('.txt')[0]
        return domain
    else:
        sys.stderr.write("ERROR: %s : No such file\n" % filename)
        sys.exit(1)
453574
public static String toValidFileName(String fileName) {
        // adds MAX_VALUE to eliminate minus character which might be returned by hashCode()
        return Long.toString((long) fileName.hashCode() + Integer.MAX_VALUE);
    }
760886
def __get_file(self, file):
        
        file_object = None
        if file['name'] in request.files:
            file_object = request.files[file['name']]
            clean_filename = secure_filename(file_object.filename)
            if clean_filename == '':
                return file_object
            if file_object and self.__allowed_extension(
                    clean_filename, file['extensions']):
                return file_object
        elif file['name'] not in request.files and file['required']:
            return file_object
        return file_object
1316221
def _valid_file(self, base, name):
        """"""

        valid = False
        fullpath = os.path.join(base, name)
        if self.file_check is not None and self.compare_file(fullpath[self._base_len:] if self.file_pathname else name):
            valid = True
        if valid and (not self.show_hidden and util.is_hidden(fullpath)):
            valid = False
        return self.on_validate_file(base, name) if valid else valid
689398
def input_file(filename):
    
    if excluded(filename) or not filename_match(filename):
        return {}
    if options.verbose:
        message('checking ' + filename)
    options.counters['files'] = options.counters.get('files', 0) + 1
    errors = Checker(filename).check_all()
    if options.testsuite and not errors:
        message("%s: %s" % (filename, "no errors found"))
    return errors
1221863
def validate (self):
    
    if not os.path.isfile(self.pathname):
      self.message.append('Filename "%s" does not exist.')
    else:
      try:
        with open(self.pathname, 'r') as stream:
          pass
      except IOError:
        self.messages.append('Could not open "%s" for reading.' % self.pathname)

    for line in self.commands:
      messages = [ ]
      if line.cmd and not line.cmd.validate(messages):
        msg = 'error: %s: %s' % (line.cmd.name, " ".join(messages))
        self.log.messages.append(msg)

    return len(self.log.messages) == 0
83896
def plugin_valid(self, filename):
        
        filename = os.path.basename(filename)
        for regex in self.regex_expressions:
            if regex.match(filename):
                return True
        return False
1155759
def api_submit():
    
    data = request.files.file
    response.content_type = 'application/json'
    if not data or not hasattr(data, 'file'):
        return json.dumps({"status": "Failed", "stderr": "Missing form params"})
    return json.dumps(analyse_pcap(data.file, data.filename), default=jsondate, indent=4)
554683
def _submit(self, pathfile, filedata, filename):
		'''
		
		'''
		if pathfile and os.path.exists(pathfile):
			files = {'file': open(pathfile, 'rb')}
		elif filedata:
			assert filename
			files = {'file' : (filename, io.BytesIO(filedata))}
		else:
			raise ValueError("You must pass either a valid file path, or a bytes array containing the captcha image!")

		payload = {
			'key'    : self.api_key,
			'method' : 'post',
			'json'   : True,
			}

		self.log.info("Uploading to 2Captcha.com.")

		url = self.getUrlFor('input', {})

		request = requests.post(url, files=files, data=payload)

		if not request.ok:
			raise exc.CaptchaSolverFailure("Posting captcha to solve failed!")

		resp_json = json.loads(request.text)
		return self._process_response(resp_json)