helper function to cancel retry future. not in iOS code.
976807
private void cancelRetryFuture() {
        if (retryFuture != null && !retryFuture.isDone()) {
            retryFuture.cancel(true);
        }
        retryFuture = null;
    }
405443
def call_with_retry(func: Callable, exceptions, max_retries: int,
                    logger: Logger, *args, **kwargs):
    """"""
    attempt = 0
    while True:
        try:
            return func(*args, **kwargs)
        except exceptions as e:
            attempt += 1
            if attempt >= max_retries:
                raise

            delay = exponential_backoff(attempt, cap=60)
            logger.warning('%s: retrying in %s', e, delay)
            time.sleep(delay.total_seconds())
76253
function retry(promise, fn, opts) {

  // Piggy back off of previous promise.
  return promise.then(function() {

    // Setup default options.
    opts = opts || {};
    opts.max = opts.max || 5;
    opts.backoff = opts.backoff || 500;

    // Recursive function.
    var rec = function(counter) {

      // Call function fn within the context of a Promise.
      return Promise.try(function() {
        return fn(counter);
      })
      // Handle errors.
      .catch(function(err) {

        // If we haven't reached max retries, delay for a short while and
        // then retry.
        if (counter < opts.max) {

          return Promise.delay(opts.backoff * counter)
          .then(function() {
            return rec(counter + 1);
          });

        } else {

          // No retries left so wrap and throw the error.
          throw new VError(
            err,
            'Failed after %s retries. %s',
            opts.max,
            JSON.stringify(opts)
          );

        }
      });

    };

    // Init recursive function.
    return rec(1);

  });

}
931084
def after_func_accept_retry_state(fn):
    """"""
    if not six.callable(fn):
        return fn

    if func_takes_retry_state(fn):
        return fn

    @_utils.wraps(fn)
    def wrapped_after_sleep_func(retry_state):
        # func, trial_number, trial_time_taken
        warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
        return fn(
            retry_state.fn,
            retry_state.attempt_number,
            retry_state.seconds_since_start)
    return wrapped_after_sleep_func
1332706
async def cancel(self):
        
        if self._cancel_done:
            raise ProtocolError('Stream was already cancelled')

        with self._wrapper:
            await self._stream.reset()  # TODO: specify error code
            self._cancel_done = True
40930
function retry(response) {
        var retryAfter = response.headers['retry-after'];
        if (typeof retryFn === 'function' && retryAfter) {
            retryAfter = parseInt(retryAfter, 10);
            setTimeout(retryFn, retryAfter * 1000);
            return true;
        }
        return false;
    }
767509
def cancel(self):
        """"""
        if self in scoop._control.execQueue.movable:
            self.exceptionValue = CancelledError()
            scoop._control.futureDict[self.id]._delete()
            scoop._control.execQueue.remove(self)
            return True
        return False
123236
function retry(err) {
    if (currentAttempt >= retryCount) {
      return callback(err, null, currentAttempt);
    }

    currentAttempt += 1;

    // Since the currentAttempt starts at 1 and it was just incremented
    // currentAttempt - 2 will be the actual timeout index.
    return setTimeout(attempt, timeouts[currentAttempt - 2]);
  }
801504
def retry_dunder_call_accept_old_params(fn):
    """"""
    @_utils.wraps(fn)
    def new_fn(self, attempt=_unset, retry_state=None):
        if retry_state is None:
            from tenacity import RetryCallState
            if attempt is _unset:
                raise _make_unset_exception('retry', attempt=attempt)
            retry_state_passed_as_non_kwarg = (
                attempt is not _unset and
                isinstance(attempt, RetryCallState))
            if retry_state_passed_as_non_kwarg:
                retry_state = attempt
            else:
                warn_about_dunder_non_retry_state_deprecation(fn, stacklevel=2)
                retry_state = RetryCallState(None, None, (), {})
                retry_state.outcome = attempt
        return fn(self, retry_state=retry_state)
    return new_fn
