Seek in data.

        On uncompressed files, the seeking works by actual
        seeks so it's fast.  On compresses files its slow
        - forward seeking happends by reading ahead,
        backwards by re-opening and decompressing from the start.
437394
def seek(self, ofs, whence=0):
        

        # disable crc check when seeking
        self._md_context = NoHashContext()

        fsize = self._inf.file_size
        cur_ofs = self.tell()

        if whence == 0:     # seek from beginning of file
            new_ofs = ofs
        elif whence == 1:   # seek from current position
            new_ofs = cur_ofs + ofs
        elif whence == 2:   # seek from end of file
            new_ofs = fsize + ofs
        else:
            raise ValueError('Invalid value for whence')

        # sanity check
        if new_ofs < 0:
            new_ofs = 0
        elif new_ofs > fsize:
            new_ofs = fsize

        # do the actual seek
        if new_ofs >= cur_ofs:
            self._skip(new_ofs - cur_ofs)
        else:
            # reopen and seek
            self._open()
            self._skip(new_ofs)
        return self.tell()
138145
private boolean readNextChunkFromFile() throws IOException {
        if (readOffset >= filledUpToWhenStarted || readOffset < 0) {
            return false;
        }

        bufferedReader.clear();
        dataFile.read(readOffset, bufferedReader);
        bufferedReader.position(0);
        if (bufferedReader.limit() > 0) {
            readOffset += bufferedReader.limit();
            while (bufferedReader.remaining() > 0) {
                byte[] dst = new byte[elementSize];
                bufferedReader.get(dst);
                pendingElements.add(dst);
            }
        }
        return true;
    }
206447
function searchFile(name, dirList, callback) {
  if (typeof dirList === 'function') {
    callback = dirList;
    dirList = '';
  }

  if (dirList === undefined) {
    dirList = ''
  }

  if (!Array.isArray(dirList)) {
    dirList = [dirList];
  }

  var success = dirList.some(function(dir) {
    if (!dir) {
      return false;
    }
    try {
      /**
       * Don't try to optimise this to be async since any failures will be
       * passed back to the caller:
       */

      var data = fs.readFileSync(path.join(dir, name), 'utf8');

      callback(null, data);
      return true;
    } catch (e) {
      return false;
    }
  });

  if (!success) {
    return callback('Failed to find file \'' + name + '\' at specified locations:' + dirList.join(','));
  }
}
293199
boolean scanIsEmpty() {
		// This 'slow' implementation is still faster than any external one
		// could be
		// (e.g.: (bitSet.length() == 0 || bitSet.nextSetBit(0) == -1))
		// especially for small BitSets
		// Depends on the ghost bits being clear!
		final int count = numWords;

		for (int i = 0; i < count; i++) {
			if (bits[i] != 0)
				return false;
		}

		return true;
	}
537088
private boolean forwardMatch(String match, boolean ignoreCase, boolean resetOnTrue)
      throws
      IOException
  {
    Mark mark = reader.mark();
    List<Integer> cbuf = Lists.newArrayList();
    StringBuilder builder = new StringBuilder();

    boolean result = true;
    boolean seenChar = false;

    while (true)
    {
      cbuf.add(reader.next());

      char ch = (char) reader.curChar;

      if (reader.curChar == -1)
      {
        result = false;
        break;
      }
      else if (WHITESPACE.matches(ch))
      {
        if (seenChar)
        {
          builder.append(ch);
        }
      }
      else
      {
        if (builder.length() == 0)
        {
          seenChar = true;
        }
        builder.append(ch);
        int index = builder.length() - 1;

        if (!ignoreCase
            && (builder.charAt(index) == match.charAt(index)))
        {
          result = false;
          break;
        }

        if (ignoreCase
            && (Ascii.toLowerCase(builder.charAt(index)) != Ascii
            .toLowerCase(match.charAt(index))))
        {
          result = false;
          break;
        }
      }

      if (builder.length() == match.length())
      {
        if (!match.equalsIgnoreCase(builder.toString()))
        {
          result = false;
        }
        break;
      }
    }

    if (!result || resetOnTrue)
    {
      reader.unread(cbuf, mark);
    }

    return result;
  }
972459
function search_dir(file) {
		var matches = [];
		foreach(_dirs).do(function(dir) {
			if(path.existsSync(dir+"/"+file)) matches.push(dir);
		});
		if(matches.length != 0) return matches.shift();
	}
597792
public int readReverse() throws IOException {
		int b;
		do {
			canRead.block(0);
			synchronized (this) {
				if (error != null) throw error;
				if (io == null) throw new IOException("IO closed");
				// check if we reached the beginning of the file
				if (bufferPosInFile == 0 && posInBuffer == minInBuffer) return -1;
				if (posInBuffer == minInBuffer) {
					// we are reading faster than buffering
					if (currentRead != null)
						canRead.restart();
					else
						readBufferBack();
					b = -1;
				} else {
					b = buffer[--posInBuffer] & 0xFF;
					if (currentRead == null && posInBuffer < buffer.length / 2 && bufferPosInFile > 0)
						readBufferBack();
				}
			}
		} while (b == -1);
		return b;
	}
