Validates a file for module import.<p>
332459
protected void validateModuleFile() {

        try {
            m_importFile.loadAndValidate();
            String importSite = m_importFile.getModule().getImportSite();
            if (importSite != null) {
                getSiteSelector().setEnabled(false);
                getSiteSelector().setValue(importSite);
            }
            getOkButton().setEnabled(true);
        } catch (Exception e) {
            LOG.info(e.getLocalizedMessage(), e);
            m_importFile = null;
            getOkButton().setEnabled(false);
            CmsErrorDialog.showErrorDialog(e);

        }
    }
1208066
def validate(self):
        """"""

        changes = self.change_collector.collect_changes()

        features = []
        imported_okay = True
        for importer, modname, modpath in changes.new_feature_info:
            try:
                mod = importer()
                features.extend(_get_contrib_features(mod))
            except (ImportError, SyntaxError):
                logger.info(
                    'Failed to import module at {}'
                    .format(modpath))
                logger.exception('Exception details: ')
                imported_okay = False

        if not imported_okay:
            return False

        # if no features were added at all, reject
        if not features:
            logger.info('Failed to collect any new features.')
            return False

        return all(
            validate_feature_api(feature, self.X, self.y, subsample=False)
            for feature in features
        )
1253649
private void validateRootFolder() {
        File rootDir = new File(m_config.root);
        if (!rootDir.exists()) {
            logErrorThrow("Root directory does not exist: {}", m_config.root);
        } else if (!rootDir.isDirectory()) {
            logErrorThrow("Root directory must be a folder: {}", m_config.root);
        } else if (!m_config.root.endsWith(File.separator)) {
            m_config.root = m_config.root + File.separator;
        }
    }
431536
public function validateFile(): bool
    {
        return Validator::make(
            ['fileType' => finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->importer->getFilePath())],
            ['fileType' => 'required|string:text/plain|string:text/csv']
        )->passes();
    }
