Used by the payment retry service
186689
public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final String userName,
                                                         final CallOrigin callOrigin, final UserType userType, @Nullable final UUID userToken, final Long tenantRecordId) {
        final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, tenantRecordId);
        return createInternalCallContext(tenantRecordId, accountRecordId, userName, callOrigin, userType, userToken, null, null, null, null);
    }
1350848
function retry(count) {
    if (count === void 0) {
        count = -1;
    }
    return function (source) { return source.lift(new RetryOperator(count, source)); };
}
768731
def enter_offline_payment(attrs={})
      Transaction.from_response API.post("#{uri}/transactions", attrs.empty? ? nil : Transaction.to_xml(attrs))
    rescue Recurly::API::UnprocessableEntity => e
      raise Invalid, e.message
    end
380752
def __retry_session(self, retries=10, backoff_factor=0.3,
                        status_forcelist=(500, 502, 504),
                        session=None):
        

        # requests.Session allows finer control, which is needed to use the
        # retrying code
        the_session = session or requests.Session()

        # The Retry object manages the actual retrying
        retry = Retry(total=retries, read=retries, connect=retries,
                      backoff_factor=backoff_factor,
                      status_forcelist=status_forcelist)

        adapter = HTTPAdapter(max_retries=retry)

        the_session.mount('http://', adapter)
        the_session.mount('https://', adapter)

        return the_session
932829
def process(self, request, item):
        """"""
        warn_untested()
        from paypal.pro.helpers import PayPalWPP

        wpp = PayPalWPP(request)
        params = self.cleaned_data
        params['creditcardtype'] = self.fields['acct'].card_type
        params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y")
        params['ipaddress'] = request.META.get("REMOTE_ADDR", "")
        params.update(item)

        try:
            # Create single payment:
            if 'billingperiod' not in params:
                wpp.doDirectPayment(params)
            # Create recurring payment:
            else:
                wpp.createRecurringPaymentsProfile(params, direct=True)
        except PayPalFailure:
            return False
        return True
45996
function(){
					console.log("handleOnlinePrivatePayment queued, will wait for "+key);
					eventBus.once(key, function(bValid){
						if (!bValid)
							return cancelAllKeys();
						assocValidatedByKey[key] = true;
						if (bParsingComplete)
							checkIfAllValidated();
						else
							console.log('parsing incomplete yet');
					});
					cb();
				}
535820
def Retry(target=None, args=[], kwargs={},
          options={"retry": True, "interval": 1}):
    
    retry = options["retry"]
    interval = options["interval"]

    while True:
        try:
            resp = target(*args, **kwargs)
            # status error
            if resp.code == 200:
                return resp

            _logger.debug("Request got response status: %s"
                          % (resp.code,) + " retry: %s" % (retry,))
        except TimeoutError:
            _logger.debug("Request message is timeout")
            _logger.debug(args)
            _logger.debug(kwargs)

        # register unsuccessful goes here
        # infinity retry
        if retry is True:
            sleep(interval)
            continue

        # no retry
        if retry is False:
            return None

        # retrying
        try:
            retry = retry - 1
            if retry <= 0:
                return None
        except TypeError as e:
            raise e
        sleep(interval)
658012
def _handle_retryable_error(self, e, retry_count):
        """"""
        if isinstance(e, error.RateLimitEnforcedError):
            time.sleep(e.retry_after)
        else:
            time.sleep(self.RETRY_DELAY * (self.RETRY_BACKOFF ** retry_count))
543120
def _should_retry(resp):
  """"""
  return (resp.status_code == httplib.REQUEST_TIMEOUT or
          (resp.status_code >= 500 and
           resp.status_code < 600))
