detect and return type for the specified Patch object
        analyzes header and filenames info

        NOTE: must be run before filenames are normalized
327142
def _detect_type(self, p):
    

    # check for SVN
    #  - header starts with Index:
    #  - next line is ===... delimiter
    #  - filename is followed by revision number
    # TODO add SVN revision
    if (len(p.header) > 1 and p.header[-2].startswith(b"Index: ")
          and p.header[-1].startswith(b"="*67)):
        return SVN

    # common checks for both HG and GIT
    DVCS = ((p.source.startswith(b'a/') or p.source == b'/dev/null')
        and (p.target.startswith(b'b/') or p.target == b'/dev/null'))

    # GIT type check
    #  - header[-2] is like "diff --git a/oldname b/newname"
    #  - header[-1] is like "index <hash>..<hash> <mode>"
    # TODO add git rename diffs and add/remove diffs
    #      add git diff with spaced filename
    # TODO http://www.kernel.org/pub/software/scm/git/docs/git-diff.html

    # Git patch header len is 2 min
    if len(p.header) > 1:
      # detect the start of diff header - there might be some comments before
      for idx in reversed(range(len(p.header))):
        if p.header[idx].startswith(b"diff --git"):
          break
      if p.header[idx].startswith(b'diff --git a/'):
        if (idx+1 < len(p.header)
            and re.match(b'index \\w{7}..\\w{7} \\d{6}', p.header[idx+1])):
          if DVCS:
            return GIT

    # HG check
    #
    #  - for plain HG format header is like "diff -r b2d9961ff1f5 filename"
    #  - for Git-style HG patches it is "diff --git a/oldname b/newname"
    #  - filename starts with a/, b/ or is equal to /dev/null
    #  - exported changesets also contain the header
    #    # HG changeset patch
    #    # User name@example.com
    #    ...
    # TODO add MQ
    # TODO add revision info
    if len(p.header) > 0:
      if DVCS and re.match(b'diff -r \\w{12} .*', p.header[-1]):
        return HG
      if DVCS and p.header[-1].startswith(b'diff --git a/'):
        if len(p.header) == 1:  # native Git patch header len is 2
          return HG
        elif p.header[0].startswith(b'# HG changeset patch'):
          return HG

    return PLAIN
929428
function getFileTypeReg(type) {
  var map = [],
    ext = fis.config.get('project.fileType.' + type);
  if (type === 'text') {
    map = TEXT_FILE_EXTS;
  } else if (type === 'image') {
    map = IMAGE_FILE_EXTS;
  } else {
    fis.log.error('invalid file type [%s]', type);
  }
  if (ext && ext.length) {
    if (typeof ext === 'string') {
      ext = ext.split(/\s*,\s*/);
    }
    map = map.concat(ext);
  }
  map = map.join('|');
  return new RegExp('\\.(?:' + map + ')$', 'i');
}
1174955
def get_filter(filetypes, ext):
    """"""
    if not ext:
        return ALL_FILTER
    for title, ftypes in filetypes:
        if ext in ftypes:
            return _create_filter(title, ftypes)
    else:
        return ''
1337787
def normalize_filename(string):
    
    if not isinstance(string, basestring):
        fail("Type of argument must be string, found '{}'"
             .format(type(string)))
    # get the file nomalizer utility
    normalizer = getUtility(IFileNameNormalizer).normalize
    return normalizer(string)
207496
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None):
    
    if youtube_id:
        return FileTypes.YOUTUBE_VIDEO_FILE
    elif web_url:
        return FileTypes.WEB_VIDEO_FILE
    elif encoding:
        return FileTypes.BASE64_FILE
    else:
        ext = os.path.splitext(filepath)[1][1:].lower()
        if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]:
            return FILE_TYPE_MAPPING[kind][ext]
    return None
119523
static function guessMimeType($file, $def = 'application/octet-stream')
	{
		// extract file extension (after . symbol)
		$ext = substr(strrchr(strtolower($file), '.'), 1);
	
		switch ( $ext )
		{
			case 'gif':
			case 'jpeg':
			case 'png':
				return "image/$ext";
			case 'jpg':
				return 'image/jpeg';
			case 'mp4':
			case 'mpeg':
			case 'avi':
				return "video/$ext";
			case 'mp3':
				return 'audio/mpeg3';
			case 'wav':
				return 'audio/wav';
			case 'pdf':
				return 'application/pdf';
			case 'htm':
			case 'html':
				return 'text/html';
			case 'txt':
				return 'text/plain';
			case 'eml':
				return 'message/rfc822';
			case 'doc':
				return 'application/msword';
			case 'docx':
				return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
			case 'xls':
				return 'application/vnd.ms-excel';
			case 'xlsx':
				return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
			case 'ppt':
			case 'pps':
				return 'application/vnd.ms-powerpoint';
			case 'pptx':
			case 'ppsx':
				return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
			case 'odt':
				return 'application/vnd.oasis.opendocument.text';
			case 'ods':
				return 'application/vnd.oasis.opendocument.spreadsheet';
			case 'odp':
				return 'application/vnd.oasis.opendocument.presentation';
			case 'zip':
				return 'application/zip';
			default :
				return $def;
		}
	}
1154735
def type(filename):
    
    assert isinstance(filename, basestring)
    while 1:
        filename, suffix = os.path.splitext (filename)
        if not suffix: return None
        suffix = suffix[1:]

        if suffix in __suffixes_to_types:
            return __suffixes_to_types[suffix]
1373556
def detect_parser_type(cls, file, encoding=None):
        '''
        '''
        is_xml = XMLDetector.is_file(file)
        doctype = cls.parse_doctype(file, encoding=encoding) or ''

        if not doctype and is_xml:
            return 'xml'

        if 'XHTML' in doctype:
            return 'xhtml'

        return 'html'
