Generate a filename from a pattern.
421254
private File generate(String pattern, int generation, int unique) throws IOException {
        File file = null;
        String word = "";
        int ix = 0;
        boolean sawg = false;
        boolean sawu = false;
        while (ix < pattern.length()) {
            char ch = pattern.charAt(ix);
            ix++;
            char ch2 = 0;
            if (ix < pattern.length()) {
                ch2 = Character.toLowerCase(pattern.charAt(ix));
            }
            if (ch == '/') {
                if (file == null) {
                    file = new File(word);
                } else {
                    file = new File(file, word);
                }
                word = "";
                continue;
            } else  if (ch == '%') {
                if (ch2 == 't') {
                    String tmpDir = System.getProperty("java.io.tmpdir");
                    if (tmpDir == null) {
                        tmpDir = System.getProperty("user.home");
                    }
                    file = new File(tmpDir);
                    ix++;
                    word = "";
                    continue;
                } else if (ch2 == 'h') {
                    file = new File(System.getProperty("user.home"));
                    // Android-changed: Don't make a special exemption for setuid programs.
                    //
                    // if (isSetUID()) {
                    //     // Ok, we are in a set UID program.  For safety's sake
                    //     // we disallow attempts to open files relative to %h.
                    //     throw new IOException("can't use %h in set UID program");
                    // }
                    ix++;
                    word = "";
                    continue;
                } else if (ch2 == 'g') {
                    word = word + generation;
                    sawg = true;
                    ix++;
                    continue;
                } else if (ch2 == 'u') {
                    word = word + unique;
                    sawu = true;
                    ix++;
                    continue;
                } else if (ch2 == '%') {
                    word = word + "%";
                    ix++;
                    continue;
                }
            }
            word = word + ch;
        }
        if (count > 1 && !sawg) {
            word = word + "." + generation;
        }
        if (unique > 0 && !sawu) {
            word = word + "." + unique;
        }
        if (word.length() > 0) {
            if (file == null) {
                file = new File(word);
            } else {
                file = new File(file, word);
            }
        }
        return file;
    }
392060
def get_filebase(path, pattern):
    """"""
    # A pattern can include directories
    tail_len = len(pattern.split(os.path.sep))
    return os.path.join(*str(path).split(os.path.sep)[-tail_len:])
189888
def funname(file):
    """"""
    if isinstance(file, str):
        files = [file]
    else:
        files = file
    bases = [os.path.basename(f) for f in files]
    names = [os.path.splitext(b)[0] for b in bases]
    if isinstance(file, str):
        return names[0]
    else:
        return names
406007
def get_filenames(directory):
    """"""
    for filename in os.listdir(directory):
        if re.search(r"cp\d{2}mu?-manylinux1_\S+\.whl", filename):
            yield filename
327271
def interleaved_filename(file_path):
    """"""
    if not isinstance(file_path, tuple):
        raise OneCodexException("Cannot get the interleaved filename without a tuple.")
    if re.match(".*[._][Rr][12][_.].*", file_path[0]):
        return re.sub("[._][Rr][12]", "", file_path[0])
    else:
        warnings.warn("Paired-end filenames do not match--are you sure they are correct?")
        return file_path[0]
74412
def filename(value):
        '''
        
        '''
        return re.sub('[^a-zA-Z0-9.-_ ]', '', os.path.basename(InputSanitizer.trim(value)))
701955
def load_from_filename(self, file_name, sep='\n'):
        """"""
        fp = open(file_name, 'rb')
        n = self.load_from_file(fp, sep)
        fp.close()
        return n
1095047
def filename_from_path(path):
    
    head, tail = ntpath.split(path)
    return head, tail or ntpath.basename(head)
68106
def prefix(filename):
    '''  '''
    return os.path.split(re.sub(_afni_suffix_regex,"",str(filename)))[1]
918391
def filename(self, value):
        """"""
        warnings.warn(
            "The 'filename' attribute will be removed in future versions.  "
            "Use 'source' instead.",
            DeprecationWarning, stacklevel=2
        )
        self.source = value
601279
def parseFilename(self, filename):
        """"""
        match = self.filename_regex.match(filename)
        if match is None:
            # TODO?: Raise exception?
            '''print("Filename", filename, "unrecognized!")'''
            return None
        lat = int(match.group(2))
        lon = int(match.group(4))
        if match.group(1) == "S":
            lat = -lat
        if match.group(3) == "W":
            lon = -lon
        return lat, lon
