Returns the ResponseFuture before calling send_request() on it
173953
def _create_response_future(self, query, parameters, trace, custom_payload,
                                timeout, execution_profile=EXEC_PROFILE_DEFAULT,
                                paging_state=None, host=None):
        

        prepared_statement = None

        if isinstance(query, six.string_types):
            query = SimpleStatement(query)
        elif isinstance(query, PreparedStatement):
            query = query.bind(parameters)

        if self.cluster._config_mode == _ConfigMode.LEGACY:
            if execution_profile is not EXEC_PROFILE_DEFAULT:
                raise ValueError("Cannot specify execution_profile while using legacy parameters.")

            if timeout is _NOT_SET:
                timeout = self.default_timeout

            cl = query.consistency_level if query.consistency_level is not None else self.default_consistency_level
            serial_cl = query.serial_consistency_level if query.serial_consistency_level is not None else self.default_serial_consistency_level

            retry_policy = query.retry_policy or self.cluster.default_retry_policy
            row_factory = self.row_factory
            load_balancing_policy = self.cluster.load_balancing_policy
            spec_exec_policy = None
        else:
            execution_profile = self._maybe_get_execution_profile(execution_profile)

            if timeout is _NOT_SET:
                timeout = execution_profile.request_timeout

            cl = query.consistency_level if query.consistency_level is not None else execution_profile.consistency_level
            serial_cl = query.serial_consistency_level if query.serial_consistency_level is not None else execution_profile.serial_consistency_level

            retry_policy = query.retry_policy or execution_profile.retry_policy
            row_factory = execution_profile.row_factory
            load_balancing_policy = execution_profile.load_balancing_policy
            spec_exec_policy = execution_profile.speculative_execution_policy

        fetch_size = query.fetch_size
        if fetch_size is FETCH_SIZE_UNSET and self._protocol_version >= 2:
            fetch_size = self.default_fetch_size
        elif self._protocol_version == 1:
            fetch_size = None

        start_time = time.time()
        if self._protocol_version >= 3 and self.use_client_timestamp:
            timestamp = self.cluster.timestamp_generator()
        else:
            timestamp = None

        if isinstance(query, SimpleStatement):
            query_string = query.query_string
            statement_keyspace = query.keyspace if ProtocolVersion.uses_keyspace_flag(self._protocol_version) else None
            if parameters:
                query_string = bind_params(query_string, parameters, self.encoder)
            message = QueryMessage(
                query_string, cl, serial_cl,
                fetch_size, timestamp=timestamp,
                keyspace=statement_keyspace)
        elif isinstance(query, BoundStatement):
            prepared_statement = query.prepared_statement
            message = ExecuteMessage(
                prepared_statement.query_id, query.values, cl,
                serial_cl, fetch_size,
                timestamp=timestamp, skip_meta=bool(prepared_statement.result_metadata),
                result_metadata_id=prepared_statement.result_metadata_id)
        elif isinstance(query, BatchStatement):
            if self._protocol_version < 2:
                raise UnsupportedOperation(
                    "BatchStatement execution is only supported with protocol version "
                    "2 or higher (supported in Cassandra 2.0 and higher).  Consider "
                    "setting Cluster.protocol_version to 2 to support this operation.")
            statement_keyspace = query.keyspace if ProtocolVersion.uses_keyspace_flag(self._protocol_version) else None
            message = BatchMessage(
                query.batch_type, query._statements_and_parameters, cl,
                serial_cl, timestamp, statement_keyspace)

        message.tracing = trace

        message.update_custom_payload(query.custom_payload)
        message.update_custom_payload(custom_payload)
        message.allow_beta_protocol_version = self.cluster.allow_beta_protocol_version
        message.paging_state = paging_state

        spec_exec_plan = spec_exec_policy.new_plan(query.keyspace or self.keyspace, query) if query.is_idempotent and spec_exec_policy else None
        return ResponseFuture(
            self, message, query, timeout, metrics=self._metrics,
            prepared_statement=prepared_statement, retry_policy=retry_policy, row_factory=row_factory,
            load_balancer=load_balancing_policy, start_time=start_time, speculative_execution_plan=spec_exec_plan,
            host=host)
1057509
protected <T extends RaftRequest, U extends RaftResponse> void sendRequest(T request, BiFunction<MemberId, T, CompletableFuture<U>> sender, CompletableFuture<U> future) {
    sendRequest(request, sender, 0, future);
  }
11150
def _make_request_to_server(self, query_function, raise_for_status=True,
                                time_limit_seconds=2, retry_delay_seconds=0.2):
        
        start_time = datetime.datetime.now()
        while datetime.datetime.now() - start_time < datetime.timedelta(
                0, time_limit_seconds):
            error = None
            response = None
            try:
                response = query_function()
            except requests.exceptions.ConnectionError as e:
                error = ServerConnectionError(
                    "No response from server.\n%s" % e)
            except:
                if response:
                    logger.info(response.text)
                raise
            if response is not None and raise_for_status:
                # raises requests.exceptions.HTTPError
                self._raise_for_status(response)
            if error:
                time.sleep(retry_delay_seconds)
                continue
            else:
                return response
        raise error
185244
def send(self, request, pk=None):
        
        schedule = self.get_object()
        queue_subscription_send.delay(str(schedule.id))

        return Response({}, status=status.HTTP_202_ACCEPTED)
899833
def post_async(self, path, params=None):
        
        request = Post(self._get_next_id(), path, params)
        request.set_callback(self._q.put)
        future = self._dispatch_request(request)
        return future
