コード例 #1
0
 def get_cell(self, value, col_settings):
     if col_settings.get('html', False):
         return mark_safe(value)
     if col_settings.get('text', False):
         return value
     try:
         value = float(value)
         if 'precision' in col_settings:
             value = round(value, col_settings['precision'])
         if col_settings.get('number_word'):
             if value < 0:
                 formatted_value = '-{}'.format(intword(-value))
             else:
                 formatted_value = intword(value)
         elif col_settings.get('number_format', True):
             formatted_value = number_format(value,
                                             decimal_pos=col_settings.get(
                                                 'decimals', None),
                                             force_grouping=True)
         else:
             formatted_value = str(int(value))
         return mark_safe(u'{prefix}{value}{postfix}'.format(
             prefix=col_settings.get('prefix', ''),
             value=formatted_value,
             postfix=col_settings.get('postfix', '')).strip())
     except ValueError:
         return value
コード例 #2
0
def get_library_stats():
    """
    Loads library stats as computed via `write_library_stats` management command.

    In the future, these stats may be served up directly from `scaife-cts-api`
    at the conclusion of indexing.  For now, `scaife-viewer` seens to be the most
    sensible place to compute the stats since it has the connection info for both
    Nautilus and ElasticSearch.
    """
    key = "library-stats"
    library_stats = cache.get(key, None)
    if library_stats is None:
        data = json.load(open(LIBRARY_STATS_PATH))
        library_stats = {
            "works_count":
            intcomma(data["works_count"]),
            "text_counts_total":
            intcomma(data["text_counts"]["total"]),
            "text_counts_greek":
            intcomma(data["text_counts"]["grc"]),
            "text_counts_latin":
            intcomma(data["text_counts"]["lat"]),
            "word_counts_total":
            intword(data["word_counts"]["total"]).split(" ")[0],
            "word_counts_greek":
            intword(data["word_counts"]["grc"]).split(" ")[0],
            "word_counts_latin":
            intword(data["word_counts"]["lat"]).split(" ")[0]
        }
        cache.set(key, library_stats, None)
    return library_stats
コード例 #3
0
 def not_started_cost_widget(self):
     """docstring for construction_cost"""
     not_started_cost = Widget('planned projects')
     not_started_cost.value = intword_span(
         intword(self.projects.not_started_cost()))
     not_started_cost.subtitle = "{0} projects".format(
         self.projects.not_started().count())
     return not_started_cost
コード例 #4
0
 def cost_by_year_widget(self, year):
     """docstring for construction_cost"""
     not_started_cost = Widget('{0} projects'.format(year))
     not_started_cost.value = intword_span(
         intword(self.projects.cost_by_year(year)))
     not_started_cost.subtitle = "{0} projects".format(
         self.projects.by_year(year).count())
     return not_started_cost
コード例 #5
0
def humanize(value):
    try:
        number, word = intword(value).split()
    except AttributeError:
        # lower than 1M
        return intcomma(value, use_l10n=False)
    word = word[0].upper()
    return "%s %s" % (number, word)
コード例 #6
0
ファイル: views.py プロジェクト: CivicVision/infrastructure
 def project_cost(self):
     """docstring for construction_cost"""
     project_cost = Widget('All projects')
     project_cost.headline_link = reverse('projects')
     project_cost.value = intword_span(intword(self.projects.overall_cost()))
     project_cost.subtitle = "{0} projects".format(self.projects.count())
     project_cost.subtitle_link = reverse('projects')
     return project_cost
コード例 #7
0
ファイル: views.py プロジェクト: datamade/bga-pensions
 def _format_large_number(self, number):
     word = intword(number)
     try:
         float(word)
     except ValueError:
         return word
     else:
         return intcomma(number)
コード例 #8
0
 def project_cost(self):
     """docstring for construction_cost"""
     project_cost = Widget('All projects')
     project_cost.headline_link = reverse('projects')
     project_cost.value = intword_span(intword(
         self.projects.overall_cost()))
     project_cost.subtitle = "{0} projects".format(self.projects.count())
     project_cost.subtitle_link = reverse('projects')
     return project_cost
コード例 #9
0
def intword(value):
    value = humanize.intword(value)
    if isinstance(value, int):
        # value may be so small that humanize.intword returns the input value
        return value
    return (value.replace('million',
                          'm').replace('billion',
                                       'bn').replace('trillion',
                                                     'tn').replace('.0', ''))
