Shrink a text file to approximately maxSize bytes
    by removing lines from the middle of the file.
431531
def shrink_text_file(filename, max_size, removal_marker=None):
    
    file_size = os.path.getsize(filename)
    assert file_size > max_size

    # We partition the file into 3 parts:
    # A) start: maxSize/2 bytes we want to keep
    # B) middle: part we want to remove
    # C) end: maxSize/2 bytes we want to keep

    # Trick taken from StackOverflow:
    # https://stackoverflow.com/questions/2329417/fastest-way-to-delete-a-line-from-large-file-in-python
    # We open the file twice at the same time, once for reading (input_file) and once for writing (output_file).
    # We position output_file at the beginning of part B
    # and input_file at the beginning of part C.
    # Then we copy the content of C into B, overwriting what is there.
    # Afterwards we truncate the file after A+C.

    with open(filename, 'r+b') as output_file:
        with open(filename, 'rb') as input_file:
            # Position outputFile between A and B
            output_file.seek(max_size // 2)
            output_file.readline() # jump to end of current line so that we truncate at line boundaries
            if output_file.tell() == file_size:
                # readline jumped to end of file because of a long line
                return

            if removal_marker:
                output_file.write(removal_marker.encode())

            # Position inputFile between B and C
            input_file.seek(-max_size // 2, os.SEEK_END) # jump to beginning of second part we want to keep from end of file
            input_file.readline() # jump to end of current line so that we truncate at line boundaries

            # Copy C over B
            copy_all_lines_from_to(input_file, output_file)

            output_file.truncate()
175619
def copy_byte_range(infile, outfile, start=None, stop=None, bufsize=16*1024):
    '''
    '''
    if start is not None: infile.seek(start)
    while 1:
        to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize)
        buf = infile.read(to_read)
        if not buf:
            break
        outfile.write(buf)
791449
def shorten_text(self, text):
        """"""
        if len(text) > self.width:
            return text[:self.width - 3] + '...'
        return text
867690
def truncate(self, max_length):
        """"""

        if self.length() > max_length:

            # If it's longer than the max_length, scale to the max_length.
            self.scale(max_length / self.length())
1164294
def _shrink(self):
        
        cursize = self._current_size
        while cursize > self._maxsize:
            name, value = self.dynamic_entries.pop()
            cursize -= table_entry_size(name, value)
        self._current_size = cursize
632781
def _delete_compressed(collection_name, spec, opts, flags, ctx):
    """"""
    op_delete, max_bson_size = _delete(collection_name, spec, opts, flags)
    rid, msg = _compress(2006, op_delete, ctx)
    return rid, msg, max_bson_size
431960
public void shrink (int maximumCapacity) {
		if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity);
		if (size > maximumCapacity) maximumCapacity = size;
		if (capacity <= maximumCapacity) return;
		maximumCapacity = nextPowerOfTwo(maximumCapacity);
		resize(maximumCapacity);
	}
796040
public void trimToSize() {
		if (_size < _data.length) {
			_data = _size == 0
				? EMPTY_ARRAY
				: copyOf(_data, _size);
		}
	}
293977
private void shrink() {
        /* If the size of the topmost array is at its minimum, don't do
         * anything.  This doesn't change the asymptotic memory usage because
         * we only do this for small arrays.
         */
        if (mArrays.length == kMinArraySize) return;

        /* Otherwise, we currently have 2^(2n) / 8 = 2^(2n - 3) elements.
         * We're about to shrink into a grid of 2^(2n - 2) elements, and so
         * we'll fill in half of the elements.
         */
        T[][] newArrays = (T[][]) new Object[mArrays.length / 2][];

        /* Copy everything over.  We'll need half as many arrays as before. */
        for (int i = 0; i < newArrays.length / 2; ++i) {
            /* Create the arrays. */
            newArrays[i] = (T[]) new Object[newArrays.length];

            /* Move everything into it.  If this is an odd array, it comes
             * from the upper half of the old array; otherwise it comes from
             * the lower half.
             */
            System.arraycopy(mArrays[i / 2], (i % 2 == 0) ? 0 : newArrays.length,
                    newArrays[i], 0, newArrays.length);

            /* Play nice with the GC.  If this is an odd-numbered array, we
             * just copied over everything we needed and can clear out the
             * old array.
             */
            if (i % 2 == 1)
                mArrays[i / 2] = null;
        }

        /* Copy the arrays over. */
        mArrays = newArrays;

        /* Drop the lg2 of the size. */
        --mLgSize;
    }