1119372
@Override
    public Future<M> requestData() {
        logger.debug(this + " requestData...");
        try {
            validateInitialization();
            synchronized (syncMonitor) {

                // Check if sync is in process.
                if (syncFuture != null && !syncFuture.isDone()) {

                    // Recover sync task if it was canceled for instance during remote reinitialization.
                    if (syncTask == null || syncTask.isDone()) {
                        syncTask = sync();
                    }
                    return syncFuture;
                } else {
                    // cleanup old sync task
                    if (syncTask != null && !syncTask.isDone()) {
                        syncTask.cancel(true);
                    }
                }

                // Create new sync process
                syncFuture = new CompletableFutureLite();
                syncTask = sync();
                return syncFuture;
            }
        } catch (CouldNotPerformException ex) {
            return FutureProcessor.canceledFuture(new CouldNotPerformException("Could not request data!", ex));
        }
    }
1079867
def sendFuture(self, future):
        """"""
        try:
            if shared.getConst(hash(future.callable),
                               timeout=0):
                # Enforce name reference passing if already shared
                future.callable = SharedElementEncapsulation(hash(future.callable))
            self.socket.send_multipart([b"TASK",
                                        pickle.dumps(future,
                                                     pickle.HIGHEST_PROTOCOL)])
        except pickle.PicklingError as e:
            # If element not picklable, pickle its name
            # TODO: use its fully qualified name
            scoop.logger.warn("Pickling Error: {0}".format(e))
            previousCallable = future.callable
            future.callable = hash(future.callable)
            self.socket.send_multipart([b"TASK",
                                        pickle.dumps(future,
                                                     pickle.HIGHEST_PROTOCOL)])
            future.callable = previousCallable
224942
@Override
    public Future<Long> ping(final Long timestamp) {
        try {
            validateMiddleware();
        } catch (InvalidStateException e) {
            try {
                waitForMiddleware(1, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
                FutureProcessor.canceledFuture(ex);
            } catch (CouldNotPerformException ex) {
                // controller not ready to respond.
                FutureProcessor.canceledFuture(ex);
            }
        }
        return FutureProcessor.completedFuture(timestamp);
    }
441382
protected <T extends Request, U extends Response> CompletableFuture<U> forward(T request) {
    CompletableFuture<U> future = new CompletableFuture<>();
    context.getConnections().getConnection(context.getLeader().serverAddress()).whenComplete((connection, connectError) -> {
      if (connectError == null) {
        connection.<T, U>sendAndReceive(request).whenComplete((response, responseError) -> {
          if (responseError == null) {
            future.complete(response);
          } else {
            future.completeExceptionally(responseError);
          }
        });
      } else {
        future.completeExceptionally(connectError);
      }
    });
    return future;
  }
1046243
async def send(self, sender, **kwargs):
        '''  '''
        if not self.receivers:
            return []
        responses = []
        futures = []
        for receiver in self._get_receivers(sender):
            method = receiver()
            if callable(method):
                futures.append(method(sender=sender, **kwargs))
        if len(futures) > 0:
            responses = await asyncio.gather(*futures)
        return responses
1070496
def give_response(response, deferred)
      @delayer.new do
        next if deferred.spoiled?
        deferred.exit_await
        fiber.resume(response).accept_request(worker: self,
                                              deferred: deferred)
      end
      nil
    end
1114253
def send_pending_requests(self):
        
        assert_open(self)

        unsent_commands = self.commands
        if unsent_commands:
            self.commands = []

            if self.auto_batch:
                unsent_commands = auto_batch_commands(unsent_commands)

            buf = []
            for command_name, args, options, promise in unsent_commands:
                buf.append((command_name,) + tuple(args))
                self.pending_responses.append((command_name, options, promise))

            cmds = self.connection.pack_commands(buf)
            self._send_buf.extend(cmds)

        if not self._send_buf:
            return True

        self.send_buffer()
        return not self._send_buf
164876
function requestAnim(func) {
    var result = q.delay(currentDelay)
      .thenResolve(func)
      .then(start);
    currentDelay += delay;
    return result;
  }
729216
def sendFinalResponse(self):
        
        self.requestProtocol.requestResponse["code"] = (
            self.responseCode
        )
        self.requestProtocol.requestResponse["content"] = (
            self.responseContent
        )
        self.requestProtocol.requestResponse["errors"] = (
            self.responseErrors
        )
        self.requestProtocol.sendFinalRequestResponse()
918673
def _send_and_wait(self, **kwargs):
        
        frame_id = self.next_frame_id
        kwargs.update(dict(frame_id=frame_id))
        self._send(**kwargs)
        timeout = datetime.now() + const.RX_TIMEOUT
        while datetime.now() < timeout:
            try:
                frame = self._rx_frames.pop(frame_id)
                raise_if_error(frame)
                return frame
            except KeyError:
                sleep(0.1)
                continue
        _LOGGER.exception(
            "Did not receive response within configured timeout period.")
        raise exceptions.ZigBeeResponseTimeout()
671033
def request_update(self):
        
        with self._lock:
            self._need_update = True
            if not self._future or self._future.is_done:
              self._future = Future()
            return self._future
923266
async def process_response(
        self,
        response: Response,
        request_context: Optional[RequestContext]=None,
    ) -> Response:
        
        request_ = (request_context or _request_ctx_stack.top).request
        functions = (request_context or _request_ctx_stack.top)._after_request_functions
        blueprint = request_.blueprint
        if blueprint is not None:
            functions = chain(functions, self.after_request_funcs[blueprint])
        functions = chain(functions, self.after_request_funcs[None])

        for function in functions:
            response = await function(response)

        session_ = (request_context or _request_ctx_stack.top).session
        if not self.session_interface.is_null_session(session_):
            await self.save_session(session_, response)
        return response