Get the exchange rate between the specified currencies
547924
def rate(self, from_currency, to_currency, date):
        """"""
        return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate(
            to_currency, date
        )
851971
public Currency getCurrency(String name) {
        Currency result;
        if (!currencyList.containsKey(name)) {
            result = Common.getInstance().getStorageHandler().getStorageEngine().getCurrency(name);
            if (result != null) {
                currencyList.put(result.getName(), result);
            }
        } else {
            result = currencyList.get(name);
        }
        return result;
    }
285412
def get_currencies(self):
        """"""
        try:
            resp = get(self.endpoint)
            resp.raise_for_status()
        except exceptions.RequestException as e:
            self.log(logging.ERROR, "%s: Problem whilst contacting endpoint:\n%s", self.name, e)
        else:
            with open(self._cached_currency_file, 'wb') as fd:
                fd.write(resp.content)

        try:
            root = ET.parse(self._cached_currency_file).getroot()
        except FileNotFoundError as e:
            raise RuntimeError("%s: XML not found at endpoint or as cached file:\n%s" % (self.name, e))

        return root
456552
function convert( $fromCurrency, $toCurrency, $value, $applyRounding = true )
    {
        if ( $fromCurrency == false || $toCurrency == false || $fromCurrency == $toCurrency || $value == 0 )
            return $value;

        $math = $this->mathHandler();

        $crossRate = $this->crossRate( $fromCurrency, $toCurrency );
        $convertedValue = $math->mul( $value, $crossRate );
        if ( $applyRounding )
        {
            switch ( $this->roundingType() )
            {
                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_ROUND':
                {
                    $convertedValue = $math->round( $convertedValue, $this->roundingPrecision(), $this->roundingTarget() );
                } break;

                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_CEIL':
                {
                    $convertedValue = $math->ceil( $convertedValue, $this->roundingPrecision(), $this->roundingTarget() );
                } break;

                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_FLOOR':
                {
                    $convertedValue = $math->floor( $convertedValue, $this->roundingPrecision(), $this->roundingTarget() );
                } break;

                case 'EZ_CURRENCY_CONVERTER_ROUNDING_TYPE_NONE':
                default:
                    break;
            }
        }

        return $convertedValue;
    }
587152
def import_fx_rates(self, rates: List[PriceModel]):
        
        have_new_rates = False

        base_currency = self.get_default_currency()

        for rate in rates:
            assert isinstance(rate, PriceModel)

            currency = self.get_by_symbol(rate.symbol)
            amount = rate.value

            # Do not import duplicate prices.
            # todo: if the price differs, update it!
            # exists_query = exists(rates_query)
            has_rate = currency.prices.filter(Price.date == rate.datetime.date()).first()
            # has_rate = (
            #     self.book.session.query(Price)
            #     .filter(Price.date == rate.date.date())
            #     .filter(Price.currency == currency)
            # )
            if not has_rate:
                log(INFO, "Creating entry for %s, %s, %s, %s",
                    base_currency.mnemonic, currency.mnemonic, rate.datetime.date(), amount)
                # Save the price in the exchange currency, not the default.
                # Invert the rate in that case.
                inverted_rate = 1 / amount
                inverted_rate = inverted_rate.quantize(Decimal('.00000000'))

                price = Price(commodity=currency,
                              currency=base_currency,
                              date=rate.datetime.date(),
                              value=str(inverted_rate))
                have_new_rates = True

        # Save the book after the prices have been created.
        if have_new_rates:
            log(INFO, "Saving new prices...")
            self.book.flush()
            self.book.save()
        else:
            log(INFO, "No prices imported.")
1170796
function Money(knwlInstance) {
    var isoTypes =
        [
            {
                iso: 'EUR',
                match: '^euro?s?$'
            }
        ,
            {
                iso: 'USD',
                match: '^usd?s?$'
            }
        ]


    var formats = [
        '^(?!0\.00)[0-9]{1,3}(,[0-9]{3})*(\.[0-9][0-9])?$', // EUR,USD
        '^(?!0,00)[0-9]{1,3}(\.[0-9]{3})*(,[0-9][0-9])?$' // inverted EUR, USD
    ]



    this.calls = function() {
        var words = knwlInstance.words.get('linkWords');              // get the String as an array of linked Words
        var results = [];                                         // prepare results
        var typeFound = {
            index: null
        }
        var quantityFound = {
            index: null
        }

        words.forEach( function(word) {                           // check each word



            formats.some( function(format){
                 var regEx = new RegExp(format);
                 var regExRes = regEx.exec(word);
                 if( regExRes != null) {
                     quantityFound.index = 0;
                     quantityFound.quantity = regExRes[0];
                     return true;
                 }
            });
            isoTypes.some( function(type){
                 regEx = new RegExp(type.match);
                 var regExRes = regEx.exec(word);
                 typeFound.value = type.iso;
                 if( regExRes != null) {
                     typeFound.index = 0;
                     return true;
                 }
            });


            if (quantityFound.index === 0 ){
                if (typeFound.index === 1){
                    results.push(
                        {type: typeFound.value,
                        quantity: quantityFound.quantity,
                        value: typeFound.value + ' ' + quantityFound.quantity
                        });
                }
            }

            if (quantityFound.index === 1 ){
                if (typeFound.index === 0){
                    results.push(
                        {type: typeFound.value,
                        quantity: quantityFound.quantity,
                        value: typeFound.value + ' ' + quantityFound.quantity
                        });
                }
            }


            quantityFound.index++;
            typeFound.index++;
        });

        return results;
    };
}
858358
def get_rate_source():
    """"""
    backend = money_rates_settings.DEFAULT_BACKEND()
    try:
        return RateSource.objects.get(name=backend.get_source_name())
    except RateSource.DoesNotExist:
        raise CurrencyConversionException(
            "Rate for %s source do not exists. "
            "Please run python manage.py update_rates" % backend.get_source_name())