コード例 #10
0
    def _generate_txt(self, stats):
        wins = stats["wins"]
        users = stats["users"]
        stats_txt = """
            Export Wins input by officers:

            Total wins generated: {}
            Total expected export value: {}
            Total expected non-export value: {}


            -----


            Export wins customers have responded to:

            Total wins responded to: {}
            Total expected export value: {}
            Total expected non export value: {}


            -----


            Users (officers):

            Total logged in last week: {}
            Total who have submitted wins: {}
            Total who have been issued password: {}

            """.format(
            wins["total"],
            "£{}".format(intword(wins["total-export-funds"])),
            "£{}".format(intword(wins["total-non-export-funds"])),
            wins["confirmed"],
            "£{}".format(intword(wins["total-confirmed-export-funds"])),
            "£{}".format(
                intword(wins["total-confirmed-non-export-funds"])),
            users["total-active"],
            users["total-creating-wins"],
            users["total"]
        )
        return textwrap.dedent(stats_txt)
コード例 #11
0
ファイル: views.py プロジェクト: CivicVision/infrastructure
 def phases(self):
     """docstring for phases"""
     row_widgets = []
     for (phase_class,phase) in PHASE_URLS:
         phase_widget = Widget(phase)
         phase_widget.headline_link = reverse('phase_projects',kwargs={'phase':phase_class})
         phase_widget.subtitle = '{0} projects'.format(self.projects.by_phase(phase).count())
         phase_widget.value = intword_span(intword(self.projects.by_phase(phase).overall_cost()))
         phase_widget.widget_class = phase_class
         row_widgets.append(phase_widget)
     return row_widgets
コード例 #12
0
ファイル: views.py プロジェクト: CivicVision/infrastructure
 def asset_types(self):
     """docstring for asset_types"""
     row_widgets = []
     for (asset_type_class,asset_type) in ASSET_TYPE_URLS:
         asset_widget = Widget(asset_type)
         asset_widget.headline_link = reverse('asset_type_projects',kwargs={'asset_type':asset_type_class})
         asset_widget.subtitle = '{0} projects'.format(Project.objects.all().by_asset_group(asset_type).count())
         asset_widget.widget_class = asset_type_class
         asset_widget.value = intword_span(intword(self.projects.by_asset_group(asset_type).overall_cost()))
         row_widgets.append(asset_widget)
     return row_widgets
コード例 #13
0
ファイル: tasks.py プロジェクト: mitchellrj/pubbot
def fight(msg, word1, word2):
    def _score(word):
        r = requests.get('http://www.google.co.uk/search',
                         params={'q': word, 'safe': 'off'})
        soup = BeautifulSoup(r.text)
        score_string = soup.find(id='resultStats').string
        return int(''.join(re.findall('\d+', score_string)))

    score1 = _score(word1)
    score2 = _score(word2)

    winner = word1 if score1 > score2 else word2

    score1 = intword(score1)
    score2 = intword(score2)

    return {
        'content': '%(word1)s (%(score1)s) vs %(word2)s (%(score2)s) -- %(winner)s wins!' %
        locals(),
    }
コード例 #14
0
ファイル: views.py プロジェクト: CivicVision/infrastructure
 def districts(self):
     """docstring for districts"""
     row_widgets = []
     for district in range(1,10):
         district_widget = Widget('District {0}'.format(district))
         district_widget.headline_link = reverse('district_projects',kwargs={'district': district})
         district_widget.subtitle = '{0} projects'.format(self.projects.by_district(district).count())
         district_widget.value = intword_span(intword(self.projects.by_district(district).overall_cost()))
         district_widget.widget_class = 'district-{0}'.format(district)
         row_widgets.append(district_widget)
     return row_widgets
コード例 #15
0
def small_intword(value):
    try:
        value = int(value)
    except (TypeError, ValueError):
        return value

    if 1000 < value < 1000000:
        new_value = value / 1000
        formated = defaultfilters.floatformat(new_value, 1)
        return '%(value)s mil' % dict(value=formated)

    return intword(value)