891427
def session_retry(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
    
    session = session or Session()
    retries = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    # mount all https requests
    session.mount('https://', adapters.HTTPAdapter(max_retries=retries))
    return session
713798
function Process(PaymentRequest $req)
	{
		$resp = new PaymentResponse();
		$resp->OrderNumber = $req->OrderNumber;

		// before bothering with contacting the processor, check for some basic fields
		if ($req->CCNumber == '')
		{
			$resp->IsSuccess = false;
			$resp->ResponseCode = "0";
			$resp->ResponseMessage = "No Credit Card Number Provided";
			return $resp;
		}

		if ($req->CustomerFirstName == '')
		{
			$resp->IsSuccess = false;
			$resp->ResponseCode = "0";
			$resp->ResponseMessage = "No Cardholder Name Provided";
			return $resp;
		}

		// post to paypal service
		// Set request-specific fields.
		$paymentType = $req->TransactionType == PaymentRequest::$TRANSACTION_TYPE_AUTH_CAPTURE
			? urlencode('Sale')
			: urlencode('Authorization') ;
		$firstName = urlencode($req->CustomerFirstName);
		$lastName = urlencode($req->CustomerLastName);
		$creditCardType = urlencode( trim($req->CCType) );
		$creditCardNumber = urlencode( trim($req->CCNumber) );

		// month needs to be two digits - padded with leading zero if necessary
		$padDateMonth = urlencode( trim(str_pad($req->CCExpMonth, 2, '0', STR_PAD_LEFT)) );

		// year needs to be full 4-digit
		$expDateYear = urlencode( $this->GetFullYear( trim($req->CCExpYear) ) );

		$email = (urlencode($req->CustomerEmail));
		$invoiceNum = (urlencode($req->InvoiceNumber));
		$orderDesc = (urlencode($req->OrderDescription));
		$cvv2Number = urlencode($req->CCSecurityCode);
		$address1 = urlencode($req->CustomerStreetAddress);
		$address2 = urlencode($req->CustomerStreetAddress2);
		$city = urlencode($req->CustomerCity);
		$state = urlencode($req->CustomerState);
		$zip = urlencode($req->CustomerZipCode);
		$amount = urlencode($req->TransactionAmount);
		$currencyID = urlencode($req->TransactionCurrency);		// or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

		// soft descriptor can only be a max of 22 chars with no non-alphanumeric characters
		$softdescriptor = urlencode(substr(preg_replace("/[^a-zA-Z0-9\s]/", "", $req->SoftDescriptor),0,22 ));

		// legit country code list: https://cms.paypal.com/us/cgi-bin/?&cmd=_render-content&content_ID=developer/e_howto_api_nvp_country_codes
		$country = urlencode( strtoupper($req->CustomerCountry) );	// US or other valid country code
		if ($country == "USA") $country = "US";


		// Add request-specific fields to the request string.
		$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
					"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
					"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID".
					"&DESC=$orderDesc&INVNUM=$invoiceNum&EMAIL=$email&SOFTDESCRIPTOR=$softdescriptor";

		// make the post - use a try/catch in case of network errors
		try
		{
			$resp->RawResponse = $this->PPHttpPost('DoDirectPayment', $nvpStr);

			if ("SUCCESS" == strtoupper($resp->RawResponse["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($resp->RawResponse["ACK"]))
			{
				$resp->IsSuccess = true;
				$resp->TransactionId = urldecode( $this->GetArrayVal($resp->RawResponse,"TRANSACTIONID") );
				$resp->ResponseCode = urldecode( "AVSCODE=" . $this->GetArrayVal($resp->RawResponse,"AVSCODE") . ",CVV2MATCH=" . $this->GetArrayVal($resp->RawResponse,"CVV2MATCH"));
				$resp->ResponseMessage = urldecode( "Charge of " . $this->GetArrayVal($resp->RawResponse,"AMT") . " Posted" );
			}
			else
			{
				// for error descriptions, refrer to https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_errorcodes
				$resp->IsSuccess = false;
				$resp->ResponseCode = urldecode( $this->GetArrayVal($resp->RawResponse,"L_ERRORCODE0") );
				$resp->ResponseMessage = $this->GetErrorMessage($resp->RawResponse);

			}

			$resp->ParsedResponse = "";
			$delim = "";
			foreach (array_keys($resp->RawResponse) as $key)
			{
				$resp->ParsedResponse .= $delim . $key . "='" . urldecode( $resp->RawResponse[$key]) . "'";
				$delim = ", ";
			}

		}
		catch (Exception $ex)
		{
			// this means we had a connection error talking to the gateway
			$resp->IsSuccess = false;
			$resp->ResponseCode = $ex->getCode();
			$resp->ResponseMessage = $ex->getMessage();
		}



		return $resp;
	}
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]);
  }
10142
def retryable_transaction(attempts=3, exceptions=(OperationalError,)):
    """"""
    assert len(exceptions) > 0
    assert attempts > 0

    def wrapper(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            for i in xrange(attempts):
                try:
                    return f(*args, **kwargs)
                except exceptions, e:
                    if i == (attempts - 1):
                        raise
                    logging.warning(
                        'Retryable error in transaction on attempt %d. %s: %s',
                        i + 1, e.__class__.__name__, e)
                    db.session.rollback()

        return wrapped

    return wrapper
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);});
      });
    }


  }
1111084
def retry_in(period)
      return unless que_target

      if id = que_target.que_attrs[:id]
        values = [period]

        if e = que_target.que_error
          values << "#{e.class}: #{e.message}".slice(0, 500) << e.backtrace.join("\n").slice(0, 10000)
        else
          values << nil << nil
        end

        Que.execute :set_error, values << id
      end

      que_target.que_resolved = true
    end
283091
private static function retryDecider()
    {
        return function (
            $retries,
            Request $request,
            Response $response = null,
            RequestException $exception = null
        ) {
            // Limit the number of retries to 10
            if ($retries >= 10) {
                return false;
            }

            // Retry connection exceptions
            if ($exception instanceof ConnectException) {
                return true;
            }

            if ($response) {
                // Retry on server errors or overload
                $statusCode = $response->getStatusCode();
                if (429 == $statusCode || 504 == $statusCode || 503 == $statusCode || 502 == $statusCode) {
                    return true;
                }
            }

            return false;
        };
    }
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()