Guess by checking BOM, and checking `_special_encode_check`, and using memory map.
422625
def _detect_buffer_encoding(self, f):
        """"""

        encoding = None
        with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
            encoding = self._analyze_file(m)
        return encoding
95314
def guess_mimetype(filename):
    
    m, encoding = mimetypes.guess_type(filename)
    if encoding:
        m = ENCODING_MIMETYPES.get(encoding, None)
    return m or 'application/octet-stream'
59986
def guess_type(typ):
    ''''''
    # Strip useless numbers
    match = re.match("([a-zA-Z]+)\d*", typ)
    if match:
        typ = match.groups()[0]
        return typ
881259
def detect_encoding_and_remove_bom(buf, default_encoding='UTF-8'):
    
    if not isinstance(buf, bytes):
        raise TypeError('buf should be a bytes instance but it is a %s: ' % type(buf).__name__)
    for bom, encoding in _byte_order_marks:
        if buf.startswith(bom):
            return buf[len(bom):], encoding
    return buf, default_encoding
1172426
def _map_fb_memory(fbfid, fix_info):
        """"""
        return mmap.mmap(
            fbfid,
            fix_info.smem_len,
            mmap.MAP_SHARED,
            mmap.PROT_READ | mmap.PROT_WRITE,
            offset=0
        )
154173
def guess_sequence(redeem_script):
    '''
    
    '''
    try:
        script_array = redeem_script.split()
        loc = script_array.index('OP_CHECKSEQUENCEVERIFY')
        return int(script_array[loc - 1], 16)
    except ValueError:
        return 0xFFFFFFFE
281878
private void memorySizeCheck(){
		if (this.stm.numInstances() + this.ltm.numInstances() > this.maxSTMSize + this.maxLTMSize){
			if (this.ltm.numInstances() > this.maxLTMSize){
				this.clusterDown();
			}else{ //shift values from STM directly to LTM since STM is full
				int numShifts = this.maxLTMSize - this.ltm.numInstances() + 1;
				for (int i = 0; i < numShifts; i++){
					this.ltm.add(this.stm.get(0).copy());
					this.stm.delete(0);
					this.stmHistory.remove(0);
					this.ltmHistory.remove(0);
					this.cmHistory.remove(0);
				}
				this.clusterDown();
				this.predictionHistories.clear();
				for (int i = 0; i < this.stm.numInstances(); i++){
					for (int j = 0; j < this.stm.numInstances(); j++){
						this.distanceMatrixSTM[i][j] = this.distanceMatrixSTM[numShifts+i][numShifts+j];
					}
				}
			}
		}
	}
675767
static final int checkMaxLgArrLongs(final Memory dstMem) {
    final int preBytes = CONST_PREAMBLE_LONGS << 3;
    final long cap = dstMem.getCapacity();
    final int maxLgArrLongs =
        Integer.numberOfTrailingZeros(floorPowerOf2((int)(cap - preBytes)) >>> 3);
    if (maxLgArrLongs < MIN_LG_ARR_LONGS) {
      throw new SketchesArgumentException(
        "dstMem not large enough for minimum sized hash table: " + cap);
    }
    return maxLgArrLongs;
  }
386004
def has_bom(self, filestream):
        """"""

        content = filestream.read(4)
        if content == b'PK\x03\x04':
            # Zip file found.
            # Return `BINARY_ENCODE` as content is binary type,
            # but don't return None which means we don't know what we have.
            return filters.BINARY_ENCODE
        # We only handle zip files, so if we are checking this, we've already failed.
        return None
771005
function stripBOM (str) {
  var bom = str.charCodeAt(0);

  // Check for the UTF-16 byte order mark (0xFEFF or 0xFFFE)
  if (bom === 0xFEFF || bom === 0xFFFE) {
    return str.slice(1);
  }

  return str;
}
893378
def detectRamPorts(stm: IfContainer, current_en: RtlSignalBase):
    
    if stm.ifFalse or stm.elIfs:
        return
    for _stm in stm.ifTrue:
        if isinstance(_stm, IfContainer):
            yield from detectRamPorts(_stm, _stm.cond & current_en)
        elif isinstance(_stm, Assignment):
            if isinstance(_stm.dst._dtype, HArray):
                assert len(_stm.indexes) == 1, "one address per RAM port"
                w_addr = _stm.indexes[0]
                mem = _stm.dst
                yield (RAM_WRITE, mem, w_addr, current_en, _stm.src)
            elif _stm.src.hidden and len(_stm.src.drivers) == 1:
                op = _stm.src.drivers[0]
                mem = op.operands[0]
                if isinstance(mem._dtype, HArray) and op.operator == AllOps.INDEX:
                    r_addr = op.operands[1]
                    if _stm.indexes:
                        raise NotImplementedError()
                    yield (RAM_READ, mem, r_addr, current_en, _stm.dst)
