Sends a chunk
@param  object $req Request
@param  string $chunk Data
@return bool
323778
public function sendChunk($req, $chunk)
    {
        $packet = "\x01" // protocol version
            . "\x06" // record type (STDOUT)
            . pack(
                'nn',
                $req->attrs->id,
                mb_orig_strlen($chunk)
            ) // id, content length
            . "\x00" // padding length
            . "\x00";// reserved

        return $this->write($packet) && $this->write($chunk); // content
    }
1066855
public function chunk($count, callable $callback)
    {
        $result = $this->getBuilder()->chunk($count, $callback);

        // Reset query builder
        $this->resetBuilder();

        return $result;
    }
276515
public static function paginate($n, $current = 0, $chunk = null)
    {
        return static::query()->paginate($n, $current, $chunk);
    }
336953
protected function insert_chunk($table, array $chunk, array $columns) {
        $fieldssql = '('.implode(',', array_keys($columns)).')';

        $valuessql = '('.implode(',', array_fill(0, count($columns), '?')).')';
        $valuessql = implode(',', array_fill(0, count($chunk), $valuessql));

        $params = array();
        foreach ($chunk as $dataobject) {
            foreach ($columns as $field => $column) {
                $params[] = $this->normalise_value($column, $dataobject[$field]);
            }
        }

        $sql = "INSERT INTO {$this->prefix}$table $fieldssql VALUES $valuessql";

        list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
        $rawsql = $this->emulate_bound_params($sql, $params);

        $this->query_start($sql, $params, SQL_QUERY_INSERT);
        $result = $this->mysqli->query($rawsql);
        $this->query_end($result);
    }
946066
protected function sendBodyWithoutLength( StreamInterface $body, $chunk_size ) {
		while ( ! $body->eof() ) {
			echo $body->read( $chunk_size );

			if ( connection_status() !== CONNECTION_NORMAL ) {
				break;
			}
		}
	}
1358941
public function send(Request $request)
    {
        $response     = new MapReduceResponse();
        $httpRequest  = $this->createHttpRequest($request);
        $httpResponse = $this->client->send($httpRequest);
        $code         = $httpResponse->getStatusCode();

        if ( ! isset($this->validResponseCodes[$code])) {
            throw RiakTransportException::unexpectedStatusCode($code);
        }

        $multipartIterator  = new MultipartResponseIterator($httpResponse);
        $mapReduceIterator  = new HttpMapReduceResponseIterator($multipartIterator);
        $response->iterator = $mapReduceIterator;

        return $response;
    }
535470
public function readFromString($chunk, $final = true)
    {
        $this->add($chunk);
        $this->readed += mb_orig_strlen($chunk);
        if ($final) {
            $this->onRead();
        }
    }
310063
protected function sendInChunk($content)
    {
        if (strlen($content) <= static::CHUNK_SIZE) {
            $this->swooleResponse->end($content);
            return;
        }

        foreach (str_split($content, static::CHUNK_SIZE) as $chunk) {
            $this->swooleResponse->write($chunk);
        }

        $this->swooleResponse->end();
    }
763875
private function makeRequest($socket, $req, $retry = true) {
    $bytes_written = 0;
    $bytes_total = strlen($req);
    $closed = false;

    // Retries with exponential backoff until success
    $backoff = 100;   // Set initial waiting time to 100ms

    while (true) {
      // Send request to server
      while (!$closed && $bytes_written < $bytes_total) {
        try {
          // Since we're try catch'ing prevent PHP logs.
          $written = @fwrite($socket, substr($req, $bytes_written));
        } catch (Exception $e) {
          $this->handleError($e->getCode(), $e->getMessage());
          $closed = true;
        }
        if (!isset($written) || !$written) {
          $closed = true;
        } else {
          $bytes_written += $written;
        }
      }

      // Get response for request
      $statusCode = 0;
      $errorMessage = "";

      if (!$closed) {
        $res = $this->parseResponse(fread($socket, 2048));
        $statusCode = (int)$res["status"];
        $errorMessage = $res["message"];
      }
      fclose($socket);

      // If status code is 200, return true
      if (200 == $statusCode) {
        return true;
      }

      // If status code is greater than 500 and less than 600, it indicates server error
      // Error code 429 indicates rate limited.
      // Retry uploading in these cases.
      if (($statusCode >= 500 && $statusCode <= 600) || 429 == $statusCode || 0 == $statusCode) {
        if ($backoff >= $this->maximum_backoff_duration) {
          break;
        }

        usleep($backoff * 1000);
      } elseif ($statusCode >= 400) {
        if ($this->debug()) {
          $this->handleError($res["status"], $res["message"]);
        }

        break;
      }

      // Retry uploading...
      $backoff *= 2;
      $socket = $this->createSocket();
    }

    return $success;
  }
