convoluted query function so we can do retries on errors
326204
function() {
            self._client.roomState(roomId).then(function(events) {
                events.forEach(function(ev) {
                    if (self._eventTypes[ev.type]) {
                        if (!r.events[ev.type]) {
                            r.events[ev.type] = {};
                        }
                        r.events[ev.type][ev.state_key] = ev;
                    }
                });
                resolve(r);
            }, function(err) {
                if (err.httpStatus >= 400 && err.httpStatus < 600) { // 4xx, 5xx
                    reject(err); // don't have permission, don't retry.
                }
                // wait a bit then try again
                Promise.delay(3000).then(function() {
                    if (!self._dict[roomId]) {
                        return;
                    }

                    queryRoomState();
                });
            });
        }
645204
function loop(fn, retries) {
    /**
     * Retries fn through the loop after the delay (ms).
     * If all retries have been exhausted the err is returned
     * as the reason for rejection of the promise.
     *
     * @param err
     *
     * @returns {Promise}
     */
    function retry (err) {
      if (retries < maxRetries) {
        return Bluebird
          .delay(ms)
          .then(function() {
            return loop(fn, retries + 1);
          });
      }

      return Bluebird.reject(err);
    }

    // Resolve non-promise and promise returns of fn()
    // Retry on any caught errors.
    return Bluebird.resolve(fn()).catch(retry);
  }
70723
function retrySameUrl(error, options, callback) {

    if (options.currentRetries <= options.retries) {

        log.warn({"url" : options.url, "step" : "queue-requester.recrawlUrl", "message" : "Recrawl -  retries : " + options.currentRetries});
        options.crawlWithDelay = true;

        //TODO : async this code
        // Reinject the same request in the queue
        // 1. Remove it from the crawl history in order to support the option skipDuplicates = true
        store.getStore().removeFromHistory(options.url);
        // 2. Add it again in the queue with the same options
        queue(options, callback);

    }
    else {

      onCrawl(error, options, function(error){
        process.nextTick(function() {callback(error);});
      });
    }


  }
290393
function retry(fn, N, retryTimeout, canContinue) {
    if(typeof N === "function" && retryTimeout === canContinue === undefined) {
        canContinue = N;
        N = retryTimeout = undefined;
    }
    else if(typeof retryTimeout === "function") {
        canContinue = retryTimeout;
        retryTimeout = undefined;
    }
    // Default args
    N = ((N === undefined || N < 0) ? 0 : N - 1);
    retryTimeout = (retryTimeout === undefined ? 0 : retryTimeout);
    canContinue = (canContinue === undefined) ?
        function() { return true; } :
        canContinue;


    return function wrapper() {
        // Actual arguments (passed first time)
        var args = arguments;
        var d = Q.defer();

        // Our failure counter (decounter by decrementing)
        var remainingTries = N;

        // Create function without args
        // that calls fn with args
        // this makes it easier to wrap
        var f = function () {
            return fn.apply(null, args);
        };

        // The function with the try logic
        var _try = function _try() {
            // Call function

            Q.invoke(f)
            .then(function(result) {
                // Success
                d.resolve(result);
            }, function(err) {
                // Failure

                // Decrement
                remainingTries -= 1;

                // No tries left, so reject promise with last error
                if(remainingTries >= 0 && canContinue(err, N - remainingTries)) {
                    // We have some retries left, so retryTimeout
                    if(retryTimeout) {
                        setTimeout(_try, retryTimeout);
                    } else {
                        _try();
                    }
                } else {
                    // Total failure
                    d.reject(err);
                    return;
                }
            }).done();
        };

        // Start trying
        _try();

        // Give promise
        return d.promise;
    };
}
776345
def errorhandle(self, resp):            
        """"""
        if self.format == 'json':
            parsed = xmltodict.parse(resp)
            errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN]
            # Create list of errors if more than one error response is given
            if type(errors) is list and len(errors) > 1:
                messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors])
            else:
                overlimit = any('transaction limit' in msg.lower() for msg in errors.values())
                if overlimit:
                    raise APILimitExceeded("This API key has used up its daily quota of calls.")
                else:    
                    messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()])    
        elif self.format == 'xml':
            import xml.etree.ElementTree as ET
            errors = ET.fromstring(resp).findall(self.ERROR_TOKEN)
            messages = ", ".join(err.find('msg').text for err in errors)
        else:
            raise ValueError("Invalid API response format specified: {}." % self.format)        
        
        raise BustimeError("API returned: {}".format(messages))
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
1057584
function modelIndexErrors(errors, context) {
        if (context && context.modelIndexErrors) {
            return context.modelIndexErrors(errors);
        }
        if (Array.isArray(errors)) {
            var rtn = {};
            _.each(errors, function(data) {
                for (var name in data) {
                    if (data.hasOwnProperty(name)) {
                        rtn[name] = data[name];
                    }
                }
            });
            return rtn;
        } else {
            return errors;
        }
    }