509425
@Override
  public synchronized void seek(long targetPos) throws IOException {
    if (targetPos > getFileLength()) {
      throw new IOException("Cannot seek after EOF");
    }
    boolean done = false;
    if (pos <= targetPos && targetPos <= blockEnd) {
      //
      // If this seek is to a positive position in the current
      // block, and this piece of data might already be lying in
      // the TCP buffer, then just eat up the intervening data.
      //
      int diff = (int)(targetPos - pos);
      if (diff <= DFSClient.TCP_WINDOW_SIZE) {
        try {
          pos += blockReader.skip(diff);
          if (pos == targetPos) {
            done = true;
          }
        } catch (IOException e) {//make following read to retry
          dfsClient.incReadExpCntToStats();

          DFSClient.LOG.debug("Exception while seek to " + targetPos + " from "
                    + currentBlock +" of " + src + " from " + currentNode +
                    ": " + StringUtils.stringifyException(e));
        }
      } else {
        if (DFSClient.LOG.isDebugEnabled()) {
          DFSClient.LOG.debug("seek() out of TCP buffer " + " block "
              + currentBlock + " current pos: " + pos + " target pos: "
              + targetPos);
        }
      }
    }
    if (!done) {
      pos = targetPos;
      blockEnd = -1;
    }
  }
217131
function doSearch(searchObject, nextPages) {

    savedSearchObject = searchObject;
    if (!files) {
        console.log("no file object found");
        return {};
    }
    results = {};
    numMatches = 0;
    numFiles = 0;
    foundMaximum = false;
    if (!nextPages) {
        exceedsMaximum = false;
        evaluatedMatches = 0;
    }
    var queryObject = parseQueryInfo(searchObject.queryInfo);
    if (searchObject.files) {
        files = searchObject.files;
    }
    if (searchObject.getAllResults) {
        searchObject.maxResultsToReturn = MAX_TOTAL_RESULTS;
    }
    doSearchInFiles(files, queryObject.queryExpr, searchObject.startFileIndex, searchObject.maxResultsToReturn);
    if (crawlComplete && !nextPages) {
        numMatches = getNumMatches(files, queryObject.queryExpr);
    }
    var send_object = {
        "results":  results,
        "foundMaximum":  foundMaximum,
        "exceedsMaximum":  exceedsMaximum
    };

    if (!nextPages) {
        send_object.numMatches = numMatches;
        send_object.numFiles = numFiles;
    }

    if (searchObject.getAllResults) {
        send_object.allResultsAvailable = true;
    }
    return send_object;
}
723165
private boolean searchHarDir(FileStatus stat) 
      throws IOException {
    if (!stat.isDir()) {
      return false;
    }
    String pattern = stat.getPath().toString() + "/*" + RaidNode.HAR_SUFFIX 
        + "*";
    FileStatus[] stats = globStatus(new Path(pattern));
    if (stats != null && stats.length > 0) {
      return true;
    }
      
    stats = fs.listStatus(stat.getPath());
   
    // search deeper.
    for (FileStatus status : stats) {
      if (searchHarDir(status)) {
        return true;
      }
    }
    return false;
  }
5871
def seek_line(self):
        
        pos = end_pos = self.file.tell()

        read_size = self.read_size
        if pos > read_size:
            pos -= read_size
        else:
            pos = 0
            read_size = end_pos

        self.seek(pos)

        bytes_read, read_str = self.read(read_size)

        if bytes_read and read_str[-1] in self.line_terminators:
            # The last charachter is a line terminator, don't count this one
            bytes_read -= 1

            if read_str[-2:] == '\r\n' and '\r\n' in self.line_terminators:
                # found crlf
                bytes_read -= 1

        while bytes_read > 0:          
            # Scan backward, counting the newlines in this bufferfull
            i = bytes_read - 1
            while i >= 0:
                if read_str[i] in self.line_terminators:
                    self.seek(pos + i + 1)
                    return self.file.tell()
                i -= 1

            if pos == 0 or pos - self.read_size < 0:
                # Not enought lines in the buffer, send the whole file
                self.seek(0)
                return None

            pos -= self.read_size
            self.seek(pos)

            bytes_read, read_str = self.read(self.read_size)

        return None