857230
function write(id, chunk) {
        // They want to write to our real stream
        var stream = streams[id];
        if (!stream) return;
        stream.write(chunk);
    }
1374295
def send_chunk(type, content = nil)
      chunk = Chunk.new(type, content).to_s
      socket.write chunk
    end
957501
public function send(PockpackQueue $queue = null)
    {
        if( is_null($queue) ) {
            throw new NoPockpackQueueException();
        }

        $params = array(
            'actions'       => json_encode($queue->getActions()),
            'consumer_key'  => $this->consumer_key,
            'access_token'  => $this->access_token
        );

        $request = $this->getClient()->get('/v3/send');
        $request->getQuery()->merge($params);

        $response = $request->send();

        // remove any items from the queue
        $queue->clear();

        return json_decode($response->getBody());
    }
1370305
public function sendDechunkedToBrowser($string)
    {
        // Do some housekeeping. Unless something dreadful had happened, there
        // should not be anything to cleanup.
        $this->cleanupOldChunks();

        // Check for HTML output.
        if ($this->isOutputHtml()) {
            $chunkPos = strpos($string, static::STRING_DELIMITER);

            while ($chunkPos !== false) {
                // We have a chunk, we send the html part.
                echo substr($string, 0, $chunkPos);
                ob_flush();
                flush();
                $chunkPart = substr($string, $chunkPos);

                // We translate the first chunk.
                $result = explode(static::STRING_DELIMITER, $chunkPart, 3);
                $string = str_replace(
                    static::STRING_DELIMITER . $result[1] . static::STRING_DELIMITER,
                    $this->dechunkMe($result[1]),
                    $chunkPart
                );
                $chunkPos = strpos($string, static::STRING_DELIMITER);
            }

            // No more chunk keys, we send what is left.
            echo $string;
            ob_flush();
            flush();
        }
    }
1178466
private function moveToNextState(CellChunk $chunk)
    {
        $this->state = $chunk->getValueSize() > 0
            ? self::$rowStateEnum['CELL_IN_PROGRESS']
            : self::$rowStateEnum['ROW_IN_PROGRESS'];
    }