126462
def currency(money):
    
    decimals = getattr(settings, 'MIDNIGHT_CATALOG_DECIMALS', 2)
    money = round(float(money), decimals)
    symbol = getattr(settings, 'MIDNIGHT_CATALOG_CURRENCY', 'руб')
    if decimals > 0:
        formatted = (str("%0."+str(decimals)+"f") % money)[-decimals-1:]
    else:
        formatted = ""
    return "%s%s %s" % (intcomma(int(money)), formatted, symbol)
76680
def get_rate(currency):
    """"""
    source = get_rate_source()
    try:
        return Rate.objects.get(source=source, currency=currency).value
    except Rate.DoesNotExist:
        raise CurrencyConversionException(
            "Rate for %s in %s do not exists. "
            "Please run python manage.py update_rates" % (
                currency, source.name))
869132
private void processDefaultCurrency(Integer currencyID) throws SQLException
   {
      List<Row> rows = getRows("select * from " + m_schema + "currtype where curr_id=?", currencyID);
      if (!rows.isEmpty())
      {
         Row row = rows.get(0);
         m_reader.processDefaultCurrency(row);
      }
   }
444989
def get_exchange_rates(self, **params):
        """"""
        response = self._get('v2', 'exchange-rates', params=params)
        return self._make_api_object(response, APIObject)
661859
def convert_currency(amount, from_currency, to_currency):
    '''
    

    '''
    try:
        rate = CurrencyRate.objects.get(
            from_currency__iso_code=from_currency,
            to_currency__iso_code=to_currency)
    except CurrencyRate.DoesNotExist:
        return _('n/a')
    try:
        history = rate.history.all()[0]
    except IndexError:
        return _('n/a')
    return amount * history.value
403103
function (currency, callback) {
      // Call an asynchronous function, often a save() to DB
      self.getPricesForSingleCurrency(from, to, currency, function (err, result) {
        if (err) {
          callback(err)
        } else {
          ratesWithTimes[currency] = result
          callback()
        }
      })
    }
22909
@Override
    public Set<CurrencyUnit> getCurrencies(CurrencyQuery query) {
        Set<CurrencyUnit> result = new HashSet<>();
        for (Locale locale : query.getCountries()) {
            try {
                result.add(Waehrung.of(Currency.getInstance(locale)));
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Cannot get currency for locale '" + locale + "':", ex);
            }
        }
        for (String currencyCode : query.getCurrencyCodes()) {
            try {
                result.add(Waehrung.of(currencyCode));
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Cannot get currency '" + currencyCode + "':", ex);
            }
        }
        for (CurrencyProviderSpi spi : Bootstrap.getServices(CurrencyProviderSpi.class)) {
            result.addAll(spi.getCurrencies(query));
        }
        return result;
    }
1367875
def get_currencysymbol(self, code):
        """"""
        if not self._symbols:
            symbolpath = os.path.join(self._dir, 'currencies.json')
            with open(symbolpath, encoding='utf8') as df:
                self._symbols = json.load(df)
        return self._symbols.get(code)
1052628
public static function getCurrencyList()
    {
        return [
            'EUR' => ['name' => 'Euro',                  'code' => 978, 'fraction' => 2],
            'USD' => ['name' => 'Dollar Américain',      'code' => 840, 'fraction' => 2],
            'CHF' => ['name' => 'Franc Suisse',          'code' => 756, 'fraction' => 2],
            'GBP' => ['name' => 'Livre Sterling',        'code' => 826, 'fraction' => 2],
            'CAD' => ['name' => 'Dollar Canadien',       'code' => 124, 'fraction' => 2],
            'JPY' => ['name' => 'Yen',                   'code' => 392, 'fraction' => 0],
            'MXN' => ['name' => 'Peso Mexicain',         'code' => 484, 'fraction' => 2],
            'TRY' => ['name' => 'Nouvelle Livre Turque', 'code' => 949, 'fraction' => 2],
            'AUD' => ['name' => 'Dollar Australien',     'code' => 036, 'fraction' => 2],
            'NZD' => ['name' => 'Dollar Néo-Zélandais',  'code' => 554, 'fraction' => 2],
            'NOK' => ['name' => 'Couronne Norvégienne',  'code' => 578, 'fraction' => 2],
            'BRL' => ['name' => 'Real Brésilien',        'code' => 986, 'fraction' => 2],
            'ARS' => ['name' => 'Peso Argentin',         'code' => 032, 'fraction' => 2],
            'KHR' => ['name' => 'Riel',                  'code' => 116, 'fraction' => 2],
            'TWD' => ['name' => 'Dollar de Taiwan',      'code' => 901, 'fraction' => 2],
            'SEK' => ['name' => 'Couronne Suédoise',     'code' => 752, 'fraction' => 2],
            'DKK' => ['name' => 'Couronne Danoise',      'code' => 208, 'fraction' => 2],
            'KRW' => ['name' => 'Won',                   'code' => 410, 'fraction' => 0],
            'SGD' => ['name' => 'Dollar de Singapour',   'code' => 702, 'fraction' => 2],
            'XPF' => ['name' => 'Franc Polynésien',      'code' => 953, 'fraction' => 0],
            'XOF' => ['name' => 'Franc CFA',             'code' => 952, 'fraction' => 0],
        ];
    }
335271
def rate(self, currency):
        """"""
        if not self._backend:
            raise ExchangeBackendNotInstalled()
        return self._backend.rate(currency)