コード例 #16
0
 def phases(self):
     """docstring for phases"""
     row_widgets = []
     for (phase_class, phase) in PHASE_URLS:
         phase_widget = Widget(phase)
         phase_widget.headline_link = reverse('phase_projects',
                                              kwargs={'phase': phase_class})
         phase_widget.subtitle = '{0} projects'.format(
             self.projects.by_phase(phase).count())
         phase_widget.value = intword_span(
             intword(self.projects.by_phase(phase).overall_cost()))
         phase_widget.widget_class = phase_class
         row_widgets.append(phase_widget)
     return row_widgets
コード例 #17
0
 def districts(self):
     """docstring for districts"""
     row_widgets = []
     for district in range(1, 10):
         district_widget = Widget('District {0}'.format(district))
         district_widget.headline_link = reverse(
             'district_projects', kwargs={'district': district})
         district_widget.subtitle = '{0} projects'.format(
             self.projects.by_district(district).count())
         district_widget.value = intword_span(
             intword(self.projects.by_district(district).overall_cost()))
         district_widget.widget_class = 'district-{0}'.format(district)
         row_widgets.append(district_widget)
     return row_widgets
コード例 #18
0
ファイル: views.py プロジェクト: davelab6/botbot-web
    def get_context_data(self, **kwargs):
        nick = self.request.GET.get('nick')

        ranks = self.channel.kudos_set.ranks(debug=nick)
        top_tier = ranks[:100]
        if len(top_tier) > 20:
            scoreboard = [r[0] for r in random.sample(top_tier, 20)]
        elif len(top_tier) > 4:
            scoreboard = random.shuffle([r[0] for r in ranks])
        else:
            scoreboard = None
        kwargs.update({
            'random_scoreboard': scoreboard,
        })

        try:
            channel_kudos = self.channel.kudostotal
        except KudosTotal.DoesNotExist:
            channel_kudos = None
        if channel_kudos and channel_kudos.message_count:
            if channel_kudos.message_count > 1000000:
                kwargs['channel_messages'] = humanize.intword(
                    channel_kudos.message_count)
            else:
                kwargs['channel_messages'] = humanize.intcomma(
                    channel_kudos.message_count)
            kwargs['channel_kudos_perc'] = '{:.2%}'.format(
                channel_kudos.appreciation)

        if nick:
            nick_lower = nick.lower()
            details = None
            for rank_nick, alltime, info in ranks:
                if rank_nick == nick_lower:
                    details = {
                        'alltime':
                        alltime,
                        'alltime_perc':
                        self.rounded_percentage(alltime, len(ranks)),
                        'current':
                        info['current_rank'],
                        'current_perc':
                        self.rounded_percentage(info['current_rank'],
                                                len(ranks)),
                    }
                    break
            kwargs['search'] = {'nick': nick, 'details': details}

        return super(ChannelKudos, self).get_context_data(**kwargs)
コード例 #19
0
 def asset_types(self):
     """docstring for asset_types"""
     row_widgets = []
     for (asset_type_class, asset_type) in ASSET_TYPE_URLS:
         asset_widget = Widget(asset_type)
         asset_widget.headline_link = reverse(
             'asset_type_projects', kwargs={'asset_type': asset_type_class})
         asset_widget.subtitle = '{0} projects'.format(
             Project.objects.all().by_asset_group(asset_type).count())
         asset_widget.widget_class = asset_type_class
         asset_widget.value = intword_span(
             intword(
                 self.projects.by_asset_group(asset_type).overall_cost()))
         row_widgets.append(asset_widget)
     return row_widgets
コード例 #20
0
ファイル: views.py プロジェクト: BotBotMe/botbot-web
    def get_context_data(self, **kwargs):
        nick = self.request.GET.get('nick')

        ranks = self.channel.kudos_set.ranks(debug=nick)
        top_tier = ranks[:100]
        if len(top_tier) > 20:
            scoreboard = [r[0] for r in random.sample(top_tier, 20)]
        elif len(top_tier) > 4:
            scoreboard = random.shuffle([r[0] for r in ranks])
        else:
            scoreboard = None
        kwargs.update({
            'random_scoreboard': scoreboard,
        })

        try:
            channel_kudos = self.channel.kudostotal
        except KudosTotal.DoesNotExist:
            channel_kudos = None
        if channel_kudos and channel_kudos.message_count:
            if channel_kudos.message_count > 1000000:
                kwargs['channel_messages'] = humanize.intword(
                    channel_kudos.message_count)
            else:
                kwargs['channel_messages'] = humanize.intcomma(
                    channel_kudos.message_count)
            kwargs['channel_kudos_perc'] = '{:.2%}'.format(
                channel_kudos.appreciation)

        if nick:
            nick_lower = nick.lower()
            details = None
            for rank_nick, alltime, info in ranks:
                if rank_nick == nick_lower:
                    details = {
                        'alltime': alltime,
                        'alltime_perc': self.rounded_percentage(
                            alltime, len(ranks)),
                        'current': info['current_rank'],
                        'current_perc': self.rounded_percentage(
                            info['current_rank'], len(ranks)),
                    }
                    break
            kwargs['search'] = {'nick': nick, 'details': details}

        return super(ChannelKudos, self).get_context_data(**kwargs)
