Creates a rate.

@param string            $url
@param ExchangeRateQuery $exchangeQuery

@return ExchangeRate

@throws Exception
430121
private function doCreateRate(string $url, ExchangeRateQuery $exchangeQuery): ExchangeRate
    {
        $content = $this->request($url);
        $data = StringUtil::jsonToArray($content);

        if (isset($data['error'])) {
            throw new Exception($data['description']);
        }

        $date = new \DateTime();
        $date->setTimestamp($data['timestamp']);
        $currencyPair = $exchangeQuery->getCurrencyPair();

        if ($data['base'] === $currencyPair->getBaseCurrency()
            && isset($data['rates'][$currencyPair->getQuoteCurrency()])
        ) {
            return $this->createRate($currencyPair, (float) ($data['rates'][$currencyPair->getQuoteCurrency()]), $date);
        }

        throw new UnsupportedCurrencyPairException($currencyPair, $this);
    }
490973
public static void setExchangeRequestPath(final HttpServerExchange exchange, final String encodedPath, final String charset, boolean decode, final boolean allowEncodedSlash, StringBuilder decodeBuffer, int maxParameters) throws ParameterLimitException {
        boolean requiresDecode = false;
        for (int i = 0; i < encodedPath.length(); ++i) {
            char c = encodedPath.charAt(i);
            if (c == '?') {
                String part;
                String encodedPart = encodedPath.substring(0, i);
                if (requiresDecode) {
                    part = URLUtils.decode(encodedPart, charset, allowEncodedSlash,false, decodeBuffer);
                } else {
                    part = encodedPart;
                }
                exchange.setRequestPath(part);
                exchange.setRelativePath(part);
                exchange.setRequestURI(encodedPart);
                final String qs = encodedPath.substring(i + 1);
                exchange.setQueryString(qs);
                URLUtils.parseQueryString(qs, exchange, charset, decode, maxParameters);
                return;
            } else if(c == ';') {
                String part;
                String encodedPart = encodedPath.substring(0, i);
                if (requiresDecode) {
                    part = URLUtils.decode(encodedPart, charset, allowEncodedSlash, false, decodeBuffer);
                } else {
                    part = encodedPart;
                }
                exchange.setRequestPath(part);
                exchange.setRelativePath(part);
                for(int j = i; j < encodedPath.length(); ++j) {
                    if (encodedPath.charAt(j) == '?') {
                        exchange.setRequestURI(encodedPath.substring(0, j));
                        String pathParams = encodedPath.substring(i + 1, j);
                        URLUtils.parsePathParams(pathParams, exchange, charset, decode, maxParameters);
                        String qs = encodedPath.substring(j + 1);
                        exchange.setQueryString(qs);
                        URLUtils.parseQueryString(qs, exchange, charset, decode, maxParameters);
                        return;
                    }
                }
                exchange.setRequestURI(encodedPath);
                URLUtils.parsePathParams(encodedPath.substring(i + 1), exchange, charset, decode, maxParameters);
                return;
            } else if(c == '%' || c == '+') {
                requiresDecode = decode;
            }
        }

        String part;
        if (requiresDecode) {
            part = URLUtils.decode(encodedPath, charset, allowEncodedSlash, false, decodeBuffer);
        } else {
            part = encodedPath;
        }
        exchange.setRequestPath(part);
        exchange.setRelativePath(part);
        exchange.setRequestURI(encodedPath);
    }
546345
private function doCreateRate(ExchangeRateQuery $exchangeQuery, DateTimeInterface $requestedDate): ExchangeRate
    {
        $currencyPair = $exchangeQuery->getCurrencyPair();
        $content = $this->request($this->buildUrl($requestedDate));

        $lines = explode("\n", $content);

        if (!$date = \DateTime::createFromFormat(self::DATE_FORMAT, $this->parseDate($lines[0]))) {
            throw new UnsupportedCurrencyPairException($currencyPair, $this);
        }

        $date->setTime(0, 0, 0);
        foreach (array_slice($lines, 2) as $line) {
            if (!preg_match(self::CURRENCY_LINE_PATTERN, $line)) {
                continue;
            }
            list(, , $count, $code, $rate) = explode('|', $line);

            if ($code === $currencyPair->getBaseCurrency()) {
                $rate = (float) str_replace(',', '.', $rate);

                return $this->createRate($currencyPair, (float) ($rate / (int) $count), $date);
            }
        }

        throw new UnsupportedCurrencyPairException($currencyPair, $this);
    }
