Check magic sequence. Note that subclasses are responsible to decide if
something should be read from buffer. This approach was taken to support
old format without magic sequence.
772027
protected boolean isMagicCorrect(BufferedReader br) throws IOException {
        if (mCheckMagicSequence) {
            String magicLine = br.readLine();
            return (magicLine != null && magicLine.equals(mMode.getMagicSequence()));
        } else {
            return true;
        }
    }
451138
private void verifyMagicBytes(TLVInputStream input) throws InvalidPublicationsFileException {
        try {
            byte[] magicBytes = new byte[PUBLICATIONS_FILE_MAGIC_BYTES_LENGTH];
            input.read(magicBytes);
            if (!Arrays.equals(magicBytes, FILE_BEGINNING_MAGIC_BYTES)) {
                throw new InvalidPublicationsFileException("Invalid publications file magic bytes");
            }
        } catch (IOException e) {
            throw new InvalidPublicationsFileException("Checking publications file magic bytes failed", e);
        }
    }
1175072
def _do_read(self, collection, version, symbol, index_range=None):
        
        from_index = index_range[0] if index_range else None
        to_index = version['up_to']
        if index_range and index_range[1] and index_range[1] < version['up_to']:
            to_index = index_range[1]
        segment_count = version.get('segment_count') if from_index is None else None

        spec = _spec_fw_pointers_aware(symbol, version, from_index, to_index)

        data = bytearray()
        i = -1
        for i, x in enumerate(sorted(collection.find(spec), key=itemgetter('segment'))):
            data.extend(decompress(x['data']) if x['compressed'] else x['data'])

        # Check that the correct number of segments has been returned
        if segment_count is not None and i + 1 != segment_count:
            raise OperationFailure("Incorrect number of segments returned for {}:{}.  Expected: {}, but got {}. {}".format(
                                   symbol, version['version'], segment_count, i + 1, collection.database.name + '.' + collection.name))

        dtype = self._dtype(version['dtype'], version.get('dtype_metadata', {}))
        rtn = np.frombuffer(data, dtype=dtype).reshape(version.get('shape', (-1)))
        return rtn
1314195
def ignore?(buf)
      return true if /^\s*$/ =~ buf
      return false if Readline::HISTORY.empty?

      buffer[Readline::HISTORY.length - 1] == buf
    end
873311
private void readPage(byte[] buffer, Table table)
   {
      int magicNumber = getShort(buffer, 0);
      if (magicNumber == 0x4400)
      {
         //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, ""));
         int recordSize = m_definition.getRecordSize();
         RowValidator rowValidator = m_definition.getRowValidator();
         String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();

         int index = 6;
         while (index + recordSize <= buffer.length)
         {
            //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, ""));
            int btrieveValue = getShort(buffer, index);
            if (btrieveValue != 0)
            {
               Map<String, Object> row = new HashMap<String, Object>();
               row.put("ROW_VERSION", Integer.valueOf(btrieveValue));
               for (ColumnDefinition column : m_definition.getColumns())
               {
                  Object value = column.read(index, buffer);
                  //System.out.println(column.getName() + ": " + value);
                  row.put(column.getName(), value);
               }

               if (rowValidator == null || rowValidator.validRow(row))
               {
                  table.addRow(primaryKeyColumnName, row);
               }
            }
            index += recordSize;
         }
      }
   }
1052105
public void checkOrRepairSequence(final int partition, final long nextSequence, final boolean viaAntiEntropy) {
        assert nextSequence > 0;

        MetaDataContainer metaData = getMetaDataContainer(partition);
        while (true) {
            final long currentSequence = metaData.getSequence();
            if (currentSequence >= nextSequence) {
                break;
            }
            if (metaData.casSequence(currentSequence, nextSequence)) {
                final long sequenceDiff = nextSequence - currentSequence;
                if (viaAntiEntropy || sequenceDiff > 1L) {
                    // we have found at least one missing sequence between current and next sequences. if miss is detected by
                    // anti-entropy, number of missed sequences will be `miss = next - current`, otherwise it means miss is
                    // detected by observing received invalidation event sequence numbers and number of missed sequences will be
                    // `miss = next - current - 1`.
                    final long missCount = viaAntiEntropy ? sequenceDiff : sequenceDiff - 1;
                    final long totalMissCount = metaData.addAndGetMissedSequenceCount(missCount);

                    if (logger.isFinestEnabled()) {
                        logger.finest(format("%s:[map=%s,partition=%d,currentSequence=%d,nextSequence=%d,totalMissCount=%d]",
                                "Invalid sequence", name, partition, currentSequence, nextSequence, totalMissCount));
                    }
                }
                break;
            }
        }
    }