491685
def validate_xml(file):
    """"""
    max_file_size = current_app.config.get(
        'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
    if file.size > max_file_size:
        return False

    with file.open() as fp:
        try:
            content = fp.read().decode('utf-8')
            xml.dom.minidom.parseString(content)
            return True
        except:
            return False
1212959
public void validate() throws PackagingException {
        if (control == null || !control.isDirectory()) {
            throw new PackagingException("The 'control' attribute doesn't point to a directory. " + control);
        }

        if (changesIn != null) {

            if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {
                throw new PackagingException("The 'changesIn' setting needs to point to a readable file. " + changesIn + " was not found/readable.");
            }

            if (changesOut != null && !isWritableFile(changesOut)) {
                throw new PackagingException("Cannot write the output for 'changesOut' to " + changesOut);
            }

            if (changesSave != null && !isWritableFile(changesSave)) {
                throw new PackagingException("Cannot write the output for 'changesSave' to " + changesSave);
            }

        } else {
            if (changesOut != null || changesSave != null) {
                throw new PackagingException("The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.");
            }
        }

        if (Compression.toEnum(compression) == null) {
            throw new PackagingException("The compression method '" + compression + "' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')");
        }

        if (deb == null) {
            throw new PackagingException("You need to specify where the deb file is supposed to be created.");
        }

        getDigestCode(digest);
    }
885856
def validate(self):
        
        # Ange Albertini (@angie4771) can kill me for this! :)
        if self.dosHeader.e_magic.value != consts.MZ_SIGNATURE:
            raise excep.PEException("Invalid MZ signature. Found %d instead of %d." % (self.dosHeader.magic.value, consts.MZ_SIGNATURE))
        
        if self.dosHeader.e_lfanew.value > len(self):
            raise excep.PEException("Invalid e_lfanew value. Probably not a PE file.")
            
        if self.ntHeaders.signature.value != consts.PE_SIGNATURE: 
            raise excep.PEException("Invalid PE signature. Found %d instead of %d." % (self.ntHeaders.optionaHeader.signature.value, consts.PE_SIGNATURE))
            
        if self.ntHeaders.optionalHeader.numberOfRvaAndSizes.value > 0x10:
            print excep.PEWarning("Suspicious value for NumberOfRvaAndSizes: %d." % self.ntHeaders.optionaHeader.numberOfRvaAndSizes.value)
958123
private void validate() {
        LibraryUtils.checkArgumentNotNull(config, "configuration is null");
        LibraryUtils.checkArgumentNotNull(exceptionHandler, "exceptionHandler is null");
        LibraryUtils.checkArgumentNotNull(progressReporter, "progressReporter is null");
        LibraryUtils.checkArgumentNotNull(s3Client, "s3Client is null");
    }
1061857
@Override
	public List<ParsingError> doValidate() {

		String fileName = this.commandName + Constants.FILE_EXT_COMMANDS;
		File commandsDirectory = new File( this.context.getApp().getDirectory(), Constants.PROJECT_DIR_COMMANDS );
		File commandFileToExecute;

		List<ParsingError> result = new ArrayList<> ();
		if( Utils.isEmptyOrWhitespaces( this.commandName )) {
			result.add( error( ErrorCode.CMD_MISSING_COMMAND_NAME ));
		}

		// Prevent a commands file from invoking itself recursively
		// If the command was loaded from a file...
		else if( this.context.getCommandFile() != null
				&& fileName.equals( this.context.getCommandFile().getName())) {

			result.add( error( ErrorCode.CMD_LOOPING_COMMAND, name( this.commandName )));
		}

		// The commands file to execute must exist.
		else if( ! ( commandFileToExecute = new File( commandsDirectory, fileName )).exists()) {
			result.add( error( ErrorCode.CMD_INEXISTING_COMMAND, name( this.commandName )));
		}

		// If it exists, we do not want it to contain the same instruction.
		// Can happen if we execute a commands (not loaded from a file) that executes
		// a commands file with the same instruction...
		else {
			try {
				String content = Utils.readFileContent( commandFileToExecute );
				Pattern p = Pattern.compile( PREFIX + "\\s+" + Pattern.quote( this.commandName ), Pattern.CASE_INSENSITIVE );
				if( p.matcher( content ).find())
					result.add( error( ErrorCode.CMD_NASTY_LOOPING_COMMAND, name( this.commandName )));

			} catch( IOException e ) {
				// If we cannot load the file's content, do not push the validation further...
				Utils.logException( Logger.getLogger( getClass().getName()), e );
			}
		}

		return result;
	}
519619
@Override
	public boolean validate(final Problems problems, final String compName, final String text) {
		boolean invalid = text.contains(File.separator) || text.contains(File.pathSeparator);
		if (!invalid && Utilities.isWindows()) {
			invalid = text.contains(":");
		}
		final String result = invalid
				? ValidationBundle.getMessage(IllegalCharactersInFileNameValidator.class, "ERR_INVALID_FILE_NAME", compName, text)
				: null; // NOI18N
		if (result != null) {
			problems.add(result);
		}
		return !invalid;
	}
1344704
public void validateFileDoesNotExist(UIInput<String> directory, UIInput<String> fileName, UIValidationContext validator) {
        String resourcePath = CamelXmlHelper.createFileName(directory, fileName);
        if (files.contains(resourcePath)) {
            validator.addValidationError(fileName, "A file with that name already exists!");
        }
    }
424899
def validate(self, path):
        """"""
        # Exclude hidden files and folders with '.' prefix
        if os.path.basename(path).startswith('.'):
            return False

        # Check that current path level is more than min path and less than max path
        if not self.check_level(path):
            return False

        if self.filters:
            if not self._level_filters(path):
                return False

        # Force include and exclude iterations to be strings in case of integer filters
        # Handle exclusions
        if self.to_exclude:
            if any(str(ex).lower() in path.lower() for ex in self.to_exclude):
                return False

        # Handle inclusions
        if self.to_include:
            if not any(str(inc).lower() in path.lower() for inc in self.to_include):
                return False

        return True
851099
def validate_file(parser, arg):
    """"""
    if not os.path.isfile(arg):
        parser.error("%s is not a file." % arg)
    return arg
874250
@SuppressWarnings("unchecked")
    protected void validate() {

        if (m_ou == null) {
            m_name.removeAllValidators();
            m_name.addValidator(new NameValidator());
        }
        m_description.setRequired(true);
        m_description.setRequiredError("Required");

        if (m_ouResources.getRows().isEmpty() & !m_webuser.getValue().booleanValue()) {
            CmsPathSelectField field = new CmsPathSelectField();
            field.setUseRootPaths(true);
            field.setCmsObject(m_cms);
            m_ouResources.addRow(field);
        }
        for (I_CmsEditableGroupRow row : m_ouResources.getRows()) {
            ((AbstractField<String>)row.getComponent()).removeAllValidators();
            ((AbstractField<String>)row.getComponent()).addValidator(new ResourceValidator());
        }
    }
1209724
public static void validate(final Module module) {
        if (null == module) {
            throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
                .entity("Module cannot be null!")
                .build());
        }
        if(module.getName() == null ||
                module.getName().isEmpty()){
            throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
                    .entity("Module name cannot be null or empty!")
                    .build());
        }
        if(module.getVersion()== null ||
                module.getVersion().isEmpty()){
            throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
                    .entity("Module version cannot be null or empty!")
                    .build());
        }

        // Check artifacts
        for(final Artifact artifact: DataUtils.getAllArtifacts(module)){
            validate(artifact);
        }

        // Check dependencies
        for(final Dependency dependency: DataUtils.getAllDependencies(module)){
            validate(dependency.getTarget());
        }
    }