669571
public function update(ExchangeRateCollection $collection)
    {
        $request = $this->initApiRequest(
            $this->account->getApiToken(Token::API_EXCHANGE_RATES),
            $this->account->getName(),
            $this->activeDomain
        );
        $request->setPath(ApiRequest::PATH_CURRENCY_EXCHANGE_RATE);
        $response = $request->post($collection);
        return self::checkResponse($request, $response);
    }
170002
protected function createExchange($exchangeClass, $channel, array $exchangeOptions)
    {
        /** @var \AMQPExchange $exchange */
        $exchange = new $exchangeClass($channel);
        $exchange->setName($exchangeOptions['name']);

        // If the type is not specified, the exchange must exist
        if (isset($exchangeOptions['type'])) {
            $exchange->setType($exchangeOptions['type']);
            $exchange->setArguments($exchangeOptions['arguments']);
            $exchange->setFlags(
                ($exchangeOptions['passive'] ? AMQP_PASSIVE : AMQP_NOPARAM) |
                ($exchangeOptions['durable'] ? AMQP_DURABLE : AMQP_NOPARAM) |
                ($exchangeOptions['auto_delete'] ? AMQP_AUTODELETE : AMQP_NOPARAM)
            );
            $exchange->declareExchange();
        }

        return $exchange;
    }
489099
public function build(): Swap
    {
        $serviceFactory = new Factory($this->httpClient, $this->requestFactory);
        $services = [];

        foreach ($this->services as $name => $options) {
            $services[] = $serviceFactory->create($name, $options);
        }

        $service = new Chain($services);
        $exchanger = new Exchanger($service, $this->cache, $this->options);

        return new Swap($exchanger);
    }
1175694
def get_exchange(connection, name, create=False):
    
    exchange = Exchange(name, type="topic", passive=not create)

    # bind the exchange to our connection so operations can be performed on it
    bound_exchange = exchange(connection)

    # ensure the exchange exists.  Throw an error if it was created with
    # passive=True and it doesn't exist.
    bound_exchange.declare()

    return bound_exchange
476505
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the ExchangeRateService.
    ExchangeRateServiceInterface exchangeRateService =
        adManagerServices.get(session, ExchangeRateServiceInterface.class);

    // Create an exchange rate.
    ExchangeRate exchangeRate = new ExchangeRate();

    // Set the currency code.
    exchangeRate.setCurrencyCode("AUD");

    // Set the direction of the conversion (from the network currency).
    exchangeRate.setDirection(ExchangeRateDirection.FROM_NETWORK);

    // Set the conversion value as 1.5 (this value is multiplied by 10,000,000,000)
    exchangeRate.setExchangeRate(15000000000L);

    // Do not refresh exchange rate from Google data. Update manually only.
    exchangeRate.setRefreshRate(ExchangeRateRefreshRate.FIXED);

    // Create the exchange rate on the server.
    ExchangeRate[] exchangeRates =
        exchangeRateService.createExchangeRates(new ExchangeRate[] {exchangeRate});

    for (ExchangeRate createdExchangeRate : exchangeRates) {
      System.out.printf(
          "An exchange rate with ID %d, currency code '%s',"
              + " direction '%s', and exchange rate %.2f was created.%n",
          createdExchangeRate.getId(),
          createdExchangeRate.getCurrencyCode(),
          createdExchangeRate.getDirection().getValue(),
          (createdExchangeRate.getExchangeRate() / 10000000000f));
    }
  }
550841
public static function createFromData(array $data)
    {
        if (!isset($data['name'])) {
            throw new DomainException(self::MSG_REQUIRED_NAME);
        }

        if (!isset($data['price'])) {
            throw new DomainException(self::MSG_REQUIRED_NAME);
        }

        if (!isset($data['currency'])) {
            throw new DomainException(self::MSG_REQUIRED_CURRENCY);
        }

        $rate = new self($data);

        return $rate;
    }
865047
public function createBill($login, $amount, $receiver, $message)
    {
        $currencyEntry = new Gamecurrency();
        $currencyEntry->setAmount($amount);
        $currencyEntry->setSenderlogin($login);
        $currencyEntry->setReceiverlogin($receiver);
        $currencyEntry->setMessage($message);
        $currencyEntry->setDatetime(new \DateTime());
        try {
            $currencyEntry->save();

            return $currencyEntry;

        } catch (\Exception $e) {
            $this->logger->error("Error while creating bill", ["exception" => $e]);
            $this->console->write('$f00 Fail.', true);

            return false;
        }
    }
55471
public static function exchangeRateNotAvailable(string $sourceCurrencyCode, string $targetCurrencyCode, string $info = null) : self
    {
        $message = sprintf(
            'No exchange rate available to convert %s to %s',
            $sourceCurrencyCode,
            $targetCurrencyCode
        );

        if ($info !== null) {
            $message .= ' (' . $info . ')';
        }

        return new self($message, $sourceCurrencyCode, $targetCurrencyCode);
    }