326712
def _cancel_callback(self, request_id):
        """"""
        def callback(future):
            if future.cancelled():
                self.notify(CANCEL_METHOD, {'id': request_id})
                future.set_exception(JsonRpcRequestCancelled())
        return callback
427512
public void cancel() {
        final OnCancelListener listener;
        synchronized (this) {
            if (mIsCanceled) {
                return;
            }
            mIsCanceled = true;
            mCancelInProgress = true;
            listener = mOnCancelListener;
        }

        try {
            if (listener != null) {
                listener.onCancel();
            }
        } finally {
            synchronized (this) {
                mCancelInProgress = false;
                notifyAll();
            }
        }
    }
1024846
def _retry(self):
        """"""
        notifications_to_delete = []
        for notification_id in self.notifications:
            if datetime.datetime.utcnow() > self.notifications[notification_id]['ts'] + self._wait_period:
                self._notify_receiver(
                    self.notifications[notification_id]['receiver'],
                    self.notifications[notification_id]['params'],
                    self.notifications[notification_id]['doc'])
                if self.notifications[notification_id]['attempts'] >= self._max_attempts - 1:
                    notifications_to_delete.append(notification_id)
                else:
                    self.notifications[notification_id]['ts'] = datetime.datetime.utcnow()
                    self.notifications[notification_id]['attempts'] += 1
        for notification_id in notifications_to_delete:
            del self.notifications[notification_id]
543120
def _should_retry(resp):
  """"""
  return (resp.status_code == httplib.REQUEST_TIMEOUT or
          (resp.status_code >= 500 and
           resp.status_code < 600))
655626
def retry_after(cls, response, default=5, _now=time.time):
        
        val = response.headers.getRawHeaders(b'retry-after', [default])[0]
        try:
            return int(val)
        except ValueError:
            return http.stringToDatetime(val) - _now()
824219
def cancel(self):
        '''
        
        '''
        if (not self.cancelled) and (self._fn is not None):
            self._cancelled = True
            self._drop_fn()
1195504
void cancel(AsyncChannelFuture future, Exception reason) throws ClosedChannelException, IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "cancel");
        }
        if (!isOpen()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Cancel request on closed connection");
            }
            future.setCancelInProgress(0);
            throw new ClosedChannelException();
        }

        // Cannot cancel a completed call.
        if (future.isCompleted()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Cancel request on completed future");
            }
            future.setCancelInProgress(0);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "cancel");
            }
            return;
        }

        long callid;
        if (((AsyncFuture) future).isRead()) {
            callid = this.readIOCB.getCallIdentifier();
        } else {
            callid = this.writeIOCB.getCallIdentifier();
        }

        int rc = provider.cancel2(this.channelIdentifier, callid);
        if (rc == 0) {
            // Mark the future completed with an Exception
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Cancel Successful, resetting CancelInProgress state to 0");
            }
            future.setCancelInProgress(0);
            future.completed(reason);
        } else {
            // could not cancel
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Cancel could not be completed");
            }
            future.setCancelInProgress(0);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "cancel");
        }
    }
1069749
def auto_retry(fun):
    """"""

    @functools.wraps(fun)
    def decorated(instance, *args, **kwargs):
        """Wrapper around a decorated function."""
        cfg = instance._retry_config
        remaining_tries = cfg.retry_attempts
        current_wait = cfg.retry_wait
        retry_backoff = cfg.retry_backoff
        last_error = None

        while remaining_tries >= 0:
            try:
                return fun(instance, *args, **kwargs)
            except socket.error as e:
                last_error = e
                instance._retry_logger.warning('Connection failed: %s', e)

            remaining_tries -= 1
            if remaining_tries == 0:
                # Last attempt
                break

            # Wait a bit
            time.sleep(current_wait)
            current_wait *= retry_backoff

        # All attempts failed, let's raise the last error.
        raise last_error

    return decorated