1123443
private function validate() : ModularParser
    {
        if (!is_string($this->modularClass)) {
            throw new RuntimeException(
                sprintf(
                    'Invalid Parent %s Class. %s extends must be as class name and string.',
                    $this->getName()
                ),
                E_WARNING
            );
        }

        $this->modularClass = rtrim($this->modularClass, '\\');
        if (!class_exists($this->modularClass)
            || strtolower($this->modularClass) != strtolower(ModularAbstract::class)
            && ! is_subclass_of($this->modularClass, ModularAbstract::class)
        ) {
            throw new RuntimeException(
                sprintf(
                    'Parent %1$s class does not extends into %2$s',
                    $this->getName(),
                    ModularAbstract::class
                )
            );
        }

        $modularClass = ltrim($this->modularClass, '\\');
        $file = $this->getFile();
        /**
         * Try to get From Cache
         */
        if (isset(self::$cachedClassesParsed[$file])) {
            $class = isset(self::$cachedClassesParsed[$file][$modularClass])
                ? self::$cachedClassesParsed[$file][$modularClass]
                : null;
            if ($class && is_string($class)) {
                $this->valid = true;
                $this->class = $class;
                return $this;
            }
            if ($class && $class instanceof \Throwable) {
                throw $class;
            }

            throw new InvalidModularException(
                sprintf(
                    'File %1$s does not contain valid class extends to `%2$s` for parser logic.',
                    $this->getName(),
                    $modularClass
                ),
                E_ERROR
            );
        }

        /**
         * strip white space is remove all new line and double spaces
         * and remove all comments
         * @see php_strip_whitespace()
         * just het 204b byte to get content
         */
        $content = substr(php_strip_whitespace($this->getFile()), 0, 2048);
        if (!$content) {
            throw new EmptyFileException(
                $this->getFile()
            );
        }

        if (strtolower(substr($content, 0, 5)) !== '<?php') {
            throw new InvalidModularException(
                sprintf(
                    'Invalid %s, %s does not start with open php tag.',
                    $this->getName()
                ),
                E_ERROR
            );
        }

        // remove declarations
        if (stripos($content, 'declare') !== false) {
            $content = preg_replace('`declare\s*\([^\)]+\)\s*\;\s*`smi', '$1', $content);
        }

        $namespace = '\\';
        if (preg_match('/\<\?php\s+namespace\s+(?P<namespace>[^;\{]+)/ms', $content, $nameSpaces)
            && !empty($nameSpaces['namespace'])
        ) {
            if (strtolower(trim($nameSpaces['namespace'])) == strtolower(__NAMESPACE__)) {
                throw new InvalidModularException(
                    sprintf(
                        'File %s contain name space of core.',
                        $this->getName()
                    ),
                    E_ERROR
                );
            }

            $namespace .= $nameSpaces['namespace'];
        }

        if ($namespace !== '\\' && preg_match('`[^\\\_a-z0-9]`i', $namespace, $match)) {
            throw new InvalidModularException(
                sprintf(
                    'File %s contain invalid name space.',
                    $this->getName()
                ),
                E_ERROR
            );
        }

        preg_match(
            '/use\s+
                (?:\\\{1})?(?P<extended>'.preg_quote($modularClass, '/').')
                (?:\s+as\s+(?P<alias>[a-z0-9_]+))?;+
            /smx',
            $content,
            $asAlias
        );

        $alias = isset($asAlias['alias'])
            ? $asAlias['alias']
            : null;
        if (!$alias && isset($asAlias['extended'])) {
            $asAlias['extended'] = explode('\\', $asAlias['extended']);
            $alias               = end($asAlias['extended']);
        }
        $content = preg_replace(
            '`^\<\?php\s+(?:namespace\s+([^;\{])*[;\{]\s*)?`smi',
            '$2',
            $content
        );

        $oldContent = $content;
        // replace for unused text
        $content = preg_replace(
            '`(use[^;]+;\s*)*\s*(class)`smi',
            '$2',
            $content
        );

        $regexNameSpace = $alias
            ? '(?P<extends>('.preg_quote($alias, '/').'))\s*'
            : '(?P<extends>('.preg_quote("\\{$modularClass}", '/') .'))\s*';
        preg_match(
            "`class\s+(?P<class>[a-z_][a-z0-9\_]+)\s+extends\s+{$regexNameSpace}`smi",
            $content,
            $class
        );

        /**
         * Try To get Use of Modular As extends Nested Name Space
         * eg :
         * Use NS1\NS2\NS3;
         * class Module extends NS3\OfModularClass;
         */
        if (empty($class['extends']) && stripos($content, ' extends ')) {
            $modularClassArray = explode('\\', ltrim($modularClass, '\\'));
            $newModularClassArray = $modularClassArray;
            array_pop($newModularClassArray);
            // check first
            $quoted = preg_quote(implode('\\', $newModularClassArray), '/');
            if (!preg_match("`use\s+\\\?(?P<alias>{$quoted}([^\s]*)?)`smi", $oldContent, $newAlias)
                || empty($newAlias['alias'])
            ) {
                $quoted = preg_quote(reset($modularClassArray), '/');
                preg_match(
                    "`use\s+\\\?(?P<alias>{$quoted}([^\s]*)?)\;`smi",
                    $oldContent,
                    $newAlias
                );
            }

            if (!empty($newAlias['alias']) && strpos($newAlias['alias'], '\\\\') === false) {
                $xpl = explode('\\', $newAlias['alias']);
                if (count($xpl) < count($modularClassArray)) {
                    $realExtendArray = array_slice($modularClassArray, count($xpl)-1);
                    $realExtend = implode('\\', $realExtendArray);
                    $regexNameSpace = '(?P<extends>('.preg_quote($realExtend, '/').'))\s*';
                    preg_match(
                        "`class\s+(?P<class>[a-z_][a-z0-9\_]+)\s+extends\s+{$regexNameSpace}`smi",
                        $content,
                        $class
                    );
                }
            }
        }

        if (empty($class['class']) || empty($class['extends']) || strpos($class['extends'], '\\\\') !== false) {
            throw new InvalidModularException(
                sprintf(
                    'File %1$s does not contain valid class extends to `%2$s` for parser logic.',
                    $this->getName(),
                    $modularClass
                ),
                E_ERROR
            );
        }

        if (strtolower(pathinfo($this->file, PATHINFO_FILENAME)) !== strtolower($class['class'])) {
            $exception = new InvalidModularException(
                sprintf(
                    'File %s does not match between file name & class.',
                    $this->getName()
                ),
                E_ERROR
            );

            self::$cachedClassesParsed[$file] = [$modularClass => $exception];
            throw $exception;
        }

        if (! preg_match('/(public\s+)?function\s+init\([^\)]*\)\s*\{/smi', $content, $match)) {
            $exception = new InvalidModularException(
                sprintf(
                    'File %s does not contain method `init`.',
                    $this->getName()
                ),
                E_ERROR
            );

            self::$cachedClassesParsed[$file] = [$modularClass => $exception];
            throw $exception;
        }

        $class = $class['class'];
        $namespace = rtrim($namespace, '\\');
        $class = "{$namespace}\\{$class}";
        // prevent multiple include file if class has been loaded
        if (class_exists($class)) {
            $exception = new InvalidModularException(
                sprintf(
                    'Object class %1$s for %2$s has been loaded.',
                    $class,
                    $this->getName()
                ),
                E_ERROR
            );

            self::$cachedClassesParsed[$file] = [$modularClass => $exception];
            throw $exception;
        }

        // start buffer
        ob_start();

        // include once
        (function ($file) {
            /** @noinspection PhpIncludeInspection */
            require_once $file;
        })->bindTo(null)($file); // binding to None of $this
        if ($error = error_get_last() && !empty($error) && $error['file'] == $file) {
            if ($error['type'] === E_ERROR) {
                @ob_end_clean();
                $exception =  new InvalidModularException(
                    sprintf(
                        'File %s contains fatal error.',
                        $this->getName()
                    ),
                    E_ERROR
                );

                self::$cachedClassesParsed[$file] = [$modularClass => $exception];
                throw $exception;
            }
        }

        // check observer and clean output buffer if there exists on module
        if (ob_get_length()) {
            @ob_end_clean();
        }

        if (!class_exists($class)) {
            $exception = new InvalidModularException(
                sprintf(
                    'File %1$s does not contain class %2$s.',
                    $this->getName(),
                    $class
                ),
                E_ERROR
            );
            self::$cachedClassesParsed[$file] = [$modularClass => $exception];
            throw $exception;
        }

        if (! method_exists($class, 'init')) {
            $exception = new InvalidModularException(
                sprintf(
                    'File %1$s does not contain method `init`.',
                    $this->getName()
                ),
                E_ERROR
            );
            self::$cachedClassesParsed[$file] = [$modularClass => $exception];
            throw $exception;
        }

        $this->valid = true;
        // trim start of class name space
        $this->class                      = ltrim($class, '\\');
        self::$cachedClassesParsed[$file] = [$modularClass => $this->class];
        return $this;
    }
105474
def validate_bam(self, input_bam):
        
        cmd = self.tools.java + " -Xmx" + self.pm.javamem
        cmd += " -jar " + self.tools.picard + " ValidateSamFile"
        cmd += " INPUT=" + input_bam
        return cmd