detect_stream_mode - Detect the mode on a given stream

            @param stream <object> - A stream object

            If "mode" is present, that will be used.

        @return <type> - "Bytes" type or "str" type
971677
def detect_stream_mode(stream):
    '''
        
    '''
    # If "Mode" is present, pull from that
    if hasattr(stream, 'mode'):
        if 'b' in stream.mode:
            return bytes
        elif 't' in stream.mode:
            return str

    # Read a zero-length string off the device 
    if hasattr(stream, 'read'):
        zeroStr = stream.read(0)
        if type(zeroStr) is str:
            return str
        return bytes
    elif hasattr(stream, 'recv'):
        zeroStr = stream.recv(0)
        if type(zeroStr) is str:
            return str
        return bytes

    # Cannot figure it out, assume bytes.
    return bytes
1358864
private function setStream($stream, $mode = 'r')
    {
        $error    = null;
        $resource = $stream;

        if (is_string($stream)) {
            set_error_handler(function ($e) use (&$error) {
                $error = $e;
            }, E_WARNING);
            $resource = fopen($stream, $mode);
            restore_error_handler();
        }

        if ($error) {
            throw new InvalidArgumentException('Invalid stream reference provided');
        }

        if (! is_resource($resource) || 'stream' !== get_resource_type($resource)) {
            throw new InvalidArgumentException(
                'Invalid stream provided; must be a string stream identifier or stream resource'
            );
        }

        if ($stream !== $resource) {
            $this->stream = $stream;
        }

        $this->resource = $resource;
    }
427945
public void addStream(Stream stream) {
        indexSets.add(stream.getIndexSet());
        if (streams.add(stream)) {
            sizeCounter.inc(8);
            if (LOG.isTraceEnabled()) {
                LOG.trace("[Message size update][{}] stream added: {}", getId(), sizeCounter.getCount());
            }
        }
    }
1285377
private static String inputStreamToString(InputStream stream)
			throws IOException {
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length;
		String resultString = null;
		while ((length = stream.read(buffer)) != -1) {
			result.write(buffer, 0, length);
		}
		resultString = result.toString("UTF-8");
		return resultString;
	}
1009807
public long getContentLength(MIMETypedStream stream) {
        long length = 0;
        if (stream.header != null) {
            for (int i = 0; i < stream.header.length; i++) {
                if (stream.header[i].name != null
                        && !stream.header[i].name.equalsIgnoreCase("")
                        && stream.header[i].name.equalsIgnoreCase("content-length")) {
                    length = Long.parseLong(stream.header[i].value);
                    break;
                }
            }
        }
        return length;
    }
687458
def is_stream_handler(self, request):
        
        handler = self.get(request)[0]
        if (hasattr(handler, 'view_class') and
                hasattr(handler.view_class, request.method.lower())):
            handler = getattr(handler.view_class, request.method.lower())
        return hasattr(handler, 'is_stream')
308551
function isReadableStream (stream) {
  return stream !== null
    && typeof (stream) === 'object'
    && typeof (stream.pipe) === 'function'
    && typeof (stream._read) === 'function'
    && typeof (stream._readableState) === 'object'
    && stream.readable !== false
}
962106
public int readFrom(InputStream stream) throws IOException {
        int bytesRead = stream.read(buffer);
        if (bytesRead < 0) {
            bytesInBuffer = 0;
        } else {
            bytesInBuffer = bytesRead;
        }
        return bytesRead;
    }