927928
async def _receive_chunk(self, chunk):
        
        self.__log_debug('< %s', chunk)

        # common
        if isinstance(chunk, DataChunk):
            await self._receive_data_chunk(chunk)
        elif isinstance(chunk, SackChunk):
            await self._receive_sack_chunk(chunk)
        elif isinstance(chunk, ForwardTsnChunk):
            await self._receive_forward_tsn_chunk(chunk)
        elif isinstance(chunk, HeartbeatChunk):
            ack = HeartbeatAckChunk()
            ack.params = chunk.params
            await self._send_chunk(ack)
        elif isinstance(chunk, AbortChunk):
            self.__log_debug('x Association was aborted by remote party')
            self._set_state(self.State.CLOSED)
        elif isinstance(chunk, ShutdownChunk):
            self._t2_cancel()
            self._set_state(self.State.SHUTDOWN_RECEIVED)
            ack = ShutdownAckChunk()
            await self._send_chunk(ack)
            self._t2_start(ack)
            self._set_state(self.State.SHUTDOWN_ACK_SENT)
        elif (isinstance(chunk, ShutdownCompleteChunk) and
              self._association_state == self.State.SHUTDOWN_ACK_SENT):
            self._t2_cancel()
            self._set_state(self.State.CLOSED)
        elif (isinstance(chunk, ReconfigChunk) and
              self._association_state == self.State.ESTABLISHED):
            for param in chunk.params:
                cls = RECONFIG_PARAM_TYPES.get(param[0])
                if cls:
                    await self._receive_reconfig_param(cls.parse(param[1]))

        # server
        elif isinstance(chunk, InitChunk) and self.is_server:
            self._last_received_tsn = tsn_minus_one(chunk.initial_tsn)
            self._reconfig_response_seq = tsn_minus_one(chunk.initial_tsn)
            self._remote_verification_tag = chunk.initiate_tag
            self._ssthresh = chunk.advertised_rwnd
            self._get_extensions(chunk.params)

            self.__log_debug('- Peer supports %d outbound streams, %d max inbound streams',
                             chunk.outbound_streams, chunk.inbound_streams)
            self._inbound_streams_count = min(chunk.outbound_streams, self._inbound_streams_max)
            self._outbound_streams_count = min(self._outbound_streams_count, chunk.inbound_streams)

            ack = InitAckChunk()
            ack.initiate_tag = self._local_verification_tag
            ack.advertised_rwnd = self._advertised_rwnd
            ack.outbound_streams = self._outbound_streams_count
            ack.inbound_streams = self._inbound_streams_max
            ack.initial_tsn = self._local_tsn
            self._set_extensions(ack.params)

            # generate state cookie
            cookie = pack('!L', self._get_timestamp())
            cookie += hmac.new(self._hmac_key, cookie, 'sha1').digest()
            ack.params.append((SCTP_STATE_COOKIE, cookie))
            await self._send_chunk(ack)
        elif isinstance(chunk, CookieEchoChunk) and self.is_server:
            # check state cookie MAC
            cookie = chunk.body
            if (len(cookie) != COOKIE_LENGTH or
               hmac.new(self._hmac_key, cookie[0:4], 'sha1').digest() != cookie[4:]):
                self.__log_debug('x State cookie is invalid')
                return

            # check state cookie lifetime
            now = self._get_timestamp()
            stamp = unpack_from('!L', cookie)[0]
            if stamp < now - COOKIE_LIFETIME or stamp > now:
                self.__log_debug('x State cookie has expired')
                error = ErrorChunk()
                error.params.append((SCTP_CAUSE_STALE_COOKIE, b'\x00' * 8))
                await self._send_chunk(error)
                return

            ack = CookieAckChunk()
            await self._send_chunk(ack)
            self._set_state(self.State.ESTABLISHED)

        # client
        elif isinstance(chunk, InitAckChunk) and self._association_state == self.State.COOKIE_WAIT:
            # cancel T1 timer and process chunk
            self._t1_cancel()
            self._last_received_tsn = tsn_minus_one(chunk.initial_tsn)
            self._reconfig_response_seq = tsn_minus_one(chunk.initial_tsn)
            self._remote_verification_tag = chunk.initiate_tag
            self._ssthresh = chunk.advertised_rwnd
            self._get_extensions(chunk.params)

            self.__log_debug('- Peer supports %d outbound streams, %d max inbound streams',
                             chunk.outbound_streams, chunk.inbound_streams)
            self._inbound_streams_count = min(chunk.outbound_streams, self._inbound_streams_max)
            self._outbound_streams_count = min(self._outbound_streams_count, chunk.inbound_streams)

            echo = CookieEchoChunk()
            for k, v in chunk.params:
                if k == SCTP_STATE_COOKIE:
                    echo.body = v
                    break
            await self._send_chunk(echo)

            # start T1 timer and enter COOKIE-ECHOED state
            self._t1_start(echo)
            self._set_state(self.State.COOKIE_ECHOED)
        elif (isinstance(chunk, CookieAckChunk) and
              self._association_state == self.State.COOKIE_ECHOED):
            # cancel T1 timer and enter ESTABLISHED state
            self._t1_cancel()
            self._set_state(self.State.ESTABLISHED)
        elif (isinstance(chunk, ErrorChunk) and
              self._association_state in [self.State.COOKIE_WAIT, self.State.COOKIE_ECHOED]):
            self._t1_cancel()
            self._set_state(self.State.CLOSED)
            self.__log_debug('x Could not establish association')
            return
323280
public function chunk($str = null)
	{
		if (false === $this->chunked)
		{
			$this->chunked = true;
			$this->header('Transfer-encoding', 'chunked');
			flush();
		}

		if (($body_length = strlen($this->body)) > 0)
		{
			printf("%x\r\n", $body_length);
			$this->sendBody();
			$this->setBody('');
			echo "\r\n";
			flush();
		}

		if (null !== $str)
		{
			printf("%x\r\n", strlen($str));
			echo "$str\r\n";
			flush();
		}

		return $this;
	}
77740
def write_chunk(cls, sock, chunk_type, payload=b''):
    """"""
    chunk = cls.construct_chunk(chunk_type, payload)
    sock.sendall(chunk)