165315
private function retrieveExchangeRateFor(Currency $currency): void
    {
        $conversion = sprintf('%s_%s', $this->baseCurrency->getCode(), $currency->getCode());

        $response = $this->client->request('GET', self::EXCHANGE_RATE_API_URL . '/api/v6/convert', [
            'query' => ['q' => $conversion]
        ]);

        $data = json_decode($response->getBody(), true);

        if (! array_key_exists($conversion, $data['results'])) {
            throw CurrencyConverterApiException::currencyNotFound($currency->getCode());
        }

        $this->exchangeRates[$currency->getCode()] = (float) $data['results'][$conversion]['val'];
    }
7723
def get_exchange(self, vhost, name):
        
        vhost = quote(vhost, '')
        name = quote(name, '')
        path = Client.urls['exchange_by_name'] % (vhost, name)
        exch = self._call(path, 'GET')
        return exch
1235593
private <T> T execute(UriComponentsBuilder uriTemplate, HttpMethod method,
			MultiValueMap<String, String> requestData, Class<T> responseType) throws EtcdException {
		long startTimeMillis = System.currentTimeMillis();
		int retry = -1;

		ResourceAccessException lastException = null;
		do {
			lastException = null;

			URI uri = uriTemplate.buildAndExpand(locations[locationIndex]).toUri();

			RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(requestData, null, method,
					uri);

			try {
				ResponseEntity<T> responseEntity = template.exchange(requestEntity, responseType);
				return responseEntity.getBody();
			} catch (HttpStatusCodeException e) {
				EtcdError error = null;
				try {
					error = responseConverter.getObjectMapper().readValue(e.getResponseBodyAsByteArray(),
							EtcdError.class);
				} catch (IOException ex) {
					error = null;
				}
				throw new EtcdException(error, "Failed to execute " + requestEntity + ".", e);
			} catch (ResourceAccessException e) {
				log.debug("Failed to execute " + requestEntity + ", retrying if possible.", e);

				if (locationIndex == locations.length - 1) {
					locationIndex = 0;
				} else {
					locationIndex++;
				}
				lastException = e;
			}
		} while (retry <= retryCount && System.currentTimeMillis() - startTimeMillis < retryDuration);

		if (lastException != null) {
			throw lastException;
		} else {
			return null;
		}
	}
1232142
function queryShare($token, $buyOrder, $shareNumber) {

        try {

            $queryShare = new queryShare();

            $queryShare->token = $token;
            $queryShare->buyOrder = $buyOrder;
            $queryShare->shareNumber = $shareNumber;

            $queryShareResponse = $this->_queryShare($queryShare);

            $xmlResponse = $this->soapClient->__getLastResponse();
            $soapValidation = new SoapValidation($xmlResponse, $this->config->getWebpayCert());
            $validationResult = $soapValidation->getValidationResult();

            if ($validationResult === TRUE) {

                $wsCompleteQuerySharesOutput = $queryShareResponse->return;
                return $wsCompleteQuerySharesOutput;

            } else {

                $error["error"] = "Error validando conexi&oacute;n a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";
                $error["detail"] = "No se pudo completar la conexi&oacute;n con Webpay";

            }
        } catch (Exception $e) {

            $error["error"] = "Error conectando a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";

            $replaceArray = array('<!--' => '', '-->' => '');
            $error["detail"] = str_replace(array_keys($replaceArray), array_values($replaceArray), $e->getMessage());
        }

        return $error;
    }
510923
private function produceExchangeInstance($exchangeName)
    {
        if (isset($this->declaredExchangeInstances[$exchangeName])) {
            return $this->declaredExchangeInstances[$exchangeName];
        }

        if (isset($this->usedExchangeInstances[$exchangeName])) {
            return $this->usedExchangeInstances[$exchangeName];
        }

        $this->ensureChannel();
        $exchange = new AMQPExchange($this->channel);
        $exchange->setName($exchangeName);
        $this->usedExchangeInstances[$exchangeName] = $exchange;
        return $exchange;
    }
1348089
private function executeQuery(string $url, string $data): \stdClass
    {
        $request = $this->getMessageFactory()->createRequest(
            'POST',
            $url,
            [
                'Content-Type' => 'application/json',
            ],
            $data
        );

        $body = $this->getParsedResponse($request);
        $json = json_decode($body);

        // API error
        if (!isset($json)) {
            throw InvalidServerResponse::create($url);
        }

        return $json;
    }