Performs the LZW compression as described by Matthew Flickinger.

    This isn't fast, but it works.
    http://www.matthewflickinger.com/lab/whatsinagif/lzw_image_data.asp
194374
def _get_image_data(image, colors):
    
    lzw_code_size, coded_bits = _lzw_encode(image, colors)
    coded_bytes = ''.join(
        '{{:0{}b}}'.format(nbits).format(val) for val, nbits in coded_bits)
    coded_bytes = '0' * ((8 - len(coded_bytes)) % 8) + coded_bytes
    coded_data = list(
        reversed([
            int(coded_bytes[8*i:8*(i+1)], 2)
            for i in range(len(coded_bytes) // 8)
        ])
    )
    output = [struct.pack('<B', lzw_code_size)]
    # Must output the data in blocks of length 255
    block_length = min(255, len(coded_data))
    while block_length > 0:
        block = struct.pack(
            '<{}B'.format(block_length + 1),
            block_length,
            *coded_data[:block_length]
        )
        output.append(block)
        coded_data = coded_data[block_length:]
        block_length = min(255, len(coded_data))
    return b''.join(output)
275950
@Override
  public Compressor createCompressor() {
    if (!isNativeCodeLoaded()) {
      throw new RuntimeException("native lz4 library not available");
    }
    int bufferSize = conf.getInt(
        IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_KEY,
        IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_DEFAULT);
    boolean useLz4HC = conf.getBoolean(
        IO_COMPRESSION_CODEC_LZ4_USELZ4HC_KEY,
        IO_COMPRESSION_CODEC_LZ4_USELZ4HC_DEFAULT); 
    return new Lz4Compressor(bufferSize, useLz4HC);
  }
1133590
function zip(data, options) {
		var flags = 0,
			level,
			crc, out = [];

		if (!options) {
			options = {};
		}
		level = options.level || DEFAULT_LEVEL;

		if (typeof data === 'string') {
			data = Array.prototype.map.call(data, function (char) {
				return char.charCodeAt(0);
			});
		}

		// magic number marking this file as GZIP
		putByte(ID1, out);
		putByte(ID2, out);

		putByte(compressionMethods['deflate'], out);

		if (options.name) {
			flags |= possibleFlags['FNAME'];
		}

		putByte(flags, out);
		putLong(options.timestamp || parseInt(Date.now() / 1000, 10), out);

		// put deflate args (extra flags)
		if (level === 1) {
			// fastest algorithm
			putByte(4, out);
		} else if (level === 9) {
			// maximum compression (fastest algorithm)
			putByte(2, out);
		} else {
			putByte(0, out);
		}

		// OS identifier
		putByte(osMap[os], out);

		if (options.name) {
			// ignore the directory part
			putString(options.name.substring(options.name.lastIndexOf('/') + 1), out);

			// terminating null
			putByte(0, out);
		}

		deflate.deflate(data, level).forEach(function (byte) {
			putByte(byte, out);
		});

		putLong(parseInt(crc32(data), 16), out);
		putLong(data.length, out);

		return out;
	}
955491
def to_zpl_line(self, compression=3, **kwargs):
        
        if compression == 3:
            data = base64.b64encode(zlib.compress(self.data.bytes))
            data = ':Z64:%s:%s' % (data.decode('ascii'), self._calc_crc(data))
        elif compression == 1:
            data = base64.b64encode(self.data.bytes)
            data = ':B64:%s:%s' % (data.decode('ascii'), self._calc_crc(data))
        else:
            lines = []
            last_unique_line = None

            for line in self.data.hex_rows:
                if line.endswith('00'):
                    line = line.rstrip('0')
                    if len(line) % 2:
                        line += '0'
                    line += ','
                if line == last_unique_line:
                    line = ':'
                else:
                    last_unique_line = line
                lines.append(line)

            data = '\n'.join(lines)
            to_compress = set(RE_UNCOMPRESSED.findall(data))
            to_compress = sorted(to_compress, reverse=True)
            for uncompressed in to_compress:
                uncompressed = uncompressed[0]
                repeat = len(uncompressed)
                compressed = ''
                while repeat >= 400:
                    compressed += 'z'
                    repeat -= 400
                if repeat >= 20:
                    value = repeat // 20
                    repeat -= value * 20
                    compressed += chr(value + 70).lower()
                if repeat > 0:
                    compressed += chr(repeat + 70)
                data = data.replace(uncompressed, compressed + uncompressed[0])

            data = data.replace('\n', '')

        zpl = '~DGR:%s.GRF,%s,%s,%s' % (
            self.filename,
            self.data.filesize,
            self.data.width // 8,
            data
        )

        return zpl
1217601
def compress(data, compresslevel=9):
    '''
    
    '''
    buf = BytesIO()
    with open_fileobj(buf, 'wb', compresslevel) as ogz:
        if six.PY3 and not isinstance(data, bytes):
            data = data.encode(__salt_system_encoding__)
        ogz.write(data)
    compressed = buf.getvalue()
    return compressed
1317313
function BmpEncoder(imgData){
	this.buffer = imgData.data;
	this.width = imgData.width;
	this.height = imgData.height;
	this.extraBytes = this.width%4;
	this.rgbSize = this.height*(3*this.width+this.extraBytes);
	this.headerInfoSize = 40;

	this.data = [];
	/******************header***********************/
	this.flag = "BM";
	this.reserved = 0;
	this.offset = 54;
	this.fileSize = this.rgbSize+this.offset;
	this.planes = 1;
	this.bitPP = 24;
	this.compress = 0;
	this.hr = 0;
	this.vr = 0;
	this.colors = 0;
	this.importantColors = 0;
}
1271511
public static boolean isCompressed(PushbackInputStream pushbackInputStream) throws IOException {
      if (pushbackInputStream == null) {
         return false;
      }
      byte[] buffer = new byte[2];
      int read = pushbackInputStream.read(buffer);
      boolean isCompressed = false;

      if (read == 2) {
         isCompressed = ((buffer[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (buffer[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8)));
      }

      if (read != -1) {
         pushbackInputStream.unread(buffer, 0, read);
      }

      return isCompressed;
   }
389910
@Override
    synchronized public int encodeIntoCompressedByteBuffer(
            final ByteBuffer targetBuffer,
            final int compressionLevel) {
        int neededCapacity = getNeededByteBufferCapacity(countsArrayLength);
        if (intermediateUncompressedByteBuffer == null || intermediateUncompressedByteBuffer.capacity() < neededCapacity) {
            intermediateUncompressedByteBuffer = ByteBuffer.allocate(neededCapacity).order(BIG_ENDIAN);
        }
        intermediateUncompressedByteBuffer.clear();
        int initialTargetPosition = targetBuffer.position();

        final int uncompressedLength = encodeIntoByteBuffer(intermediateUncompressedByteBuffer);
        targetBuffer.putInt(getCompressedEncodingCookie());

        targetBuffer.putInt(0); // Placeholder for compressed contents length

        Deflater compressor = new Deflater(compressionLevel);
        compressor.setInput(intermediateUncompressedByteBuffer.array(), 0, uncompressedLength);
        compressor.finish();

        byte[] targetArray;

        if (targetBuffer.hasArray()) {
            targetArray = targetBuffer.array();
        } else {
            if (intermediateUncompressedByteArray == null ||
                intermediateUncompressedByteArray.length < targetBuffer.capacity()) {
                intermediateUncompressedByteArray = new byte[targetBuffer.capacity()];
            }
            targetArray = intermediateUncompressedByteArray;
        }

        int compressedTargetOffset = initialTargetPosition + 8;
        int compressedDataLength =
            compressor.deflate(
                targetArray,
                compressedTargetOffset,
                targetArray.length - compressedTargetOffset
            );
        compressor.end();

        if (!targetBuffer.hasArray()) {
            targetBuffer.put(targetArray, compressedTargetOffset, compressedDataLength);
        }

        targetBuffer.putInt(initialTargetPosition + 4, compressedDataLength); // Record the compressed length
        int bytesWritten = compressedDataLength + 8;
        targetBuffer.position(initialTargetPosition + bytesWritten);
        return bytesWritten;
    }
1172952
def __decompressContent(coding, pgctnt):
    '''
    
    '''

    log.trace("Decompressing %s byte content with compression type: %s", len(pgctnt), coding)

    if coding == 'deflate':
        pgctnt = zlib.decompress(pgctnt, -zlib.MAX_WBITS)

    elif coding == 'gzip':
        buf = io.BytesIO(pgctnt)
        f = gzip.GzipFile(fileobj=buf)
        pgctnt = f.read()

    elif coding == "sdch":
        raise ValueError("SDCH compression is not currently supported")
    elif coding == "br":
        raise ValueError("Brotli compression is not currently supported")
    elif coding == "compress":
        raise ValueError("LZW compression is not currently supported")

    elif coding == 'identity':
        pass

    log.trace("Content size after decompression: %s", len(pgctnt))
    return pgctnt
842164
public static function isPhpOutputCompressed()
    {
        // Off = ''; On = '1'; otherwise, it's a buffer size
        $zlibOutputCompression = ini_get('zlib.output_compression');

        // could be ob_gzhandler, ob_deflatehandler, etc
        $outputHandler = ini_get('output_handler');

        // output handlers can be stacked
        $obHandlers = array_filter(ob_list_handlers(), function ($var) {
            return $var !== "default output handler";
        });

        // user defined handler via wrapper
        if (!defined('PIWIK_TEST_MODE')) {
            $autoPrependFile = ini_get('auto_prepend_file');
            $autoAppendFile = ini_get('auto_append_file');
        }

        return !empty($zlibOutputCompression) ||
        !empty($outputHandler) ||
        !empty($obHandlers) ||
        !empty($autoPrependFile) ||
        !empty($autoAppendFile);
    }
237076
protected function _compress() {
        //$before = '(?<=[:(, ])';
        //$after = '(?=[ ,);}])';
        //$units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';

        foreach ($this->_data as $value) {
            $this->_concatContent .= $value;
        }

        if ($this->_type == 'css') {
            $this->_concatContent = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $this->_concatContent);
            $this->_concatContent = str_replace(': ', ':', $this->_concatContent);
            $this->_concatContent = str_replace(["\r\n", "\r", "\n", "\t", '  ', '    ', '    '], '', $this->_concatContent);
        }
    }
583443
def bz2_compress_stream(src, level=9):
    
    compressor = bz2.BZ2Compressor(level)
    for block in src:
        encoded = compressor.compress(block)
        if encoded:
            yield encoded
    yield compressor.flush()
361702
def gzip_encode(data):
    
    if not gzip:
        raise NotImplementedError
    f = StringIO.StringIO()
    gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
    gzf.write(data)
    gzf.close()
    encoded = f.getvalue()
    f.close()
    return encoded
1108939
static byte[] gzip(byte[] data, int level) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
    try (GzipLevelOutputStream out = new GzipLevelOutputStream(baos)) {
      out.setLevel(level);
      out.write(data);
    }
    return baos.toByteArray();
  }
213396
def decompress(compressed_data):
    """"""
    raw_data = []

    index = 0

    while index < len(compressed_data):
        current = compressed_data[index]
        index += 1

        if current == RLE_BYTE:
            directive = compressed_data[index]
            index += 1

            if directive == RLE_BYTE:
                raw_data.append(RLE_BYTE)
            else:
                count = compressed_data[index]
                index += 1

                raw_data.extend([directive] * count)
        elif current == SPECIAL_BYTE:
            directive = compressed_data[index]
            index += 1

            if directive == SPECIAL_BYTE:
                raw_data.append(SPECIAL_BYTE)
            elif directive == DEFAULT_WAVE_BYTE:
                count = compressed_data[index]
                index += 1

                raw_data.extend(DEFAULT_WAVE * count)
            elif directive == DEFAULT_INSTR_BYTE:
                count = compressed_data[index]
                index += 1

                raw_data.extend(DEFAULT_INSTRUMENT_FILEPACK * count)
            elif directive == EOF_BYTE:
                assert False, ("Unexpected EOF command encountered while "
                               "decompressing")
            else:
                assert False, "Countered unexpected sequence 0x%02x 0x%02x" % (
                    current, directive)
        else:
            raw_data.append(current)

    return raw_data
594277
def CompressionFile(dst_fp, algorithm, level=0):
    """"""
    if algorithm == "lzma":
        return lzma.open(dst_fp, "w", preset=level)

    if algorithm == "snappy":
        return SnappyFile(dst_fp, "wb")

    if algorithm:
        raise InvalidConfigurationError("invalid compression algorithm: {!r}".format(algorithm))

    return dst_fp
938043
def write(self, data):
        
        self._check_can_write()
        compressed = self._compressor.compress(data)
        self._fp.write(compressed)
        self._pos += len(data)
        return len(data)