コード例 #21
0
def intcomma_word(value):
    if value >= 1_000_000:
        return intword(value)
    return intcomma_floatformat(value)
コード例 #22
0
ファイル: views.py プロジェクト: CivicVision/infrastructure
 def not_started_cost_widget(self):
     """docstring for construction_cost"""
     not_started_cost = Widget('planned projects')
     not_started_cost.value = intword_span(intword(self.projects.not_started_cost()))
     not_started_cost.subtitle = "{0} projects".format(self.projects.not_started().count())
     return not_started_cost
コード例 #23
0
 def readable_last_sold_price(self):
     return intword(self.last_sold_price)
コード例 #24
0
 def readable_price(self):
     return intword(self.price)
コード例 #25
0
 def readable_rentzestimate_amount(self):
     return intword(self.rentzestimate_amount)
コード例 #26
0
 def readable_rent_price(self):
     return intword(self.rent_price)
コード例 #27
0
 def construction_cost(self):
     """docstring for construction_cost"""
     construction_cost = Widget('construction \n $$$')
     construction_cost.value = intword_span(
         intword(self.projects.construction_cost()))
     return construction_cost
コード例 #28
0
 def readable_tax_value(self):
     return intword(self.tax_value)
コード例 #29
0
ファイル: models.py プロジェクト: glossm/api
 def number_of_speakers(self):
     return intword(self.num_speakers)
コード例 #30
0
 def amount_full_satoshi_word(self):
     return "{}".format(intword(int(self.amount_full_satoshi)))
コード例 #31
0
ファイル: views.py プロジェクト: Solfasol/suggest
                        user_id=','.join([str(k) for k, v in top_100]),
                    )
                except TwitterRateLimitError, e:
                    if last_suggestion:
                        suggestions = last_suggestion
                else:
                    for user in response.data:
                        if foafs[int(user['id'])] < 2:
                            break
                        suggestions.append({
                            'id': user['id'],
                            'name': user['name'],
                            'screen_name': user['screen_name'],
                            'profile_image_url': user['profile_image_url'],
                            'created_at': user['created_at'],
                            'favourites_count': intword(user['favourites_count']),
                            'url': user['url'],
                            'listed_count': user['listed_count'],
                            'lang': user['lang'],
                            'followers_count': intword(user['followers_count']),
                            'friends_count': intword(user['friends_count']),
                            'description': user['description'],
                            'verified': user['verified'],
                            'statuses_count': intword(user['statuses_count']),
                            'status': user.get('status'),
                            'following_friends': [friends[fid] for fid in foafs[int(user['id'])]],
                        })

                Suggestion.objects.create(
                    user=self.request.user,
                    suggestions=suggestions,
コード例 #32
0
 def _budget_limit(self, budget: money_models.Budget) -> str:
     return intword(budget.limit)
コード例 #33
0
ファイル: views.py プロジェクト: CivicVision/infrastructure
 def construction_cost(self):
     """docstring for construction_cost"""
     construction_cost = Widget('construction \n $$$')
     construction_cost.value = intword_span(intword(self.projects.construction_cost()))
     return construction_cost
コード例 #34
0
ファイル: _humanize.py プロジェクト: kafura0/OranKids
def intword(source):
    return humanize.intword(source)
コード例 #35
0
ファイル: views.py プロジェクト: CivicVision/infrastructure
 def cost_by_year_widget(self,year):
     """docstring for construction_cost"""
     not_started_cost = Widget('{0} projects'.format(year))
     not_started_cost.value = intword_span(intword(self.projects.cost_by_year(year)))
     not_started_cost.subtitle = "{0} projects".format(self.projects.by_year(year).count())
     return not_started_cost