1055583
def get_next_want_file(self, byte_index, block):
        '''
        
        '''
        while block:
            rightmost = get_rightmost_index(byte_index=byte_index,
                                            file_starts=self.file_starts)
            if rightmost in self.want_file_pos:
                return rightmost, byte_index, block
            else:
                    file_start = (self.file_starts
                                  [rightmost])
                    file_length = self.file_list[rightmost]['length']
                    bytes_rem = file_start + file_length - byte_index
                    if len(block) > bytes_rem:
                        block = block[bytes_rem:]
                        byte_index = byte_index + bytes_rem
                    else:
                        block = ''
        else:
            return None
676146
def seekset(func):
    """"""
    @functools.wraps(func)
    def seekcur(self, *args, **kw):
        seek_cur = self._file.tell()
        self._file.seek(self._seekset, os.SEEK_SET)
        return_ = func(self, *args, **kw)
        self._file.seek(seek_cur, os.SEEK_SET)
        return return_
    return seekcur
1001719
private int findSlotBefore(SearchKey searchKey) {
		/*
		 * int slot = 0; while (slot < contents.getNumRecords() &&
		 * getKey(contents, slot).compareTo(searchKey) < 0) slot++; return slot
		 * - 1;
		 */
		// Optimization: Use binary search rather than sequential search
		int startSlot = 0, endSlot = currentPage.getNumRecords() - 1;
		int middleSlot = (startSlot + endSlot) / 2;

		if (endSlot >= 0) {
			while (middleSlot != startSlot) {
				if (getKey(currentPage, middleSlot, keyType.length())
						.compareTo(searchKey) < 0)
					startSlot = middleSlot;
				else
					endSlot = middleSlot;

				middleSlot = (startSlot + endSlot) / 2;
			}

			if (getKey(currentPage, endSlot, keyType.length()).compareTo(searchKey) < 0)
				return endSlot;
			else if (getKey(currentPage, startSlot, keyType.length())
					.compareTo(searchKey) < 0)
				return startSlot;
			else
				return startSlot - 1;
		} else
			return -1;
	}
27801
@Override
  public synchronized void seek(long pos) throws IOException {
    long startTime = System.nanoTime();
    logger.atFine().log("seek: %d", pos);
    try {
      channel.position(pos);
    } catch (IllegalArgumentException e) {
      throw new IOException(e);
    }
    long duration = System.nanoTime() - startTime;
    ghfs.increment(GoogleHadoopFileSystemBase.Counter.SEEK);
    ghfs.increment(GoogleHadoopFileSystemBase.Counter.SEEK_TIME, duration);
  }
407001
function readCodeFromFile()
  {
    $fp = @fopen($this->wordlist_file, 'rb');
    if (!$fp) return false;

    $fsize = filesize($this->wordlist_file);
    if ($fsize < 32) return false; // too small of a list to be effective

    if ($fsize < 128) {
      $max = $fsize; // still pretty small but changes the range of seeking
    } else {
      $max = 128;
    }

    fseek($fp, rand(0, $fsize - $max), SEEK_SET);
    $data = fread($fp, 128); // read a random 128 bytes from file
    fclose($fp);
    $data = preg_replace("/\r?\n/", "\n", $data);

    $start = strpos($data, "\n", rand(0, 100)) + 1; // random start position
    $end   = strpos($data, "\n", $start);           // find end of word

    return strtolower(substr($data, $start, $end - $start)); // return substring in 128 bytes
  }
883624
public void decode(SeekPoint from, SeekPoint to) throws IOException {
        // position random access file
        if (!(inputStream instanceof RandomFileInputStream)) throw new IOException("Not a RandomFileInputStream: " + inputStream.getClass().getName());
        ((RandomFileInputStream)inputStream).seek(from.getStreamOffset());
        bitStream.reset();
        samplesDecoded = from.getSampleNumber();
        
        //state = DECODER_SEARCH_FOR_FRAME_SYNC;
        try {
            while (true) {
                //switch (state) {
                //case DECODER_SEARCH_FOR_METADATA :
                //    readStreamSync();
                //    break;
                //case DECODER_READ_METADATA :
                //    Metadata metadata = readNextMetadata();
                //    if (metadata == null) break;
                //    break;
                //case DECODER_SEARCH_FOR_FRAME_SYNC :
                findFrameSync();
                //    break;
                //case DECODER_READ_FRAME :
                try {
                    readFrame();
                    frameListeners.processFrame(frame);
                    callPCMProcessors(frame);
                } catch (FrameDecodeException e) {
                    badFrames++;
                }
                //frameListeners.processFrame(frame);
                //callPCMProcessors(frame);
                //System.out.println(samplesDecoded +" "+ to.getSampleNumber());
                if (to != null && samplesDecoded >= to.getSampleNumber()) return;
                //    break;
                //case DECODER_END_OF_STREAM :
                //case DECODER_ABORTED :
                //    return;
                //default :
                //    throw new IOException("Unknown state: " + state);
                //}
            }
        } catch (EOFException e) {
            eof = true;
        }
    }