Buffer stdin and flush, and avoid incomplete files.
320469
def main(args=None):
    """"""
    parser = argparse.ArgumentParser(description=main.__doc__)
    parser.add_argument(
        '--binary',
        dest='mode',
        action='store_const',
        const="wb",
        default="w",
        help='write in binary mode')
    parser.add_argument(
        'output', metavar='FILE', type=unicode, help='Output file')

    logging.basicConfig(
        level=logging.DEBUG,
        stream=sys.stderr,
        format='[%(levelname)s elapsed=%(relativeCreated)dms] %(message)s')

    args = parser.parse_args(args or sys.argv[1:])

    with open(args.output, args.mode) as fd:
        for line in sys.stdin:
            fd.write(line)
351103
def __flush_data(self, data):
        
        if not data:
            return defer.succeed(None)

        assert (len(data) <= self.chunk_size)
        chunk = {"files_id": self._file["_id"],
                 "n": self._chunk_number,
                 "data": Binary(data)}

        def ok(_):
            self._chunk_number += 1
            self._position += len(data)

        # Continue writing after the insert completes (non-blocking)
        return self._chunks.insert(chunk).addCallback(ok)
914975
private void flushBuffer() throws IOException
    {
        while (_flush.hasRemaining())
        {
            int len=_channel.write(_flush);
            if (len<0)
                throw new IOException("EOF");
            if (len==0)
            {
                // write channel full.  Try letting other threads have a go.
                Thread.yield();
                len=_channel.write(_flush);
                if (len<0)
                    throw new IOException("EOF");
                if (len==0)
                {
                    // still full.  need to  block until it is writable.
                    if (_selector==null)
                     {
                            _selector=Selector.open();
                            _channel.register(_selector,SelectionKey.OP_WRITE);
                     }

                     _selector.select();
                }
            }
        }
    }
115722
public function flushBuffer() {
        $content = $this->format($this->buffer->flush());

        if ( ! $this->is(OutputVerbosity::SILENT)) {
            fwrite($this->getOutputStream(), $content);
        }
    }
284772
protected synchronized void flushBuffer(boolean chunkComplete,
      boolean keepPartialData) throws IOException {
    if (count != 0) {
      int chunkLen = count;
      count = 0;
      writeChecksumChunk(buf, 0, chunkLen, keepPartialData && !chunkComplete);
      if (!chunkComplete) {
        if (!keepPartialData) {
          bytesSentInChunk += chunkLen;
        } else {
          count = chunkLen;
        }
      } else {
        bytesSentInChunk = 0;
      }
    }
  }
543042
def flush(self):
        """"""
        if self.__logFileStream is not None:
            try:
                self.__logFileStream.flush()
            except:
                pass
            try:
                os.fsync(self.__logFileStream.fileno())
            except:
                pass
        if self.__stdout is not None:
            try:
                self.__stdout.flush()
            except:
                pass
            try:
                os.fsync(self.__stdout.fileno())
            except:
                pass
255963
def flushInput(self):
                ''''''
                self.buf = ''
                saved_timeout = self.timeout
                self.timeout = 0.5
                self._recv()
                self.timeout = saved_timeout
                self.buf = ''
                self.debug("flushInput")
1337794
def _flushBuffer(self, request):
        ''''''
        assert request is self.requestSession.request
        self.requestSession.writeData(self.buffer)
        self.buffer = []
758481
private void flush(boolean isEnd)
  {
    if (_startOffset == _offset && _bufferSize == 0) {
      if (! isCommitted() || isEnd) {
        flush(null, isEnd);
        _startOffset = bufferStart();
        _offset = _startOffset;
      }
      return;
    }

    int sublen = _offset - _startOffset;
    _tBuf.length(_offset);
    _contentLength += _offset - _startOffset;
    _bufferSize = 0;
    
    if (_startOffset > 0) {
      fillChunkHeader(_tBuf, sublen);
    }
    
    flush(_tBuf, isEnd);

    if (! isEnd) {
      _tBuf = TempBuffer.create();
    
      _startOffset = bufferStart();
      _offset = _startOffset;

      _tBuf.length(_offset);
      
      _buffer = _tBuf.buffer();
    }
    else {
      _tBuf = null;
    }
  }
975009
def pipe_data_received(self, fd, data):
        """"""
        if fd == 2:  # stderr fd number
            self._on_stderr(data)
        elif self._on_data:
            self._on_data(data)
        else:
            self._queued_data.append(data)
1223009
def _flush_raw_or_buffered(self):
        
        # Flush only if bytes written
        # This avoid no required process/thread
        # creation and network call.
        # This step is performed by raw stream.
        if self._buffer_seek and self._seek:
            self._seek += 1
            with handle_os_exceptions():
                self._flush()

        # If data lower than buffer size
        # flush data with raw stream to reduce IO calls
        elif self._buffer_seek:
            self._raw._write_buffer = self._get_buffer()
            self._raw._seek = self._buffer_seek
            self._raw.flush()
98033
private void flushBuffer(ByteBuffer buffer, WritableByteChannel output) throws IOException {
    buffer.flip();
    output.write(buffer);
    buffer.flip();
    buffer.limit(buffer.capacity());
  }
539299
def _flush(self):
        
        # Initialize multipart upload
        if self._upload_id is None:
            with _handle_oss_error():
                self._upload_id = self._bucket.init_multipart_upload(
                    self._key).upload_id

        # Upload part with workers
        response = self._workers.submit(
            self._bucket.upload_part, key=self._key, upload_id=self._upload_id,
            part_number=self._seek, data=self._get_buffer().tobytes())

        # Save part information
        self._write_futures.append(
            dict(response=response, part_number=self._seek))
1012307
def flush(self):
        """"""
        if self.shutdown:
            return
        self.flush_buffers(force=True)
        self.queue.put(FLUSH_MARKER)
        self.queue.join()
1203632
private void flushBuffer() {
		// Do the actual logging:
		removes.ensureCapacity(buffer.size());
		for(Iterator<LoggingEvent> i = buffer.iterator(); i.hasNext();) {
			try {
				LoggingEvent event = (LoggingEvent)i.next();
				doLog(event);
				removes.add(event);
			} catch(Exception e) {
				errorHandler.error("Failed to flush log", e, ErrorCode.FLUSH_FAILURE);
			}
		}

		// Remove from the buffer any events that were reported:
		buffer.removeAll(removes);

		// Clear the buffer of reported events:
		removes.clear();
	}
843867
public void flush() throws IOException {
        checkForClosed();
        writeBufferToFile();
        if (_currentOffset > _offset) { // something to commit
            _nfsFile.commit(_offset, (int) (_currentOffset - _offset));
            _offset = _currentOffset;
        }
        super.flush();
    }
954274
private static void __flush(InputStream is, OutputStream os, int bufferSize) throws IOException {
        byte[] buffer = new byte[bufferSize];

        for (int length = 0; (length = is.read(buffer)) > 0;) {
            os.write(buffer, 0, length);
        }
    }