53061
def _check(self, file):
        

        if not os.path.exists(file):
            raise Error("file \"{}\" not found".format(file))

        _, extension = os.path.splitext(file)
        try:
            check = self.extension_map[extension[1:]]
        except KeyError:
            magic_type = magic.from_file(file)
            for name, cls in self.magic_map.items():
                if name in magic_type:
                    check = cls
                    break
            else:
                raise Error("unknown file type \"{}\", skipping...".format(file))

        try:
            with open(file) as f:
                code = "\n".join(line.rstrip() for line in f)
        except UnicodeDecodeError:
            raise Error("file does not seem to contain text, skipping...")

        # Ensure we don't warn about adding trailing newline
        try:
            if code[-1] != '\n':
                code += '\n'
        except IndexError:
            pass

        return check(code)
158259
private boolean readRequiredBytes() {
    int totalBytesRead = 0;
    int deflatedBytesRead = 0;
    try {
      if (nextFrame == null) {
        nextFrame = new CompositeReadableBuffer();
      }

      // Read until the buffer contains all the required bytes.
      int missingBytes;
      while ((missingBytes = requiredLength - nextFrame.readableBytes()) > 0) {
        if (fullStreamDecompressor != null) {
          try {
            if (inflatedBuffer == null || inflatedIndex == inflatedBuffer.length) {
              inflatedBuffer = new byte[Math.min(missingBytes, MAX_BUFFER_SIZE)];
              inflatedIndex = 0;
            }
            int bytesToRead = Math.min(missingBytes, inflatedBuffer.length - inflatedIndex);
            int n = fullStreamDecompressor.inflateBytes(inflatedBuffer, inflatedIndex, bytesToRead);
            totalBytesRead += fullStreamDecompressor.getAndResetBytesConsumed();
            deflatedBytesRead += fullStreamDecompressor.getAndResetDeflatedBytesConsumed();
            if (n == 0) {
              // No more inflated data is available.
              return false;
            }
            nextFrame.addBuffer(ReadableBuffers.wrap(inflatedBuffer, inflatedIndex, n));
            inflatedIndex += n;
          } catch (IOException e) {
            throw new RuntimeException(e);
          } catch (DataFormatException e) {
            throw new RuntimeException(e);
          }
        } else {
          if (unprocessed.readableBytes() == 0) {
            // No more data is available.
            return false;
          }
          int toRead = Math.min(missingBytes, unprocessed.readableBytes());
          totalBytesRead += toRead;
          nextFrame.addBuffer(unprocessed.readBytes(toRead));
        }
      }
      return true;
    } finally {
      if (totalBytesRead > 0) {
        listener.bytesRead(totalBytesRead);
        if (state == State.BODY) {
          if (fullStreamDecompressor != null) {
            // With compressed streams, totalBytesRead can include gzip header and trailer metadata
            statsTraceCtx.inboundWireSize(deflatedBytesRead);
            inboundBodyWireSize += deflatedBytesRead;
          } else {
            statsTraceCtx.inboundWireSize(totalBytesRead);
            inboundBodyWireSize += totalBytesRead;
          }
        }
      }
    }
  }
331435
function magic(buf, cb) {
  setTimeout(() => {
    const sampleLength = 24;
    const sample = buf.slice(0, sampleLength).toString('hex'); // lookup data

    const found = Object.keys(_magicDb2.default).find(it => {
      return sample.indexOf(it) != -1;
    });

    if (found) {
      cb(null, _magicDb2.default[found]);
    } else {
      cb(new Error('Magic number not found'));
    }
  }, 0);
}
997192
def is_sequence(obj):
    """"""
    return isinstance(obj, Sequence) and not (
        isinstance(obj, str) or BinaryClass.is_valid_type(obj))
