Creates or updates rates for a source
767742
def update_rates(self):
        
        source, created = RateSource.objects.get_or_create(name=self.get_source_name())
        source.base_currency = self.get_base_currency()
        source.save()

        for currency, value in six.iteritems(self.get_rates()):
            try:
                rate = Rate.objects.get(source=source, currency=currency)
            except Rate.DoesNotExist:
                rate = Rate(source=source, currency=currency)

            rate.value = value
            rate.save()
262140
def update_source!(source)
      # e.g. /\[%\s+javascript\s+((\S+)\s?(\S+))\s+%\]/
      regex = /
        #{Regexp.escape options[:src_pre]}
        \s+#{type.to_s.singularize}
        \s+((\S+)\s?(\S+))\s+
        #{Regexp.escape options[:src_post]}
      /x
      source.gsub! regex do
        if Regexp.last_match[2] == options[:inline]
          assets[Regexp.last_match[3]].to_s
        else
          asset = write Regexp.last_match[1]

          # @todo Raise warning or error if asset not found.
          p "asset not found: #{Regexp.last_match[1]}" && next if asset.nil?

          "#{options[:cdn]}#{format_path asset}"
        end
      end
      true
    end
1213070
def maybe_rate_limit(client, headers, atexit=False):
    """"""
    # pylint: disable=fixme
    # pylint: disable=global-statement
    # FIXME: Yes, I know this is not great. We'll fix it later. :-)
    global LAST_CLIENT, LAST_HEADERS

    if LAST_CLIENT and LAST_HEADERS:
        # Wait based on previous client/headers
        rate_limit(LAST_CLIENT, LAST_HEADERS, atexit=atexit)

    LAST_CLIENT = copy.copy(client)
    LAST_HEADERS = copy.copy(headers)
545137
def sync_sources(self, force=False):
        """"""
        from ambry.orm.file import File

        self.dstate = self.STATES.BUILDING

        synced = 0

        for fc in [File.BSFILE.SOURCES]:
            bsf = self.build_source_files.file(fc)
            if bsf.fs_is_newer or force:
                self.log('Syncing {}'.format(bsf.file_name))
                bsf.fs_to_objects()
                synced += 1

        return synced
1070082
def rates(ctx, opts):
    """"""
    click.echo("Retrieving rate limits ... ", nl=False)

    context_msg = "Failed to retrieve status!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            resources_limits = get_rate_limits()

    click.secho("OK", fg="green")

    headers = ["Resource", "Throttled", "Remaining", "Interval (Seconds)", "Reset"]

    rows = []
    for resource, limits in six.iteritems(resources_limits):
        rows.append(
            [
                click.style(resource, fg="cyan"),
                click.style(
                    "Yes" if limits.throttled else "No",
                    fg="red" if limits.throttled else "green",
                ),
                "%(remaining)s/%(limit)s"
                % {
                    "remaining": click.style(
                        six.text_type(limits.remaining), fg="yellow"
                    ),
                    "limit": click.style(six.text_type(limits.limit), fg="yellow"),
                },
                click.style(six.text_type(limits.interval), fg="blue"),
                click.style(six.text_type(limits.reset), fg="magenta"),
            ]
        )

    if resources_limits:
        click.echo()
        utils.pretty_print_table(headers, rows)

    click.echo()

    num_results = len(resources_limits)
    list_suffix = "resource%s" % ("s" if num_results != 1 else "")
    utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix)
1247988
def create_feature_type_rates(self, created=False):
        
        if created:
            for feature_type in FeatureType.objects.all():
                FeatureTypeRate.objects.create(role=self, feature_type=feature_type, rate=0)
219960
def rate(self):
        """"""
        return float(self._eta.rate_unstable if self.eta_every > 1 else self._eta.rate)
