Wrap response input stream if it is compressed, return input its self if not use compress
347900
private InputStream decompressBody() {
        if (!decompress) {
            return body;
        }
        // if has no body, some server still set content-encoding header,
        // GZIPInputStream wrap empty input stream will cause exception. we should check this
        if (method.equals(Methods.HEAD)
                || (statusCode >= 100 && statusCode < 200) || statusCode == NOT_MODIFIED || statusCode == NO_CONTENT) {
            return body;
        }

        String contentEncoding = headers.getHeader(NAME_CONTENT_ENCODING);
        if (contentEncoding == null) {
            return body;
        }

        //we should remove the content-encoding header here?
        switch (contentEncoding) {
            case "gzip":
                try {
                    return new GZIPInputStream(body);
                } catch (IOException e) {
                    Closeables.closeQuietly(body);
                    throw new RequestsException(e);
                }
            case "deflate":
                // Note: deflate implements may or may not wrap in zlib due to rfc confusing.
                // here deal with deflate without zlib header
                return new InflaterInputStream(body, new Inflater(true));
            case "identity":
            case "compress": //historic; deprecated in most applications and replaced by gzip or deflate
            default:
                return body;
        }
    }
311995
function convertToCompressedRequest(req, res, compression) {
        var type = mime.lookup(req.path);
        var charset = mime.charsets.lookup(type);
        var search = req.url.split('?').splice(1).join('?');

        if (search !== "") {
            search = "?" + search;
        }

        req.url = req.path + compression.fileExtension + search;
        res.setHeader("Content-Encoding", compression.encodingName);
        res.setHeader("Content-Type", type + (charset ? "; charset=" + charset : ""));
    }
400675
function decompressResponse (res) {
  var encoding = lowercase(res.headers['content-encoding']);
  var isCompressed = ['gzip', 'compress', 'deflate'].indexOf(encoding) >= 0;

  if (isCompressed) {
    // The response is compressed, so add decompression middleware to the stream
    res.pipe(zlib.createUnzip());

    // Remove the content-encoding header, to prevent double-decoding
    delete res.headers['content-encoding'];
  }
}
983618
function handleUncompressed(res, _write, _end, callback) {
  let buffer = new BufferHelper();
  // Rewrite response method and get the content.
  res.write = data => buffer.concat(data);

  res.end = () => {
    let body;
    try {
      body = JSON.parse(buffer.toBuffer().toString());
    } catch (e) {
      body = buffer.toBuffer().toString();
      console.log('JSON.parse error:', e);
    }

    // Custom modified logic
    if (typeof callback === 'function') {
      body = callback(body);
    }

    let finish = _body => {
      // Converts the JSON to buffer.
      let body = new Buffer(JSON.stringify(_body));

      // Call the response method
      _write.call(res, body);
      _end.call(res);
    };

    if (body && body.then) {
      body.then(finish);
    } else {
      finish(body);
    }
  };
}
365916
def uncompress_body(response)
      case response['content-encoding']
      when 'gzip'
        # ZLib::GzipReader has an associated encoding, by default Encoding.default_external
        return Zlib::GzipReader.new(StringIO.new(response.body), :encoding => Encoding::BINARY).read
      when 'deflate'
        return Zlib::Inflate.new.inflate(response.body)
      when nil, 'identity'
        return response.body
      else
        raise Net::HTTPError.new(_("Unknown content encoding - %{encoding}") % { encoding: response['content-encoding'] }, response)
      end
    end
344586
def stream(input, encoding=None, errors='strict'):
	
	
	input = (i for i in input if i)  # Omits `None` (empty wrappers) and empty chunks.
	
	if encoding:  # Automatically, and iteratively, encode the text if requested.
		input = iterencode(input, encoding, errors=errors)
	
	return input
809681
def parse_content_encoding(self, response_headers, response_data):
        
        if response_headers['content-encoding'] == 'gzip':
            buf = StringIO.StringIO(response_data)
            zipbuf = gzip.GzipFile(fileobj=buf)
            response_data = zipbuf.read()
        elif response_headers['content-encoding'] == 'deflate':
            data = StringIO.StringIO(zlib.decompress(response_data))
            response_data = data.read()
        else:
            raise errors.TestError(
                'Received unknown Content-Encoding',
                {
                    'content-encoding':
                        str(response_headers['content-encoding']),
                    'function': 'http.HttpResponse.parse_content_encoding'
                })
        return response_data