188402
def _generate_filenames(sources):
    

    for source in sources:

        if os.path.isdir(source):
            for path, dirlist, filelist in os.walk(source):
                for fname in filelist:
                    if nmrstarlib.VERBOSE:
                        print("Processing file: {}".format(os.path.abspath(fname)))
                    if GenericFilePath.is_compressed(fname):
                        if nmrstarlib.VERBOSE:
                            print("Skipping compressed file: {}".format(os.path.abspath(fname)))
                        continue
                    else:
                        yield os.path.join(path, fname)

        elif os.path.isfile(source):
            yield source

        elif GenericFilePath.is_url(source):
            yield source

        elif source.isdigit():
            try:
                urlopen(nmrstarlib.BMRB_REST + source)
                yield nmrstarlib.BMRB_REST + source
            except HTTPError:
                urlopen(nmrstarlib.PDB_REST + source + ".cif")
                yield nmrstarlib.PDB_REST + source + ".cif"

        elif re.match("[\w\d]{4}", source):
            yield nmrstarlib.PDB_REST + source + ".cif"

        else:
            raise TypeError("Unknown file source.")
651323
def rename(pattern)
      from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/'
      if to.nil?
        from, to = current_item.name, from
      else
        from = Regexp.new from
      end
      unless in_zip?
        selected_items.each do |item|
          name = item.name.gsub from, to
          FileUtils.mv item, current_dir.join(name) if item.name != name
        end
      else
        Zip::File.open(current_zip) do |zip|
          selected_items.each do |item|
            name = item.name.gsub from, to
            zip.rename item.name, name
          end
        end
      end
      ls
    end
52912
protected final void parseFileNamePattern() {
    List converters = new ArrayList();
    List fields = new ArrayList();

    ExtrasPatternParser.parse(
            fileNamePatternStr, converters, fields, null,
            ExtrasPatternParser.getFileNamePatternRules());
    patternConverters = new PatternConverter[converters.size()];
    patternConverters =
      (PatternConverter[]) converters.toArray(patternConverters);
    patternFields = new ExtrasFormattingInfo[converters.size()];
    patternFields = (ExtrasFormattingInfo[]) fields.toArray(patternFields);
  }
1081854
def __getFilenameSuffix(self, filename):
        """"""
        if filename and isinstance(filename, string_types):
            if self.__isValidTGZ(filename):
                return ".tar.gz"
            elif filename.endswith(".zip"):
                return ".zip"
922647
def explode_filename(name: str, scheme: str) -> dict:
    

    if not scheme:
        return split_filename(name)

    replacements = {
        'name': '(?P<name>.*)',
        'ext': '(?P<extension>.+)$',
        'index': '(?P<index>[0-9]{{{length}}})'
    }

    scheme_pattern = '^'
    empty_scheme_pattern = ''

    offset = 0
    while offset < len(scheme):
        char = scheme[offset]
        next_char = scheme[offset + 1] if (offset + 1) < len(scheme) else None

        if char in r'.()^$?*+\[]|':
            addition = '\\{}'.format(char)
            scheme_pattern += addition
            empty_scheme_pattern += addition
            offset += 1
            continue

        if char != '{':
            scheme_pattern += char
            empty_scheme_pattern += char
            offset += 1
            continue

        if next_char != '{':
            scheme_pattern += char
            empty_scheme_pattern += char
            offset += 1
            continue

        end_index = scheme.find('}}', offset)

        contents = scheme[offset:end_index].strip('{}').lower()

        if contents in replacements:
            scheme_pattern += replacements[contents]
        elif contents == ('#' * len(contents)):
            addition = replacements['index'].format(length=len(contents))
            scheme_pattern += addition
            empty_scheme_pattern += addition
        else:
            addition = '{{{}}}'.format(contents)
            scheme_pattern += addition
            empty_scheme_pattern += addition

        offset = end_index + 2

    match = re.compile(scheme_pattern).match(name)

    if not match:
        parts = split_filename(name)
        comparison = re.compile(empty_scheme_pattern.rstrip('-_: .\\'))
        match = comparison.match(parts['name'])
        if not match:
            return parts

    parts = match.groupdict()
    index = parts.get('index')
    index = int(index) if index else None

    return dict(
        index=index - 1,
        name=parts.get('name', ''),
        extension=parts.get('extension', 'py')
    )
965832
def expand_filename_pattern(self, pattern, base_dir, sourcefile=None):
        

        # replace vars like ${benchmark_path},
        # with converting to list and back, we can use the function 'substitute_vars()'
        expandedPattern = substitute_vars([pattern], self, sourcefile)
        assert len(expandedPattern) == 1
        expandedPattern = expandedPattern[0]

        if expandedPattern != pattern:
            logging.debug("Expanded variables in expression %r to %r.",
                          pattern, expandedPattern)

        fileList = util.expand_filename_pattern(expandedPattern, base_dir)

        # sort alphabetical,
        fileList.sort()

        if not fileList:
            logging.warning("No files found matching %r.", pattern)

        return fileList