106416
def retry_failed_logs_action(self, request, queryset):
        """"""
        count = 0
        for trigger_log in queryset:
            retried = _retry_failed_log(trigger_log)
            if retried:
                count += 1
        self.message_user(
            request,
            _('{count} failed trigger logs retried.').format(count=count),
        )
794200
def _make_error(index, code, errmsg, operation):
    
    return {
        _UINDEX: index,
        _UCODE: code,
        _UERRMSG: errmsg,
        _UOP: operation
    }
446637
def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
	
	attempts = count() if retries == float('inf') else range(retries)
	for attempt in attempts:
		try:
			return func()
		except trap:
			cleanup()

	return func()
675144
def handle_wikidata_errors(data, query):
    
    entities = data.get('entities')

    if not entities:
        raise LookupError(query)
    elif '-1' in entities:
        raise LookupError(query)
    else:
        item = list(entities.values())[0]
        if 'missing' in item:
            errmsg = "wikidata item %s has been deleted" % item['id']
            raise LookupError(errmsg)
1027907
def _create_retry_request(self):
        """"""
        req_manager = _ReadRowsRequestManager(
            self.request, self.last_scanned_row_key, self._counter
        )
        return req_manager.build_updated_request()
497284
def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0):
    """"""

    def decorator(action):
        """Function decorator that retries `action` in case of a deadlock."""

        @wraps(action)
        def f(*args, **kwargs):
            num_failures = 0
            while True:
                try:
                    return action(*args, **kwargs)
                except (DBAPIError, DBSerializationError) as e:
                    num_failures += 1
                    is_serialization_error = (
                        isinstance(e, DBSerializationError)
                        or get_db_error_code(e.orig) in DEADLOCK_ERROR_CODES
                    )
                    if num_failures > retries or not is_serialization_error:
                        raise
                session.rollback()
                wait_seconds = min(max_wait, min_wait * 2 ** (num_failures - 1))
                time.sleep(wait_seconds)

        return f

    return decorator
1354814
def _txn_retry_loop(conn, callback):
    
    with conn.begin():
        while True:
            try:
                with _NestedTransaction(conn):
                    ret = callback(conn)
                    return ret
            except sqlalchemy.exc.DatabaseError as e:
                if isinstance(e.orig, psycopg2.OperationalError):
                    if e.orig.pgcode == psycopg2.errorcodes.SERIALIZATION_FAILURE:
                        continue
                raise
669464
def retry_until_ok(func, *args, **kwargs):
    
    max_tries = 120
    for i in range(max_tries):
        try:
            return func(*args, **kwargs)
        except RuntimeError:
            # Do not mask RuntimeError.
            raise
        except errors.OperationFailure as exc:
            if exc.code == 13 or (  # MongoDB >= 2.6 sets the error code,
                exc.details
                and "unauthorized" == exc.details.get("errmsg")  # MongoDB 2.4 does not.
            ):
                # Do not mask authorization failures.
                raise
            if i == max_tries - 1:
                LOG.exception(
                    "Call to %s failed too many times in " "retry_until_ok", func
                )
                raise
        except Exception:
            if i == max_tries - 1:
                LOG.exception(
                    "Call to %s failed too many times in " "retry_until_ok", func
                )
                raise
        time.sleep(1)
1295358
def retry(default=None):
    """"""

    def decorator(func):
        """Retry decorator"""

        @functools.wraps(func)
        def _wrapper(*args, **kw):
            for pos in range(1, MAX_RETRIES):
                try:
                    return func(*args, **kw)
                except (RuntimeError, requests.ConnectionError) as error:
                    LOGGER.warning("Failed: %s, %s", type(error), error)

                # Wait a bit before retrying
                for _ in range(pos):
                    _rest()

            LOGGER.warning("Request Aborted")
            return default

        return _wrapper

    return decorator
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);

  });

}