815952
private static boolean canRead(final DataInput pInput, final boolean pReset) {
        long pos = FREE_SID;
        if (pReset) {
            try {
                if (pInput instanceof InputStream && ((InputStream) pInput).markSupported()) {
                    ((InputStream) pInput).mark(8);
                }
                else if (pInput instanceof ImageInputStream) {
                    ((ImageInputStream) pInput).mark();
                }
                else if (pInput instanceof RandomAccessFile) {
                    pos = ((RandomAccessFile) pInput).getFilePointer();
                }
                else if (pInput instanceof LittleEndianRandomAccessFile) {
                    pos = ((LittleEndianRandomAccessFile) pInput).getFilePointer();
                }
                else {
                    return false;
                }
            }
            catch (IOException ignore) {
                return false;
            }
        }

        try {
            byte[] magic = new byte[8];
            pInput.readFully(magic);
            return Arrays.equals(magic, MAGIC);
        }
        catch (IOException ignore) {
            // Ignore
        }
        finally {
            if (pReset) {
                try {
                    if (pInput instanceof InputStream && ((InputStream) pInput).markSupported()) {
                        ((InputStream) pInput).reset();
                    }
                    else if (pInput instanceof ImageInputStream) {
                        ((ImageInputStream) pInput).reset();
                    }
                    else if (pInput instanceof RandomAccessFile) {
                        ((RandomAccessFile) pInput).seek(pos);
                    }
                    else if (pInput instanceof LittleEndianRandomAccessFile) {
                        ((LittleEndianRandomAccessFile) pInput).seek(pos);
                    }
                }
                catch (IOException e) {
                    // TODO: This isn't actually good enough...
                    // Means something fucked up, and will fail...
                    e.printStackTrace();
                }
            }
        }

        return false;
    }
843363
def check_multiline_sequence(node, sequence, index)
      return unless sequence.members.size > 1
      return unless sequence.members[2..-1].any? { |member| member == "\n" }

      add_lint(node.line + index, MESSAGE)
    end
1146431
def checkseq(sequence: str=None,  code="ATGC") -> bool:
    
    for base in sequence:
        if base not in code:
            return False
    return True
124196
private int getMagicNumber(InputStream in)
	throws IOException {


		int t = in.read();
		if (t < 0) throw new EOFException("Failed to read magic number");
		int magic = (t & 0xff) << 8;
		t = in.read();
		if (t < 0) throw new EOFException("Failed to read magic number");
		magic += t & 0xff;

		return magic;
	}
771663
def is_magic(line, language, global_escape_flag=True):
    """"""
    if language in ['octave', 'matlab']:
        return False
    if _MAGIC_FORCE_ESC_RE.get(language, _MAGIC_FORCE_ESC_RE['python']).match(line):
        return True
    if not global_escape_flag or _MAGIC_NOT_ESC_RE.get(language, _MAGIC_NOT_ESC_RE['python']).match(line):
        return False
    if _MAGIC_RE.get(language, _MAGIC_RE['python']).match(line):
        return True
    if language != 'python':
        return False
    if _PYTHON_HELP_OR_BASH_CMD.match(line):
        return True
    return _PYTHON_MAGIC_CMD.match(line)
426570
def pyc_load(fp):
    

    magic_1 = U16(fp.read(2), target=MARSHAL_TARGET)
    magic_2 = U16(fp.read(2), target=MARSHAL_TARGET)

    internals = MAGIC_MAP.get(magic_1)
    if internals is None:
        raise ValueError('Invalid or unknown magic (%d).' % magic_1)

    if magic_2 != 2573:
        raise ValueError('Invalid secondary magic (%d).' % magic_2)

    timestamp = datetime.datetime.fromtimestamp(U32(fp.read(4), target=MARSHAL_TARGET))

    if internals['version'] >= 33:
        file_size = U32(fp.read(4))
    else:
        file_size = None

    code_object = marshal_load(fp, internals)

    return PycFile(magic_1, internals, timestamp, file_size, code_object)
1064349
public boolean check(ByteBuffer data)
    {
        assert (data != null);
        int size = data.limit();
        //  This function is on critical path. It deliberately doesn't use
        //  recursion to get a bit better performance.
        Trie current = this;
        int start = 0;
        while (true) {
            //  We've found a corresponding subscription!
            if (current.refcnt > 0) {
                return true;
            }

            //  We've checked all the data and haven't found matching subscription.
            if (size == 0) {
                return false;
            }

            //  If there's no corresponding slot for the first character
            //  of the prefix, the message does not match.
            byte c = data.get(start);
            if (c < current.min || c >= current.min + current.count) {
                return false;
            }

            //  Move to the next character.
            if (current.count == 1) {
                current = current.next[0];
            }
            else {
                current = current.next[c - current.min];
                if (current == null) {
                    return false;
                }
            }
            start++;
            size--;
        }
    }