192355
def cli(env, identifier, price=False, guests=False):
    """"""
    dhost = SoftLayer.DedicatedHostManager(env.client)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    result = dhost.get_host(identifier)
    result = utils.NestedDict(result)

    table.add_row(['id', result['id']])
    table.add_row(['name', result['name']])
    table.add_row(['cpu count', result['cpuCount']])
    table.add_row(['memory capacity', result['memoryCapacity']])
    table.add_row(['disk capacity', result['diskCapacity']])
    table.add_row(['create date', result['createDate']])
    table.add_row(['modify date', result['modifyDate']])
    table.add_row(['router id', result['backendRouter']['id']])
    table.add_row(['router hostname', result['backendRouter']['hostname']])
    table.add_row(['owner', formatting.FormattedItem(
        utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') or formatting.blank(),)])

    if price:
        total_price = utils.lookup(result,
                                   'billingItem',
                                   'nextInvoiceTotalRecurringAmount') or 0
        total_price += sum(p['nextInvoiceTotalRecurringAmount']
                           for p
                           in utils.lookup(result,
                                           'billingItem',
                                           'children') or [])
        table.add_row(['price_rate', total_price])

    table.add_row(['guest count', result['guestCount']])
    if guests:
        guest_table = formatting.Table(['id', 'hostname', 'domain', 'uuid'])
        for guest in result['guests']:
            guest_table.add_row([
                guest['id'], guest['hostname'], guest['domain'], guest['uuid']])
        table.add_row(['guests', guest_table])

    table.add_row(['datacenter', result['datacenter']['name']])

    env.fout(table)
809665
def rate_limit(client, headers, atexit=False):
    """"""
    if not client or not headers:
        return False

    if not getattr(client.config, "rate_limit", False):
        return False

    rate_info = RateLimitsInfo.from_headers(headers)
    if not rate_info or not rate_info.interval:
        return False

    if rate_info.interval:
        cb = getattr(client.config, "rate_limit_callback", None)
        if cb and callable(cb):
            cb(rate_info, atexit=atexit)
        time.sleep(rate_info.interval)
    return True
1131924
def rate():
    """"""
    auth = request.authorization

    if not auth or not check_auth(auth.username, auth.password):
        return "60/minute"
    else:
        return "600/minute"
1267606
public static SettingsRate get(Map<String, String[]> clArgs, SettingsCommand command)
    {
        String[] params = clArgs.remove("-rate");
        if (params == null)
        {
            switch (command.type)
            {
                case WRITE:
                case COUNTER_WRITE:
                    if (command.count > 0)
                    {
                        ThreadOptions options = new ThreadOptions();
                        options.accept("threads=200");
                        return new SettingsRate(options);
                    }
            }
            AutoOptions options = new AutoOptions();
            options.accept("auto");
            return new SettingsRate(options);
        }
        GroupedOptions options = GroupedOptions.select(params, new AutoOptions(), new ThreadOptions());
        if (options == null)
        {
            printHelp();
            System.out.println("Invalid -rate options provided, see output for valid options");
            System.exit(1);
        }
        if (options instanceof AutoOptions)
            return new SettingsRate((AutoOptions) options);
        else if (options instanceof ThreadOptions)
            return new SettingsRate((ThreadOptions) options);
        else
            throw new IllegalStateException();
    }
876540
public function updateRatesAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
            return $response;
        }

        try {
            $event = new CurrencyUpdateRateEvent();

            $this->dispatch(TheliaEvents::CURRENCY_UPDATE_RATES, $event);

            if ($event->hasUndefinedRates()) {
                return $this->render('currencies', [
                    'undefined_rates' => $event->getUndefinedRates()
                ]);
            }
        } catch (\Exception $ex) {
            // Any error
            return $this->errorPage($ex);
        }

        return $this->redirectToListTemplate();
    }
542524
def rate_limit(self, name, limit=5, per=60, debug=False):
        
        return RateLimit(self, name, limit, per, debug)
362614
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
    """"""
    return util.rate_limited(max_per_hour, *args)
172421
def cache_rate(self, currency, date, rate):
        
        if not self.is_supported(defaults.INTERNAL_CURRENCY):
            logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency))
        else:
            cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date))
796620
def get_rates(file,au_min=25,au_max=150):
    
    import os, string

    rate_command='rate.pl --file %s %d ' % ( file, au_min)
    rate=os.popen(rate_command)
    line=rate.readline()
    print line
    rate.close()
    (min_rate, min_ang, min_aw, min_rmin, min_rmax)=string.split(line)
    rate_command='rate.pl --file %s %d ' % ( file, au_min)
    rate=os.popen(rate_command)
    line=rate.readline()
    rate.close()
    (max_rate, max_ang, max_aw, max_rmin, max_rmax)=string.split(line)
    rmin=float(min(max_rmin, min_rmin))
    rmax=float(max(max_rmax, min_rmax))
    aw=float(max(max_aw,min_aw))
    angle=(float(max_ang)+float(min_ang))/2.0
    rates={'rmin': rmin, 'rmax': rmax, 'angle': angle, 'aw': aw}
    return rates
882146
def refresh_entitlement(owner, repo, identifier, show_tokens):
    """"""
    client = get_entitlements_api()

    with catch_raise_api_exception():
        data, _, headers = client.entitlements_refresh_with_http_info(
            owner=owner, repo=repo, identifier=identifier, show_tokens=show_tokens
        )

    ratelimits.maybe_rate_limit(client, headers)
    return data.to_dict()