811155
function ensureMap(set) {
            if (!set['[[SetData]]']) {
              var m = set['[[SetData]]'] = new collectionShims.Map();
              Object.keys(set._storage).forEach(function(k) {
                // fast check for leading '$'
                if (k.charCodeAt(0) === 36) {
                  k = k.substring(1);
                } else {
                  k = +k;
                }
                m.set(k, k);
              });
              set._storage = null; // free old backing storage
            }
          }
873533
def detect_unicode_bom(str)
      bom_bytes = str.byteslice(0, 4).bytes.to_a

      BOM.each do |encoding, bytes|
        if bom_bytes[0, bytes.size] == bytes
          str = str.dup
          str.force_encoding(Encoding::BINARY)
          str.slice!(0, bytes.size)
          str.force_encoding(encoding)
          return str
        end
      end

      return str
    end
468750
private static String guessEncodingByNutch(byte[] content) {
        int length = Math.min(content.length, CHUNK_SIZE);

        String str = "";
        try {
            str = new String(content, "ascii");
        } catch (UnsupportedEncodingException e) {
            return null;
        }

        Matcher metaMatcher = metaPattern.matcher(str);
        String encoding = null;
        if (metaMatcher.find()) {
            Matcher charsetMatcher = charsetPattern.matcher(metaMatcher.group(1));
            if (charsetMatcher.find()) {
                encoding = new String(charsetMatcher.group(1));
            }
        }
        if (encoding == null) {
            metaMatcher = charsetPatternHTML5.matcher(str);
            if (metaMatcher.find()) {
                encoding = new String(metaMatcher.group(1));
            }
        }
        if (encoding == null) {
            if (length >= 3 && content[0] == (byte) 0xEF
                    && content[1] == (byte) 0xBB && content[2] == (byte) 0xBF) {
                encoding = "UTF-8";
            } else if (length >= 2) {
                if (content[0] == (byte) 0xFF && content[1] == (byte) 0xFE) {
                    encoding = "UTF-16LE";
                } else if (content[0] == (byte) 0xFE
                        && content[1] == (byte) 0xFF) {
                    encoding = "UTF-16BE";
                }
            }
        }

        return encoding;
    }
41952
def guess_phred_format(self):
        """"""
        # Possibilities #
        self.intervals = {
            'Sanger':       (33,  74),         # <- This one is the gold standard
            'Solexa':       (59, 105),
            'Illumina-1.3': (64, 105),         # <- These were abandoned after they wised up.
            'Illumina-1.5': (67, 105),         # <- These were abandoned after they wised up.
        }
        # Initialize variables #
        glob_min  = 9999
        glob_max  = 0
        take_next = False
        # Stop after #
        max_sequences_to_consider = 2000000
        # Error message #
        message = "Multiple PHRED encodings possible for '%s'.\n"
        # Loop #
        self.open()
        for i, line in enumerate(self.handle):
            # Are we on the PHRED line? #
            if not take_next:
                take_next = line.startswith('+')
                continue
            # Now we are on the PHRED line! #
            take_next = False
            current_min, current_max = self.get_qual_range(line.rstrip('\n'))
            if current_min < glob_min or current_max > glob_max:
                glob_min = min(current_min, glob_min)
                glob_max = max(current_max, glob_max)
                valid_encodings = [e for e, r in self.intervals.items() if glob_min >= r[0] and glob_max <= r[1]]
                if len(valid_encodings) == 0:
                    message = "Illegal PHRED encoding for '%s'.\n"
                    break
                if len(valid_encodings) == 1:
                    return valid_encodings[0]
            # Stop condition #
            if i >= max_sequences_to_consider: break
        # It didn't work #
        message += "Maximum detected value is: %s.\n"
        message += "Minimum detected value is: %s.\n"
        message += "Possibilities are: %s."
        message  = message % (self, glob_max, glob_min, ' or '.join(valid_encodings))
        raise Exception(message)
611501
def memoryCheck(vms_max_kb):
    
    safety_factor = 1.2
    vms_max = vms_max_kb
    vms_gigs = vms_max / 1024 ** 2
    buffer = safety_factor * vms_max
    buffer_gigs = buffer / 1024 ** 2
    vm = psutil.virtual_memory()
    free_gigs = vm.available / 1024 ** 2
    if vm.available < buffer:
        raise MemoryError('Running this requires quite a bit of memory ~ '
                          f'{vms_gigs:.2f}, you have {free_gigs:.2f} of the '
                          f'{buffer_gigs:.2f} needed')
797020
function amf0encBool(num) {
    var buf = new Buffer(2);
    buf.writeUInt8(0x01, 0);
    buf.writeUInt8((num ? 1 : 0), 1);
    return buf;
}