1215734
private String detectBinaryTypes(byte[] bytes) {
		// NB: there are a lot of specific mimetypes we can detect by file
		// magic, but we don't want to make too much effort here.
		// "application/octet-stream" is fine if file looks very much like
		// binary but don't know what exactly. Returned value is not really
		// used beyond being non-null. We're only concerned with file formats
		// frequently sent out with imprecise Content-Type.
		switch (bytes[0]) {
		case (byte)0xFF:
			if (bytes[1] == (byte)0xFE) {
				// UTF-16LE BOM
				return null;
			} else if ((bytes[1] & 0xFE) == (byte)0xFA) {
				// audio/mp3
				return "audio/mp3";
			} else if (bytes[1] == (byte)0xD8) {
				// image/jpeg - commonly <FF><D8><FF><E0> or <FF><D8><FF><E1>
				return "image/jpeg";
			}
			// WordPerfect (<FF>WPC) falls in this category.
			// (WordPerfect also has <D8>WPC
			return BINARY_FILE;
		case (byte)0xFE:
			if (bytes[1] == (byte)0xFF) {
				// UTF-16BE BOM
				return null;
			}
			break;
		case (byte)0xF7:
			if (bytes[1] == 0x02 && bytes[2] == 0x01) {
				// unconfirmed.
				return "application/x-dvi";
			}
			break;
		case (byte)0xEF:
			if (bytes[1] == (byte)0xBB && bytes[2] == (byte)0xBF) {
				// UTF-8 BOM
				return null;
			}
			break;
		case (byte)0xD0:
			if (bytes[1] == (byte)0xCF && bytes[2] == 0x11 && bytes[2] == (byte)0xE1) {
				// MS Word.Document.8
				return BINARY_FILE;
			}
			break;
		case (byte)0xCA:
			if (bytes[1] == (byte)0xFE && bytes[2] == (byte)0xBA && bytes[3] == (byte)0xBE) {
				// application/java (class files)
				return "application/java";
			}
			break;
		case (byte)0x89:
			if (bytes[1] == 'P' && bytes[2] == 'N' && bytes[3] == 'G') {
				return "image/png";
			}
			break;
		case 0x00:
			if (bytes[1] == 0x00) {
				// Windows icon resource falls in this category.
				return BINARY_FILE;
			} else if (bytes[1] == 0x01) {
				// TTF?
				return BINARY_FILE;
			}
			break;
		case 0x01:
			if (bytes[1] == (byte)0xB3 || bytes[1] == (byte)0xBA) {
				return "video/mpeg";
			} else if (bytes[1] == 0x00) {
				// very likely is a binary file
				return BINARY_FILE;
			}
			break;
		case 0x1F:
			if (bytes[1] == (byte)0x8B) {
				return "application/x-gzip";
			} else if (bytes[1] == (byte)0x9D) {
				// followed by 0x90
				return "application/x-compress";
			}
			break;
		case '%':
			if (bytes[1] == 'P' && bytes[2] == 'D' && bytes[3] == 'F' && bytes[4] == '-') {
				return "application/pdf";
			} else if (bytes[1] == '!' && bytes[2] == 'P' && bytes[3] == 'S' && bytes[4] == '-') {
				// application/postscript, Type 1 font.
				return "application/postscript";
			}
			break;
		case 'B':
			if (bytes[1] == 'Z' && bytes[2] == 'h') {
				return "application/x-bzip2";
			}
			break;
		case 'F':
			if (bytes[1] == 'W' && bytes[2] == 'S') {
				// followed by <04> or <05>. Also 'CWS<07>?
				return "application/x-shockwave-flash";
			} else if (bytes[1] == 'L' && bytes[2] == 'V' && bytes[3] == 0x01) {
				return "video/x-flv";
			}
			break;
		case 'G':
			if (bytes[1] == 'I' && bytes[2] == 'F' && bytes[3] == '8') {
				// GIF87a or GIF89a
				return "image/gif";
			}
			break;
		case 'M':
			if (bytes[1] == 'Z') {
				// MS-DOS Executable (MZ <00-FF><00-01>)
				if (bytes[3] == 0x00 || bytes[3] == 0x01) {
					return "application/x-dosexec";
				}
			} else if (bytes[1] == 'S' && bytes[2] == 'C' && bytes[3] == 'F') {
				// MS cab file
				return "application/vnd.ms-cab-compressed";
			} else if (bytes[1] == 'T' && bytes[2] == 'h' && bytes[3] == 'd') {
				// MIDI
				return "audio/midi"; // or "application/x-midi"
			}
			break;
		case 'P':
			if (bytes[1] == 'K' && bytes[2] == 0x03 && bytes[3] == 0x04) {
				return "application/zip";
			} else if (bytes[1] == 'E' && bytes[2] == 0x00 && bytes[3] == 0x00 && bytes[4] == 'M' && bytes[5] == 'S') {
				// Windows PE
				return BINARY_FILE;
			}
			break;
		case 'm':
			if (bytes[1] == 'o' && bytes[2] == 'o' && bytes[3] == 'v') {
				return "video/quicktime";
			} else if (bytes[1] == 'd' && bytes[2] == 'a' && bytes[3] == 't') {
				return "video/quicktime";
			}
			break;
		case '{':
			if (bytes[1] == '\\' && bytes[2] == 'r' && bytes[3] == 't' && bytes[4] == 'f' && bytes[5] == '1') {
				return "application/rtf";
			}
			break;
		}

		if (bytes[2] == '-' && bytes[3] == 'l' && bytes[4] == 'h' && bytes[5] == '5' && bytes[6] == '-') {
			// LZH archive
			return BINARY_FILE;
		}
		// Other formats we may want to add
		// "RIFF" <?><?><?><?> "WAVEfmt " - "audio/wav"
		// <DB><A5><2D><00> - commonly with suffix .doc. files command doesn't know this format.
		// <C5><D0><D3><C6><1E><00><00><00> - some EPS has a binary header starting with this, before "%!PS-"
		return null;
	}