684790
private void trimToSize() {
		if (wordsInUse != words.length) {
			words = Arrays.copyOf(words, wordsInUse);
			checkInvariants();
		}
	}
183536
def trunc_str(s: str) -> str:
    """"""
    if len(s) > max_str_size:
        i = max(0, (max_str_size - 3) // 2)
        j = max(0, max_str_size - 3 - i)
        s = s[:i] + "..." + s[-j:]
    return s
680096
def trimsplit(args):
    
    from jcvi.utils.cbook import SummaryStats

    p = OptionParser(trimsplit.__doc__)
    p.add_option("--minlength", default=1000, type="int",
                 help="Min length of contigs to keep")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    fastafile, = args
    minlength = opts.minlength

    fw = must_open(fastafile.rsplit(".", 1)[0] + ".split.fasta", "w")
    ntotal = 0
    removed = []
    Ns = []
    for name, seq in parse_fasta(fastafile):
        stretches = []
        ntotal += len(seq)
        for lower, stretch in groupby(seq, key=lambda x: x.islower()):
            stretch = "".join(stretch)
            if lower or len(stretch) < minlength:
                removed.append(len(stretch))
                continue
            for isN, s in groupby(stretch, key=lambda x: x in "Nn"):
                s = "".join(s)
                if isN or len(s) < minlength:
                    Ns.append(len(s))
                    continue
                stretches.append(s)
        for i, seq in enumerate(stretches):
            id = "{0}_{1}".format(name.split("|")[0], i)
            s = SeqRecord(Seq(seq), id=id, description="")
            SeqIO.write([s], fw, "fasta")
    fw.close()

    # Reporting
    if removed:
        logging.debug("Total bases removed: {0}".\
                        format(percentage(sum(removed), ntotal)))
        print(SummaryStats(removed), file=sys.stderr)
    if Ns:
        logging.debug("Total Ns removed: {0}".\
                        format(percentage(sum(Ns), ntotal)))
        print(SummaryStats(Ns), file=sys.stderr)
951068
def _trim_text(text, max_width):
    
    width = get_cwidth(text)

    # When the text is too wide, trim it.
    if width > max_width:
        # When there are no double width characters, just use slice operation.
        if len(text) == width:
            trimmed_text = (text[:max(1, max_width-3)] + '...')[:max_width]
            return trimmed_text, len(trimmed_text)

        # Otherwise, loop until we have the desired width. (Rather
        # inefficient, but ok for now.)
        else:
            trimmed_text = ''
            for c in text:
                if get_cwidth(trimmed_text + c) <= max_width - 3:
                    trimmed_text += c
            trimmed_text += '...'

            return (trimmed_text, get_cwidth(trimmed_text))
    else:
        return text, width
791641
def fromfile(cls, f):
        """"""
        filter = cls()
        filter._setup(*unpack(cls.FILE_FMT, f.read(calcsize(cls.FILE_FMT))))
        nfilters, = unpack(b'<l', f.read(calcsize(b'<l')))
        if nfilters > 0:
            header_fmt = b'<' + b'Q'*nfilters
            bytes = f.read(calcsize(header_fmt))
            filter_lengths = unpack(header_fmt, bytes)
            for fl in filter_lengths:
                filter.filters.append(BloomFilter.fromfile(f, fl))
        else:
            filter.filters = []

        return filter
747100
public static String truncate(String str, int maxSize) {
        if (str == null) {
            return null;
        }

        if (str.length() <= maxSize) {
            return str;
        }

        return str.substring(0, maxSize);
    }
585067
def text_normalize(text):
    
    # if not isinstance(text, str):
    if isinstance(text, bytes):
        # -- MAYBE: command.ouput => bytes, encoded stream output.
        text = codecs.decode(text)
    lines = [ line.strip()  for line in text.splitlines()  if line.strip() ]
    return "\n".join(lines)
1282140
def trim(lines):
    
    trim_top = None
    trim_bottom = None
    _lines = lines[:]

    for (lineno, line) in enumerate(_lines):
        if hasattr(line, 'is_text_line') and line.is_text_line and not line.text.strip():
            trim_top = lineno
        else:
            break

    for (lineno, line) in enumerate(reversed(_lines)):
        if hasattr(line, 'is_text_line') and line.is_text_line and not line.text.strip():
            trim_bottom = lineno
        else:
            break

    if trim_top is not None:
        _lines = _lines[trim_top + 1:]

    if trim_bottom is not None:
        trim_bottom = len(_lines) - trim_bottom - 1
        _lines = _lines[:trim_bottom]

    return _lines