458691
function getCompressedStream(req, res) {
  var encoding = req.headers['accept-encoding'] || '';
  var stream;
  var contentEncodingHeader = res.getHeader('Content-Encoding');
  if ((contentEncodingHeader === 'gzip') || /\bgzip\b/.test(encoding)) {
    if (!contentEncodingHeader) {
      res.setHeader('Content-Encoding', 'gzip');
    }
    stream = zlib.createGzip();
    stream.pipe(res);
  } else if ((contentEncodingHeader === 'deflate') ||
      /\bdeflate\b/.test(encoding)) {
    if (!contentEncodingHeader) {
      res.setHeader('Content-Encoding', 'deflate');
    }
    stream = zlib.createDeflate();
    stream.pipe(res);
  }
  return stream;
}
162269
def dump(self, stream=None):
        
        if stream is None:
            stream = BytesIO()

        if isinstance(stream, bytes):
            stream = BytesIO(stream)

        stream = self.codec.compress(stream)
        self.fs.dump(stream)

        return self
10839
def _handle_response(res, delimiter):
    """"""
    if res.status_code == 200:
        # Python 2 -- csv.reader will need bytes
        if sys.version_info[0] < 3:
            csv_io = BytesIO(res.content)
        # Python 3 -- csv.reader needs str
        else:
            csv_io = StringIO(res.text)
        data_iter = read_unicode_csv_fileobj(csv_io, delimiter=delimiter,
                                             skiprows=1)
    else:
        raise Exception('Could not download Signor data.')
    return data_iter
356419
function streamToText(stream) {
    return new Promise((fulfill, reject) => {
        let chunks = [];
        let length = 0;
        stream.setEncoding('utf8');
        stream.on('data', chunk => {
            length += chunk.length;
            if (length > MAX_TEXT_LENGTH) {
                reject(new Error('Response is too big'));
                return;
            }
            chunks.push(chunk);
        });
        stream.on('end', () => {
            fulfill(chunks.join(''));
        });
        stream.on('error', err => {
            reject(err);
        });
    });
}
407061
public  int[] compress(int[] input) {
        int [] compressed = new int[input.length + input.length / 100 + 1024];
        compressed[0] = input.length;
        IntWrapper outpos = new IntWrapper(1);
        IntWrapper initvalue = new IntWrapper(0);
		try {
			codec.headlessCompress(input, new IntWrapper(0), input.length, compressed, outpos, initvalue);
		} catch (IndexOutOfBoundsException ioebe) {
			throw new UncompressibleInputException(
					"Your input is too poorly compressible with the current codec : " + codec);
		}
        compressed = Arrays.copyOf(compressed,outpos.intValue());
        return compressed;
    }
209320
def deflate(f, *args, **kwargs):
    """"""

    data = f(*args, **kwargs)

    if isinstance(data, Response):
        content = data.data
    else:
        content = data

    deflater = zlib.compressobj()
    deflated_data = deflater.compress(content)
    deflated_data += deflater.flush()

    if isinstance(data, Response):
        data.data = deflated_data
        data.headers['Content-Encoding'] = 'deflate'
        data.headers['Content-Length'] = str(len(data.data))

        return data

    return deflated_data
953068
function processInputStream(msg) {
      var tmp = msg.payload;

      if ('string' === typeof msg.payload) {
        msg.payload = JSON.parse(tmp);
      }
      if (msg.payload.action) {
        if ('start' === msg.payload.action) {
          startPacket = msg.payload;
        }
      } else {
        msg.payload = { 'action' : 'data', 'data' : tmp };
      }

      return Promise.resolve(msg.payload);
    }
590201
def wrap_json_response(func=None, *, encoder=json.JSONEncoder):
    

    if func is None:
        return functools.partial(wrap_json_response, encoder=encoder)

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        if "Content-Type" in response.headers and response.headers['Content-Type'] is not None:
            ctype, pdict = parse_header(response.headers.get('Content-Type', ''))
            if ctype == "application/json" and (isinstance(response.body, dict) or isinstance(response.body, list)):
                response.body = json.dumps(response.body, cls=encoder)
        return response

    return wrapper
585772
def gzipped(fn):
    
    def gzipped_wrapper(*args, **kwargs):
        accepted_encoding = request.get_header("Accept-Encoding")

        if not accepted_encoding or "gzip" not in accepted_encoding:
            return fn(*args, **kwargs)

        response.set_header("Content-Encoding", "gzip")

        return to_gzipped_file(fn(*args, **kwargs))

    return gzipped_wrapper
1250007
public void flushResponse() throws IOException {
        try {
            // Finish GZIP encodig
            if (gzipOut != null) {
                gzipOut.finish();
            }

            flushBuffer();
        }
        finally {
            // Close stream
            if (writer != null) {
                writer.close();
            }
            else {
                if (out != null) {
                    out.close();
                }
            }
        }
    }