625325
def get_stream(self, stream):
        
        path = '/archive/{}/streams/{}'.format(self._instance, stream)
        response = self._client.get_proto(path=path)
        message = archive_pb2.StreamInfo()
        message.ParseFromString(response.content)
        return Stream(message)
1024582
def parse_stream(self, stream: BytesIO, context=None):
        
        if context is None:
            context = Context()
        if not isinstance(context, Context):
            context = Context(context)
        try:
            return self._parse_stream(stream, context)
        except Error:
            raise
        except Exception as exc:
            raise ParsingError(str(exc))
1094992
function (opt) {
    if (typeof opt !== "object" || opt === null) {
        opt = {};
    }
    if (typeof opt.tag !== "string") {
        opt.tag = null;
    }
    if (typeof opt.encoding !== "string") {
        opt.encoding = "utf8";
    }

    //Extends the readable stream
    stream.Readable.call(this, {encoding: opt.encoding});

    this._tag = (typeof opt.tag === "string") ? opt.tag.trim() : null;
    this._level = labels.length;
    this._disabled = false;

    //Default message format
    this._format = function (tag, label, text) {
        let list = [];
        if (tag) {
            //Add the tag if it is provided
            list.push("[" + tag + "]");
        }
        list.push("[" + timestamp("YYYY-MM-DD hh:mm:ss") + "]");
        list.push("[" + label.toUpperCase() + "]");
        list.push(text.trim());
        return list.join(" ");
    };

    return this;
}
320281
public static <T, U> Stream<U> cast(final Stream<T> stream, final Class<? extends U> type) {
        return stream.map(type::cast);
    }
1111536
public static byte[] streamBytes(InputStream stream) throws IOException {

		ByteArrayOutputStream bytes = new ByteArrayOutputStream();

		copyStream(stream, bytes);

		return bytes.toByteArray();
	}
380137
def _detect_type_load_headers(self, stream,
                                  statusline=None, known_format=None):
        

        if known_format != 'arc':
            # try as warc first
            try:
                rec_headers = self.warc_parser.parse(stream, statusline)
                return 'warc', rec_headers
            except StatusAndHeadersParserException as se:
                if known_format == 'warc':
                    msg = 'Invalid WARC record, first line: '
                    raise ArchiveLoadFailed(msg + str(se.statusline))

                statusline = se.statusline
                pass

        # now try as arc
        try:
            rec_headers = self.arc_parser.parse(stream, statusline)
            return self.arc_parser.get_rec_type(), rec_headers
        except StatusAndHeadersParserException as se:
            if known_format == 'arc':
                msg = 'Invalid ARC record, first line: '
            else:
                msg = 'Unknown archive format, first line: '
            raise ArchiveLoadFailed(msg + str(se.statusline))
109146
function Parser_findASCII85DecodeInlineStreamEnd(stream) {
      var TILDE = 0x7E, GT = 0x3E;
      var startPos = stream.pos, ch, length;
      while ((ch = stream.getByte()) !== -1) {
        if (ch === TILDE && stream.peekByte() === GT) {
          stream.skip();
          break;
        }
      }
      length = stream.pos - startPos;
      if (ch === -1) {
        warn('Inline ASCII85Decode image stream: ' +
             'EOD marker not found, searching for /EI/ instead.');
        stream.skip(-length); // Reset the stream position.
        return this.findDefaultInlineStreamEnd(stream);
      }
      this.inlineStreamSkipEI(stream);
      return length;
    }
869742
def _wrap_stream(stream):
        
        if hasattr(stream, "buffer"):
            return io.TextIOWrapper(stream.buffer, encoding="utf-8")
        elif hasattr(stream, "readable"):
            return io.TextIOWrapper(stream, encoding="utf-8")
        # Python 2.x stdin and stdout are just files
        else:
            return io.open(stream.fileno(), mode=stream.mode, encoding="utf-8")