1105312
def AnalyzeFileObject(self, file_object):
    
    tsk_image_object = tsk_image.TSKFileSystemImage(file_object)

    try:
      pytsk3.Volume_Info(tsk_image_object)
    except IOError:
      return None

    return self.type_indicator
334976
def determine_file_type(filename):
    
    if filename.endswith('.cls'):
        return FileType.CLS
    elif filename.endswith('.go'):
        return FileType.GO
    elif filename.endswith('.java'):
        return FileType.JAVA
    elif filename.endswith('.js'):
        return FileType.JAVASCRIPT
    elif filename.endswith('.php'):
        return FileType.PHP
    elif filename.endswith('.py'):
        return FileType.PYTHON
    elif (
        filename.endswith(
            ('.yaml', '.yml'),
        )
    ):
        return FileType.YAML
    return FileType.OTHER
1278536
def load(self):
        
        # pylint: disable=too-many-return-statements
        if not os.path.isdir(self.patch_path):
            raise OSError('EOPatch does not exist in path {} anymore'.format(self.patch_path))

        path = self.get_file_path()
        if not os.path.exists(path):
            raise OSError('Feature in path {} does not exist anymore'.format(path))

        file_formats = FileFormat.split_by_extensions(path)[1:]

        if not file_formats or file_formats[-1] is FileFormat.PICKLE:
            with open(path, "rb") as infile:
                data = pickle.load(infile)

                if isinstance(data, sentinelhub.BBox) and not hasattr(data, 'crs'):
                    return self._correctly_load_bbox(data, path)
                return data

        if file_formats[-1] is FileFormat.NPY:
            if self.mmap:
                return np.load(path, mmap_mode='r')
            return np.load(path)

        if file_formats[-1] is FileFormat.GZIP:
            if file_formats[-2] is FileFormat.NPY:
                return np.load(gzip.open(path))

            if len(file_formats) == 1 or file_formats[-2] is FileFormat.PICKLE:
                data = pickle.load(gzip.open(path))

                if isinstance(data, sentinelhub.BBox) and not hasattr(data, 'crs'):
                    return self._correctly_load_bbox(data, path, is_zipped=True)
                return data

        raise ValueError('Could not load data from unsupported file format {}'.format(file_formats[-1]))
113032
function lookupType (path, spec, types) {
  const type = (() => {
    const match = R.path(path, spec).match(/^#\/definitions\/(.+)/)
    if (match !== void 0) {
      return match[1]
    } else {
      throw Error(`Reference path does not meet specification: ${path}`)
    }
  })()

  if (type in types) {
    return types[type]
  } else {
    throw Error(`Couldn't find definition for ${type}`)
  }
}
539225
function (type, disposition) {
        Header.isHeader(type) && (type = type.value);
        Header.isHeader(disposition) && (disposition = disposition.value);

        // validate that the content type exists
        if (!(type && _.isString(type))) { return; }

        var normalised = mimeFormat.lookup(type),
            info = {};

        _.assign(info, {
            type: normalised.type, // sanitised mime type base
            format: normalised.format, // format specific to the type returned
            name: DEFAULT_RESPONSE_FILENAME,
            ext: mimeType.extension(normalised.source) || E, // file extension from sanitised content type
            charset: normalised.charset || UTF8,

            // also storing some meta info for possible debugging
            _originalContentType: type, // the user provided mime type
            _sanitisedContentType: normalised.source, // sanitised mime type
            _accuratelyDetected: !normalised.orphan // this being true implies worse case (raw render)
        });

        // build the file name from extension
        info.filename = info.name;
        info.ext && (info.filename += (DOT + info.ext));

        return info;
    }
1065557
async function isFileOfType(filename, condition){
    try{
        // get stats
        const stats = await _fs.stat(filename);

        // is directory ?
        return condition(stats);
    }catch(e){
        // file not found error ?
        if (e.code === 'ENOENT'){
            return false;
        }else{
            throw e;
        }
    }
}
754428
def is_regex_type(type_):
    

    return (
        callable(type_)
        and getattr(type_, "__name__", None) == REGEX_TYPE_NAME
        and hasattr(type_, "__supertype__")
        and is_compiled_pattern(type_.__supertype__)
    )
453277
function _monkeypatch(filePath, monkeyPatched, processor, complete) {
  async.waterfall(
    [
      function read(next) {
        fs.readFile(filePath, 'utf8', next);
      },

      // TODO - need to parse gyp file - this is a bit hacker
      function monkeypatch(content, next) {
        if (monkeyPatched(content)) return complete();

        _log('monkey patch %s', filePath);
        processor(content, next);
      },

      function write(content, next) {
        fs.writeFile(filePath, content, 'utf8', function(err) {
          return next(err);
        });
      },
    ],
    complete,
  );
}
9069
function detectMimeType() {
  var extension = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

  extension = extension.toString().toLowerCase().replace(/\s/g, '').replace(/^\./g, '');

  if (!(extension in _listExtensions.extensions)) {
    return 'application/octet-stream';
  }

  if (typeof _listExtensions.extensions[extension] === 'string') {
    return _listExtensions.extensions[extension];
  }

  // search for name match
  for (var i = 0, len = _listExtensions.extensions[extension].length; i < len; i++) {
    var mimePart = _listExtensions.extensions[extension][i].split('/')[1];
    if (mimePart === extension) {
      return _listExtensions.extensions[extension][i];
    }
  }

  // use the first one
  return _listExtensions.extensions[extension][0];
}