Пример #1
0
 def title(self) -> str:
     """Get a title string for a DeTable"""
     max_rank = self.max_rank()
     table_size = self.detableentry_set.count()
     if max_rank == 1:
         special_titles = {
             2: _("Final"),
             4: _("SemiFinal"),
             8: _("QuarterFinal")
         }
         table_size = self.detableentry_set.count()
         # Translators: title for a de table e.g. Table of 64
         return special_titles.get(
             table_size,
             _("Table of %(size)i") % {'size': table_size})
     elif table_size == 2:
         # Translators: title for a de table of 2 e.g. Fight for 9th
         return _("Fight for %(max_rank)s") % {
             'max_rank': ordinal(max_rank)
         }
     else:
         # Translators: title for a de table e.g. Fights for 9th between 8
         return _("Fights for %(max_rank)s between %(table_size)i") % {
             'max_rank': ordinal(max_rank),
             'table_size': table_size
         }
Пример #2
0
def page_groundhog_removals_scoreboard_annual(request):
    step_hit_count_by_page(request.path)
    logs = groundhog_removal_scoreboard_annual()
    last_year = datetime.now() - timedelta(days=(1 * 365))
    last_year_year = last_year.strftime("%Y")
    last_year_month = last_year.strftime("%B")
    last_year_day = last_year.strftime("%m")
    rolling_year_date = "{0} {1} of {2}".format(last_year_month,
                                                ordinal(last_year_day),
                                                last_year_year)

    now = datetime.now()
    now_year = now.strftime("%Y")
    now_month = now.strftime("%B")
    now_day = now.strftime("%m")
    now_string = "{0} {1} of {2}".format(now_month, ordinal(now_day), now_year)

    context = {
        # "restart": get_restart_notice,
        "copy_year": datetime.now().year,
        "rolling_year_date": rolling_year_date,
        "datetime_now": now_string,
        "logs": logs,
        'release': get_version_json(),
        "title": "Top Groundhog Removers",
        "blurb":
        get_page_blurb_override('groundhog_logbook/removal_scoreboard/'),
    }
    return render(
        request, "groundhog_logbook/groundhog_removal_scoreboard_annual.html",
        context)
Пример #3
0
def format_invoice_period(from_date, to_date):
    invoice_period = from_date.strftime("%B ")
    day = int(from_date.strftime("%d"))
    invoice_period += humanize.ordinal(str(day))
    invoice_period += to_date.strftime(" - %B ")
    day = int(to_date.strftime("%d"))
    invoice_period += humanize.ordinal(str(day))
    invoice_period += from_date.strftime(", %Y")
    return invoice_period
Пример #4
0
def format_invoice_period(from_date, to_date):
    invoice_period = from_date.strftime("%B ")
    day = int(from_date.strftime("%d"))
    invoice_period += humanize.ordinal(str(day))
    invoice_period += to_date.strftime(" - %B ")
    day = int(to_date.strftime("%d"))
    invoice_period += humanize.ordinal(str(day))
    invoice_period += from_date.strftime(", %Y")
    return invoice_period
Пример #5
0
def download_medal_labels(request):
    specs = labels.Specification(215.9,
                                 279.4,
                                 4,
                                 5,
                                 38.1,
                                 38.1,
                                 corner_radius=19.0,
                                 top_margin=20,
                                 bottom_margin=20)
    sheet = labels.Sheet(specs, draw_medal_label, border=False)

    medal_labels = []
    for division in models.Division.objects.all():
        # Event Awards
        for event in models.Event.objects.all():
            for place in range(division.event_award_count):
                medal_labels.append({
                    'meet':
                    division.meet.short_name,
                    'session':
                    division.session.first().name,
                    'level':
                    'Level: {}'.format(division.level.name.upper()),
                    'age_div':
                    'Div: {}'.format(division.short_name),
                    'place':
                    '{} Place'.format(ordinal(place + 1)),
                    'event':
                    event.name,
                })
        # All Around Awards, skipping 1st-3rd place
        if division.all_around_award_count > 3:
            for place in range(4, division.all_around_award_count + 1):
                medal_labels.append({
                    'meet':
                    division.meet.short_name,
                    'session':
                    division.session.first().name,
                    'level':
                    'Level: {}'.format(division.level.name.upper()),
                    'age_div':
                    'Div: {}'.format(division.short_name),
                    'place':
                    '{} Place'.format(ordinal(place)),
                    'event':
                    'All Around',
                })

    sheet.add_labels(medal_labels)

    timestamp = datetime.now().strftime('%Y-%m-%d-%H-%M')
    response = HttpResponse(content_type='applicaiton/pdf')
    response[
        'content-Disposition'] = 'attachment;filename=medal_labels_' + timestamp + '.pdf'
    sheet.save(response)
    return response
Пример #6
0
 def format_session(s):
     if s[0] >= 77:
          # year and congress number in parens
         return s[1] + " (" + ordinal(s[0]) + " Congress)"
     else:
         # date range and congress number in parens
         if s[2].year == s[3].year:
             # strftime requires year>=1900, so fool it for generating
             # month names by replacing old years with 1900
             if s[2].month == s[3].month:
                 return str(s[2].year) + " " + s[2].replace(1900).strftime("%b") + " (" + ordinal(s[0]) + " Congress)"
             else:
                 return str(s[2].year) + " " + s[2].replace(1900).strftime("%b-") + s[3].replace(1900).strftime("%b") + " (" + ordinal(s[0]) + " Congress)"
         else:
             return str(s[2].year) + "-" + str(s[3].year) + " (" + ordinal(s[0]) + " Congress)"
Пример #7
0
 def format_session(s):
     if s[0] >= 77:
          # year and congress number in parens
         return s[1] + " (" + ordinal(s[0]) + " Congress)"
     else:
         # date range and congress number in parens
         if s[2].year == s[3].year:
             # strftime requires year>=1900, so fool it for generating
             # month names by replacing old years with 1900
             if s[2].month == s[3].month:
                 return str(s[2].year) + " " + s[2].replace(1900).strftime("%b") + " (" + ordinal(s[0]) + " Congress)"
             else:
                 return str(s[2].year) + " " + s[2].replace(1900).strftime("%b-") + s[3].replace(1900).strftime("%b") + " (" + ordinal(s[0]) + " Congress)"
         else:
             return str(s[2].year) + "-" + str(s[3].year) + " (" + ordinal(s[0]) + " Congress)"
Пример #8
0
    def create_divisions(self, f, districts_per_state):
        usa, created = Division.objects.get_or_create(
            name="United States of America",
            label="United States of America",
            short_label="USA",
            level=self.country,
        )

        for state in us.states.STATES:
            f.seek(0)
            this_state, created = Division.objects.get_or_create(
                name=state.name,
                label=state.name,
                short_label=state.abbr,
                code=state.fips,
                parent=usa,
                level=self.state,
            )

            for district_state in districts_per_state:
                if district_state["state"] == state.name:
                    num_districts = int(district_state["districts"])

            if num_districts == 1:
                Division.objects.get_or_create(
                    name="{} at-large congressional district".format(
                        state.name),
                    label="{} at-large congressional district".format(
                        state.name),
                    short_label="{}-AL".format(state.abbr),
                    code="{}-AL".format(state.abbr),
                    parent=this_state,
                    level=self.district,
                )
            else:
                for x in range(1, num_districts + 1):
                    Division.objects.get_or_create(
                        name="{} {} congressional district".format(
                            state.name, ordinal(x)),
                        label="{} {} congressional district".format(
                            state.name, ordinal(x)),
                        short_label="{}-{}".format(state.abbr,
                                                   str(x).zfill(2)),
                        code="{}-{}".format(state.abbr,
                                            str(x).zfill(2)),
                        parent=this_state,
                        level=self.district,
                    )
Пример #9
0
 def validate(self, value):
     if settings.FIRST_NAME[self.letter_position].lower() != value.lower():
         raise ValidationError(
             _("{value} is not the {position} letter in my first name.").format(
                 value=value, position=ordinal(self.letter_position + 1)
             )
         )
Пример #10
0
def side_and_position_names(tournament):
    """Yields 2-tuples (side, positions), where position is a list of position
    names, all being translated human-readable names. This should eventually
    be extended to return an appropriate list for the tournament configuration.
    """
    sides = [
        get_side_name(tournament, side, 'full').title()
        for side in tournament.sides
    ]

    if tournament.pref('teams_in_debate') == 'bp' \
            and tournament.last_substantive_position == 2 \
            and tournament.reply_position is None:

        for side, positions in zip(sides, _BP_POSITION_NAMES):
            yield side, positions

    else:
        for side in sides:
            positions = [
                _("Reply")
                if pos == tournament.reply_position else ordinal(pos)
                for pos in tournament.positions
            ]
            yield side, positions
Пример #11
0
    def get_description(self):
        """A description of this role, e.g. Delegate for District of Columbia At Large."""

        from django.contrib.humanize.templatetags.humanize import ordinal

        if self.role_type == RoleType.president:
            return self.get_title_name(False)
        if self.role_type == RoleType.vicepresident:
            return self.get_title_name(False)
        if self.role_type == RoleType.senator:
            js = ""
            if self.current and self.senator_rank:
                js = self.get_senator_rank_display() + " "
            return js + self.get_title_name(False) + " from " + statenames[
                self.state]
        if self.role_type == RoleType.representative:
            if self.district == -1:
                return self.get_title_name(False) + " for " + statenames[
                    self.state]
            elif self.district == 0:
                return self.get_title_name(False) + " for " + statenames[
                    self.state] + " At Large"
            else:
                return self.get_title_name(False) + " for " + statenames[
                    self.state] + "'s " + ordinal(
                        self.district) + " congressional district"
Пример #12
0
 def done(self):
     if self.state == EntrantStates.joined.value \
             and self.race.is_in_progress \
             and self.ready \
             and not self.dnf \
             and not self.dq \
             and not self.finish_time:
         self.finish_time = timezone.now() - self.race.started_at
         self.place = len(
             self.race.entrant_set.filter(
                 dnf=False,
                 dq=False,
                 finish_time__isnull=False,
             )) + 1
         self.save()
         self.race.add_message(
             '%(user)s has ##good##finished## in %(place)s place with a time of %(time)s!'
             % {
                 'user': self.user,
                 'place': ordinal(self.place),
                 'time': self.finish_time_str
             })
         self.race.finish_if_none_remaining()
     else:
         raise SafeException('Possible sync error. Refresh to continue.')
Пример #13
0
 def __str__(self):
     return '{} {} - {} ({})'.format(
         self.date.strftime('%B'),
         ordinal(self.date.day),
         self.name,
         self.id,
     )
Пример #14
0
def muni_ward_namer(feature):
    if feature['NUMBER'].value == 0:
        muni = feature['MUNICIPALI'].value
        if muni.endswith(' Uninc'):
            muni = muni.replace(' Uninc','')
        return "Unincorporated %s" % muni
    return "%s, %s %s" % (feature['MUNICIPALI'],ordinal(str(feature['NUMBER'])),feature['TYPE'])
Пример #15
0
 def build_info():
     feeds = [f for f in Feed.get_simple_feeds() if f.category == "federal-bills"]
     
     groups = [
         (   g[0], # title
             g[1], # text 1
             g[2], # text 2
             "/congress/bills/browse?status=" + ",".join(str(s) for s in g[4]), # link
            load_bill_status_qs(g[4]).count(), # count in category
            load_bill_status_qs(g[4]).order_by('-current_status_date')[0:6], # top 6 in this category
             )
         for g in bill_status_groups ]
         
     dhg_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, docs_house_gov_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=10)).filter(docs_house_gov_postdate__gt=F('current_status_date'))
     sfs_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, senate_floor_schedule_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=5)).filter(senate_floor_schedule_postdate__gt=F('current_status_date'))
     coming_up = list(dhg_bills | sfs_bills)
     coming_up.sort(key = lambda b : b.docs_house_gov_postdate if (b.docs_house_gov_postdate and (not b.senate_floor_schedule_postdate or b.senate_floor_schedule_postdate < b.docs_house_gov_postdate)) else b.senate_floor_schedule_postdate, reverse=True)
     
     start, end = get_congress_dates(CURRENT_CONGRESS)
     end_year = end.year if end.month > 1 else end.year-1 # count January finishes as the prev year
     current_congress_years = '%d-%d' % (start.year, end.year)
     current_congress = ordinal(CURRENT_CONGRESS)
     
     return {
         "feeds": feeds,
         
         "total": Bill.objects.filter(congress=CURRENT_CONGRESS).count(),
         "current_congress_years": current_congress_years,
         "current_congress": current_congress,
         "groups": groups,
         "coming_up": coming_up,
         "subjects": subject_choices(),
         "BILL_STATUS_INTRO": (BillStatus.introduced, BillStatus.referred, BillStatus.reported),
     }
Пример #16
0
    def make_observations(self, membership):

        from signalbox.models import Observation

        times = self.datetimes(membership.date_randomised)
        times_indexes = list(zip(times, list(range(1, len(list(times)) + 1))))

        observations = []
        for time, index in times_indexes:
            observations.append(
                Observation(due_original=time,
                    n_in_sequence=index,
                    label=render_string_with_context(self.label,
                                {'i': index,
                                'n': ordinal(index),
                                 'script': self,
                                 'membership': membership
                                }),
                    dyad=membership,
                    created_by_script=self)
                )

        [i.save() for i in observations]

        return observations
Пример #17
0
    def get_district_shp(self):
        cmd_path = os.path.dirname(os.path.realpath(__file__))
        pa_path = os.path.join(cmd_path, "../../bin/pa")

        shape = shapefile.Reader(
            os.path.join(pa_path, "{}.shp".format(SHP_SLUG))
        )
        fields = shape.fields[1:]
        field_names = [f[0] for f in fields]
        district_records = [shp for shp in shape.shapeRecords()]
        features = []
        for shp in district_records:
            rec = dict(zip(field_names, shp.record))
            label = "{} congressional district".format(
                ordinal(int(rec["DISTRICT"]))
            )

            geometry = shp.shape.__geo_interface__
            geodata = {
                "type": "Feature",
                "geometry": geometry,
                "properties": {
                    "state": 42,
                    "district": rec["DISTRICT"],
                    "name": label,
                },
            }
            features.append(geodata)
        return self.toposimplify(geojson.FeatureCollection(features), "0.03")
Пример #18
0
    def build_info():
        feeds = [f for f in Feed.get_simple_feeds() if f.category == "federal-bills"]

        groups = [
            (   g[0], # title
                g[1], # text 1
                g[2], # text 2
                "/congress/bills/browse?status=" + ",".join(str(s) for s in g[4]), # link
               load_bill_status_qs(g[4]).count(), # count in category
               load_bill_status_qs(g[4]).order_by('-current_status_date')[0:6], # top 6 in this category
                )
            for g in bill_status_groups ]

        dhg_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, docs_house_gov_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=10)).filter(docs_house_gov_postdate__gt=F('current_status_date'))
        sfs_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, senate_floor_schedule_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=5)).filter(senate_floor_schedule_postdate__gt=F('current_status_date'))
        coming_up = list(dhg_bills | sfs_bills)
        coming_up.sort(key = lambda b : b.docs_house_gov_postdate if (b.docs_house_gov_postdate and (not b.senate_floor_schedule_postdate or b.senate_floor_schedule_postdate < b.docs_house_gov_postdate)) else b.senate_floor_schedule_postdate, reverse=True)

        start, end = get_congress_dates(CURRENT_CONGRESS)
        end_year = end.year if end.month > 1 else end.year-1 # count January finishes as the prev year
        current_congress_years = '%d-%d' % (start.year, end.year)
        current_congress = ordinal(CURRENT_CONGRESS)

        return {
            "feeds": feeds,

            "total": Bill.objects.filter(congress=CURRENT_CONGRESS).count(),
            "current_congress_years": current_congress_years,
            "current_congress": current_congress,
            "groups": groups,
            "coming_up": coming_up,
            "subjects": subject_choices(),
            "BILL_STATUS_INTRO": (BillStatus.introduced, BillStatus.referred, BillStatus.reported),
        }
Пример #19
0
def homepage_summary(request):
	# parse & validate parameters
	try:
		state = request.GET["district"][0:2]
		district = int(request.GET["district"][2:])
		if state not in statenames: raise Exception()
	except:
		return None

	from django.contrib.humanize.templatetags.humanize import ordinal

	# view
	people = Person.from_state_and_district(state, district)
	feeds = [p.get_feed() for p in people]
	events = Feed.get_events_for(feeds, 6)

	from events.templatetags.events_utils import render_event
	for i in range(len(events)):
		events[i] = render_event(events[i], feeds)
		if not isinstance(events[i]["date"], str):
			events[i]["date"] = events[i]["date"].strftime('%B %d, %Y') # can't JSON-serialize a datetime anyway, TODO handle date_has_no_time
		for k in list(events[i]): # remove anything else in case it is not JSON-serializable
			if k not in ('type', 'date', 'title', 'body_html', 'url'):
				del events[i][k]

	# form output
	return {
		"state": state,
		"district": district,
		"state_name": statenames[state],
		"district_ordinal": ordinal(district),
		"reps": [ { "link": p.get_absolute_url(), "name": p.name_and_title(), "title": p.role.get_description(), "photo": p.get_photo_url() } for p in people],
		"events": events,
	}
Пример #20
0
    def get_description(self):
        """A description of this role, e.g. Delegate for District of Columbia At Large."""

        from django.contrib.humanize.templatetags.humanize import ordinal

        if self.role_type in (RoleType.president, RoleType.vicepresident):
            return self.get_title_name(False)
        if self.role_type == RoleType.senator:
            js = ""
            if self.current and self.senator_rank:
                js = self.get_senator_rank_display() + " "
            return js + self.get_title_name(False) + " for " + statenames[
                self.state]
        if self.role_type == RoleType.representative:
            if self.district == -1 or stateapportionment.get(self.state) in (
                    "T", None
            ):  # unknown district / current territories and former state-things, all of which send/sent delegates
                return self.get_title_name(
                    False) + " for " + self.state_name_article()
            elif self.district == 0:
                return self.get_title_name(False) + " for " + statenames[
                    self.state] + " At Large"
            else:
                return self.get_title_name(False) + " for " + statenames[
                    self.state] + "'s " + ordinal(
                        self.district) + " congressional district"
Пример #21
0
    def make_observations(self, membership):

        from signalbox.models import Observation

        times = self.datetimes(membership.date_randomised)
        times_indexes = list(zip(times, list(range(1, len(list(times)) + 1))))

        observations = []
        for time, index in times_indexes:
            observations.append(
                Observation(due_original=time,
                            n_in_sequence=index,
                            label=render_string_with_context(
                                self.label, {
                                    'i': index,
                                    'n': ordinal(index),
                                    'script': self,
                                    'membership': membership
                                }),
                            dyad=membership,
                            created_by_script=self))

        [i.save() for i in observations]

        return observations
Пример #22
0
def get_bill_number(bill, show_congress_number="ARCHIVAL"):
    "Compute display form of bill number"

    from bill.models import BillType
    ret = '%s %s' % (BillType.by_value(bill.bill_type).label, bill.number)
    if (bill.congress != settings.CURRENT_CONGRESS and show_congress_number == "ARCHIVAL") or show_congress_number == "ALL":
        ret += ' (%s)' % ordinal(bill.congress)
    return ret
Пример #23
0
def district_name(district):
    if district['seat'] == 'federal:senate':
        return 'Senate'
    elif district['seat'] == 'federal:house' and district['district']:
        d = district['district'].split('-')
        num = ordinal(int(d[1]))
        return 'House %s District' % num
    return ''
Пример #24
0
 def __init__(self, letter_position, *args, **kwargs):
     super(LetterField, self).__init__(choices=LetterField.ALPHABET,
                                       label=_("%s letter ") %
                                       ordinal(letter_position + 1),
                                       initial='--',
                                       *args,
                                       **kwargs)
     self.letter_position = letter_position
Пример #25
0
 def render_group(self, record):
     return mark_safe(
         '<span class="tooltips" title="%(result_group)s in the group (%(points_group)s points)">%(group)s</span>'
         % {
             'group': record.participant.group,
             'result_group': ordinal(record.result_group),
             'points_group': record.points_group
         })
Пример #26
0
 def __init__(self, letter_position, *args, **kwargs):
     super(LetterField, self).__init__(
         choices=LetterField.ALPHABET,
         label=_("%s letter ") % ordinal(letter_position + 1),
         initial="--",
         *args,
         **kwargs
     )
     self.letter_position = letter_position
Пример #27
0
def person_search_manager():
    sm = SearchManager(Person, connection="person")

    sm.add_filter("was_moc__in", [True])  # exclude presidents/vice presidents

    sm.add_option('text', label='name', type="text")
    sm.add_option('is_currently_moc',
                  label="currently serving?",
                  type="radio",
                  choices=[(False, "No"), (True, "Yes")])
    sm.add_option('most_recent_role_type',
                  label="senator or representative",
                  type="radio",
                  formatter=lambda v: v.capitalize())
    sm.add_option('most_recent_role_state',
                  label="state",
                  type="select",
                  formatter=lambda state: statenames[state.upper()],
                  sort="LABEL")
    sm.add_option('most_recent_role_district',
                  label="district",
                  type="select",
                  formatter=lambda v: "At Large" if v == 0 else ordinal(v),
                  visible_if=lambda form: "most_recent_role_state" in form,
                  sort="KEY")
    sm.add_option('most_recent_role_party',
                  label="party",
                  type="select",
                  formatter=lambda v: v.capitalize())
    sm.add_option('gender')
    sm.add_sort("Last Name", "lastname", default=True)

    # sm.add_option('name', label='last name', type="text", filter=name_filter, choices="NONE")
    # sm.add_option('roles__current', label="currently serving?", type="radio", filter=current_filter)
    # sm.add_option('roles__year', label="year served", type="select", visible_if=lambda form : form.get("roles__current", "__ALL__") == "false", filter=year_filter, choices=years)
    # sm.add_option('roles__role_type', label="chamber")
    # sm.add_option('roles__state', label='state', sort=False, type="select")
    # sm.add_option('roles__district', label='district', sort=False, choices=[('0', 'At Large')] + [(x, str(x)) for x in xrange(1, 53+1)], type="select", visible_if=lambda form : form.get("roles__state", "__ALL__") != "__ALL__" and unicode(RoleType.representative) in form.getlist("roles__role_type[]"))
    # sm.add_option('roles__party', label='party', type="select")
    # sm.add_option('gender')
    # sm.add_option('sort', label='sort by', choices=[('name', 'name'), ('district', 'state/district, then year')], filter=sort_filter, type="radio", required=True)

    sm.set_template("""
    	<div style="float: left; margin-right: 1.5em">
			{% if object.has_photo %}
				<img src="{{object.get_photo_url_50}}" width="50" height="60"/>
			{% else %}
				<div style="border: 1px solid black; width: 50px; height: 60px;"/>
			{% endif %}
		</div>
    	<a href="{{object.get_absolute_url}}" style="margin-top: 4px">{{object.name_no_details_lastfirst}}</a>
    	<div>{{description}}</div>
	""")
    sm.set_template_context_func(template_get_context)

    return sm
Пример #28
0
    def edition_or_component(self):
        issue = ''

        if self.edition != 1:
            issue = '{} edition'.format(ordinal(self.edition))

        if self.component:
            issue = '{}, {}'.format(issue, self.component)

        return issue
Пример #29
0
 def test_str_book_section(self, book_section):
     # book section with authors, title, book title, edition, year, volume no.
     assert str(book_section) == '%s, "%s," in %s, %s ed. (%s), vol. %s.' % (
         book_section.authors.first().firstname_lastname(),
         book_section.title,
         book_section.journal,
         ordinal(book_section.edition),
         book_section.year,
         book_section.volume,
     )
Пример #30
0
 def get_display(self):
     if self.repeat_period == self.REPEAT_NEVER:
         return _("in %(timeperiod)s") % {"timeperiod": timeuntil(self.next_fire)} if self.next_fire else ""
     elif self.repeat_period == self.REPEAT_DAILY:
         time_of_day = time(self.repeat_hour_of_day, self.repeat_minute_of_hour, 0).strftime("%H:%M")
         return _("each day at %(time)s") % {"time": time_of_day}
     elif self.repeat_period == self.REPEAT_WEEKLY:
         days = [str(day) for day in self.get_repeat_days_display()]
         return _("each week on %(daysofweek)s" % {"daysofweek": ", ".join(days)})
     elif self.repeat_period == self.REPEAT_MONTHLY:
         return _("each month on the %(dayofmonth)s" % {"dayofmonth": ordinal(self.repeat_day_of_month)})
Пример #31
0
def build_title(p, t):
	if t['type'] == "sen":
		return t['state_rank'][0].upper() + t['state_rank'][1:] + " Senator from " + statenames[t['state']]
	elif t['state'] == "PR":
		return "Resident Commissioner for Puerto Rico"
	elif t['state'] in ('AS', 'DC', 'GU', 'MP', 'VI'):
		return "Delegate from " + statenames[t['state']]
	elif t['district'] == 0:
		return "Representative for " + statenames[t['state']] + " At-Large"
	else:
		return "Representative for " + statenames[t['state']] + "’s " + ordinal(t['district']) + " Congressional District"
Пример #32
0
 def get_context_data(self, **kwargs):
     kwargs['ballots'] = json.dumps(self.get_ballots_dicts())
     kwargs['ordinals'] = [ordinal(i) for i in range(1, 5)]
     motions = self.round.motion_set.order_by('seq')
     kwargs['motions'] = json.dumps([{
         'seq': m.seq,
         'text': m.text
     } for m in motions])
     kwargs['use_team_code_names'] = use_team_code_names(
         self.tournament, False)
     return super().get_context_data(**kwargs)
Пример #33
0
def index_in_pi(number):
    global pi
    if pi is None:
        print(u'reading digits of \u03C0...', end='')
        with open('data/pi.txt') as f:
            pi = f.read()
        print(u'\u03C0 read')

    number = str(number)
    index = pi.index(number) + 1
    return ordinal(index)
Пример #34
0
 def _friendly_daily_date(self, relative_to):
     delta_days = (relative_to - self.date).days
     if delta_days == 0:
         return _("Today")
     elif delta_days == 1:
         return _("Yesterday")
     elif delta_days < 7:
         # Full day name
         return self.date.strftime("%A")
     else:
         # "March 1st"
         return "%s %s" % (self.date.strftime("%B"), ordinal(self.date.day))
Пример #35
0
def get_bill_number(bill, show_congress_number="ARCHIVAL"):
    "Compute display form of bill number"
    
    if bill.congress <= 42:
        # This is an American Memory bill. It's number is stored.
        ret = bill.title.split(":")[0]
    else:
        from bill.models import BillType
        ret = '%s %s' % (BillType.by_value(bill.bill_type).label, bill.number)
    if (bill.congress != settings.CURRENT_CONGRESS and show_congress_number == "ARCHIVAL") or show_congress_number == "ALL":
        ret += ' (%s)' % ordinal(bill.congress)
    return ret
Пример #36
0
    def __str__(self):
        issue = '{}: {}'.format(
            self.publication,
            self.issue_date.strftime(self.publication.date_format))

        if self.edition != 1:
            issue = '{}, {} edition'.format(issue, ordinal(self.edition))

        if self.component:
            issue = '{}, {}'.format(issue, self.component)

        return issue
Пример #37
0
    def _result_cell_bp(self, ts, compress=False, show_score=False, show_ballots=False):
        if not hasattr(ts, 'debate_team'):
            return {'text': self.BLANK_TEXT}

        other_teams = {dt.side: self._team_short_name(dt.team) for dt in ts.debate_team.debate.debateteam_set.all()}
        other_team_strs = [_("Teams in debate:")]
        for side in self.tournament.sides:
            if ts.debate_team.debate.sides_confirmed:
                line = _("%(team)s (%(side)s)") % {
                    'team': other_teams.get(side, _("??")),
                    'side': get_side_name(self.tournament, side, 'abbr'),
                }
            else:
                line = other_teams.get(side, _("??"))
            if side == ts.debate_team.side:
                line = "<strong>" + line + "</strong>"
            other_team_strs.append(line)

        cell = {'popover': {
            'content': [{'text': "<br />".join(other_team_strs)}],
            'title': "",
            'class': "no-wrap",
        }}

        if ts.debate_team.debate.round.is_break_round:
            cell = self._result_cell_class_four_elim(ts.win, cell)
            if ts.win is True:
                cell['text'] = _("advancing")
                cell['popover']['title'] = _("Advancing")
            elif ts.win is False:
                cell['text'] = _("eliminated")
                cell['popover']['title'] = _("Eliminated")
            else:
                cell['text'] = "–"
                cell['popover']['title'] = _("No result for debate")
        else:
            cell = self._result_cell_class_four(ts.points, cell)
            places = [ordinal(n) for n in reversed(range(1, 5))]
            if ts.points is not None:
                place = places[ts.points] if ts.points < 4 else _("??")
                cell['text'] = place
                cell['popover']['title'] = _("Placed %(place)s") % {'place': place}
            else:
                cell['text'] = "–"
                cell['popover']['title'] = _("No result for debate")

        if show_score and ts.score is not None:
            self._show_score(ts, cell)

        if show_ballots:
            self._show_ballots(cell, ts, "results-ballotset-edit")

        return cell
Пример #38
0
def get_year(raw_year):
    if raw_year == "":
        return "Unknown"
    parts = list(map(lambda x: int(x), raw_year.split("-")))
    if parts[1] == 0:
        return "{}".format(parts[0])
    if len(parts) < 3 or parts[2] == 0:
        dt = datetime(parts[0], parts[1], 1, 0, 0)
        return dt.strftime('%B %Y')
    else:
        dt = datetime(parts[0], parts[1], 1, 0, 0)
        return "{} {}".format(ordinal(parts[2]), dt.strftime('%B %Y'))
Пример #39
0
 def _friendly_daily_date(self, relative_to):
     delta_days = (relative_to - self.date).days
     if delta_days == 0:
         return _("Today")
     elif delta_days == 1:
         return _("Yesterday")
     elif delta_days < 7:
         # Full day name
         return self.date.strftime("%A")
     else:
         # "March 1st"
         return "%s %s" % (self.date.strftime("%B"), ordinal(self.date.day))
def index(request):
    contract_month_start_day = getattr(settings, 'SLA_METRICS_CONTRACT_START_DAY', 1)
    stats = Report.get_stats(contract_month_start_day)

    return render(request, 'index.html', {
        'last_synced_at': naturaltime(SingletonMetadata.load().last_synced_at),
        'stats': stats,
        'totals': stats.pop('totals'),
        'bookmarklet_url': get_bookmarklet_url(request),
        'contract_month_start_day': contract_month_start_day,
        'contract_month_start_day_ordinal': ordinal(contract_month_start_day),
    })
Пример #41
0
    def build_info():
        # feeds about all legislation that we offer the user to subscribe to
        feeds = [f for f in Feed.get_simple_feeds() if f.category == "federal-bills"]

        # info about bills by status
        groups = [
            (   g[0], # title
                g[1], # text 1
                g[2], # text 2
                "/congress/bills/browse?status=" + ",".join(str(s) for s in g[4]) + "&sort=-current_status_date", # link
               load_bill_status_qs(g[4]).count(), # count in category
               load_bill_status_qs(g[4]).order_by('-current_status_date')[0:6], # top 6 in this category
                )
            for g in bill_status_groups ]

        # legislation coming up
        dhg_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, docs_house_gov_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=10)).filter(docs_house_gov_postdate__gt=F('current_status_date'))
        sfs_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, senate_floor_schedule_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=5)).filter(senate_floor_schedule_postdate__gt=F('current_status_date'))
        coming_up = list(dhg_bills | sfs_bills)
        coming_up.sort(key = lambda b : b.docs_house_gov_postdate if (b.docs_house_gov_postdate and (not b.senate_floor_schedule_postdate or b.senate_floor_schedule_postdate < b.docs_house_gov_postdate)) else b.senate_floor_schedule_postdate, reverse=True)

        # top tracked bills
        top_bills = Feed.objects\
            .filter(feedname__startswith='bill:')\
            .filter(feedname__regex='^bill:[hs][jcr]?%d-' % CURRENT_CONGRESS)
        top_bills = top_bills\
            .annotate(count=Count('tracked_in_lists'))\
            .order_by('-count')\
            .values('feedname', 'count')\
            [0:25]
        top_bills = [(Bill.from_feed(Feed.from_name(bf["feedname"])), bf["count"]) for bf in top_bills]

        # current congrss years
        start, end = get_congress_dates(CURRENT_CONGRESS)
        end_year = end.year if end.month > 1 else end.year-1 # count January finishes as the prev year
        current_congress_years = '%d-%d' % (start.year, end.year)
        current_congress = ordinal(CURRENT_CONGRESS)

        return {
            "feeds": feeds,

            "total": Bill.objects.filter(congress=CURRENT_CONGRESS).count(),
            "current_congress_years": current_congress_years,
            "current_congress": current_congress,

            "groups": groups,
            "coming_up": coming_up,
            "top_tracked_bills": top_bills,

            "subjects": subject_choices(),
            "BILL_STATUS_INTRO": (BillStatus.introduced, BillStatus.referred, BillStatus.reported),
        }
def extras():
    """
    Load some of the extra data we want for our model that's not included
    in the source shapefile. 
        
        * The Django state field
        * The slug field
        * The ForeignKey connection to a State model.
        * Simplified versions of our polygons that contain few points
        
    Example usage:
    
        >> from congressional_districts import load; load.extras();
        
    """
    from django.template.defaultfilters import slugify
    from django.contrib.humanize.templatetags.humanize import ordinal
    from models import District
    # Pull a crosswalk between FIPS and state abbreviations
    adict = abbrevs()
    # Loop through everybody...
    for obj in queryset_iterator(District.objects.all()):
        # ...set the state...
        obj.state = adict[obj.state_fips_code]
        # ...slug...
        obj.slug = u'%s-%s' % (slugify(obj.state), slugify(obj.district_number))
        # ... name with ordinal ...
        if obj.district_number == "00": # special-case at-large districts
            obj.at_large = True
            obj.ordinal_name = ordinal(1)
        else:
            obj.ordinal_name = ordinal(obj.district_number)
        # .. the full set of polygons...
        obj.set_polygons()
        obj.set_simple_polygons()
        # ... the square miles ...
        obj.square_miles = obj.get_square_miles()
        # ... save the changes ...
        obj.save()
Пример #43
0
def near_future_date(date):
    """
    Returns just the name of the day if it's in the next few days; if it's
    in the next month, a string like "Tuesday the 5th"; otherwise, a string
    like "May 12".
    """
    distance = (date - date.today()).days
    if 0 <= distance < 6:
        return date.strftime("%A")
    elif 0 < distance < 20:
        return date.strftime("%A the ") + ordinal(date.day)
    else:
        return date.strftime("%B ") + str(date.day)
def ordinalize_name(contest):
    if "sos-districtwide-us-house-of-representatives" in contest.contestid:
        str_to_remove = "US House of Representatives District"
        suffix = "Congressional District"
        value = contest.contestname.lower()
        district_number = value.replace(str_to_remove.lower(), "")
        output = "California's %s %s" % (ordinal(district_number), suffix)
    elif "sos-districtwide-state-senate" in contest.contestid:
        str_to_remove = "State Senate District"
        suffix = "State Senate District"
        value = contest.contestname.lower()
        district_number = value.replace(str_to_remove.lower(), "")
        output = "California's %s %s" % (ordinal(district_number), suffix)
    elif "sos-districtwide-state-assembly" in contest.contestid:
        str_to_remove = "State Assembly District"
        suffix = "State Assembly District"
        value = contest.contestname.lower()
        district_number = value.replace(str_to_remove.lower(), "")
        output = "California's %s %s" % (ordinal(district_number), suffix)
    else:
        output = contest.contestname
    return output
Пример #45
0
 def stress(self, obj):
     stress_word = obj.ipa_transcription or obj.rfe_transcription
     if stress_word:
         stress_char = u"ˈ"
         if stress_char in stress_word:
             stress_word = stress_word[:stress_word.index(stress_char)]
             stress_count = self.get_chars_count(stress_word, u".") + 1
             stress_position = mark_safe(humanize.ordinal(stress_count))
         else:
             stress_position = None
     else:
         stress_position = None
     return stress_position
Пример #46
0
    def initial(self, request, *args, **kwargs):
        super(LoggingMixin, self).initial(request, *args, **kwargs)

        d = date.today().isoformat()
        user = request.user
        endpoint = request.resolver_match.url_name

        r = redis.StrictRedis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            db=settings.REDIS_DATABASES['STATS'],
        )
        pipe = r.pipeline()

        # Global and daily tallies for all URLs.
        pipe.incr('api:v3.count')
        pipe.incr('api:v3.d:%s.count' % d)

        # Use a sorted set to store the user stats, with the score representing
        # the number of queries the user made total or on a given day.
        pipe.zincrby('api:v3.user.counts', user.pk)
        pipe.zincrby('api:v3.user.d:%s.counts' % d, user.pk)

        # Use a sorted set to store all the endpoints with score representing
        # the number of queries the endpoint received total or on a given day.
        pipe.zincrby('api:v3.endpoint.counts', endpoint)
        pipe.zincrby('api:v3.endpoint.d:%s.counts' % d, endpoint)

        results = pipe.execute()
        total_count = results[0]
        user_count = results[2]

        if total_count in MILESTONES_FLAT:
            Event.objects.create(description="API has logged %s total requests."
                                             % total_count)
        if user.is_authenticated():
            if user_count in self.milestones:
                Event.objects.create(
                    description="User '%s' has placed their %s API request." %
                                (user.username, intcomma(ordinal(user_count))),
                    user=user,
                )
            if user_count == 5:
                email = emails['new_api_user']
                send_mail(
                    email['subject'],
                    email['body'] % user.first_name or 'there',
                    email['from'],
                    [user.email],
                )
Пример #47
0
    def __init__(self, *args, **kwargs):
        self.profile = kwargs.pop('profile')
        self.instance = kwargs.pop('instance')
        self.content = kwargs.pop('content')
        super().__init__(*args, **kwargs)
        total = self.content.total()
        min_size = max(total['min_group_size'], 2)
        max_size = total['max_group_size']

        for n in range(2, max_size + 1):
            widget = forms.TextInput(attrs={'class':'form-control'})
            field = forms.CharField(widget=widget, required=(n <= min_size))
            field.label = mark_safe(_('{num} member').format(num=ordinal(n)))
            self.fields['member{:d}'.format(n)] = field
Пример #48
0
    def _description_builder(self):
        if self.repeat_type != ScheduleRepeatType.NONE:
            yield 'every'
            if self.repeat_every > 1:
                yield apnumber(self.repeat_every)
            yield pluralize(self.repeat_every, ScheduleRepeatType.pluralized_instances_dict[self.repeat_type])
            if self.repeat_type == ScheduleRepeatType.WEEKLY and \
                    any(getattr(self, weekday_entry[0]) for weekday_entry in WeekDay.choices):
                yield 'on'
                yield self.humanized_weekdays
            elif self.repeat_type == ScheduleRepeatType.MONTHLY and self.monthly_is_based_on_weekday:
                week_position = (datetime.date(self.start_date.year, self.start_date.month, 1).weekday() + self.start_date.day) / 7
                is_last_weekday = (self.start_date + datetime.timedelta(weeks=1)).month != self.start_date.month
                if is_last_weekday:
                    yield 'on the last %s' % WeekDay.choices[self.start_date.weekday()][1]
                else:
                    yield 'on the %s %s' % (ordinal(week_position + 1), WeekDay.choices[self.start_date.weekday()][1])
            elif self.repeat_type == ScheduleRepeatType.MONTHLY and not self.monthly_is_based_on_weekday:
                yield 'on the'
                yield ordinal(self.start_date.day)
            yield 'from'
            yield formats.date_format(self.start_date, 'SHORT_DATE_FORMAT')

            if self.end_date is not None:
                yield 'until'
                yield formats.date_format(self.end_date, 'SHORT_DATE_FORMAT')

            if self.end_after_occurrences > 0:
                if self.end_date:
                    yield 'or'
                yield 'until'
                yield six.text_type(self.end_after_occurrences)
                yield pluralize(self.end_after_occurrences, 'occurence,occurences')
                yield 'took place'
        else:
            yield 'on'
            yield formats.date_format(self.start_date, 'SHORT_DATE_FORMAT')
Пример #49
0
def import_city_council(filename):
    ds = DataSource(filename)
    lyr = ds[0]
    layer, _ = Layer.objects.get_or_create(
        name='Baltimore City Council'
    )
    for feature in lyr:
        name = feature.get('AREA_NAME')
        district, created = District.objects.get_or_create(
            layer = layer,
            name = name,
            pretty_name = '%s District' % ordinal(name),
            geom = feature.geom.geos
        )
        if created:
            print 'created', district
Пример #50
0
    def handle(self, *args, **options):
        today = datetime.date.today()

        try:
            twilio = TwilioAPI()
        except Exception as e:
            raise CommandError(e)

        for person in Person.objects.all():
            if (person.next_birthday - today).days != options['days']:
                continue

            args = (
                person.name,
                options['days'],
                person.birth_date.strftime('{} %B').format(ordinal(person.birth_date.day)),
            )
            twilio.send("{}'s birthday is in {} days ({}).".format(*args))
Пример #51
0
    def build_citation(self):
        """
        Formats a specific citation based on the type of reference
        """
        citation = u"{0} ({1}) <i>{2}</i>".format(
            escape(self.author), escape(self.year), escape(self.title))

        if self.edition and self.edition > 1:
            citation += u" " + ordinal(self.edition) + u" ed"

        if self.publisher:
            citation += u". {0}{1}".format(
                escape(self.publisher), ": " + escape(self.place) if self.place else "")

        if self.url:
            citation += u" [Online]. Available from  <a href='{0}'>{0}</a>".format(
                escape(self.url))

        citation += "."
        return citation.encode('utf-8')
Пример #52
0
def getFaves(user):
    faves = []
    for fave in user.faves.all().order_by('name'):
        floor = humanize.ordinal(fave.floor) + " floor" if fave.floor>0 else "Basement"
        fobj = {"id":fave.id, "name":fave.name, "email":fave.email}
        if fave.age and fave.enabled and datetime.today()-fave.age < timedelta(hours=6) and (fave.sharing == 0 or (fave.sharing == 1 and user in fave.shares.all())):
            if fave.building.id == 160: # Remove this hardcoded check once locations for buses are implemented
                loc = str(fave.building)
            else:
                loc = str(fave.location) if fave.location else str(fave.building) + " - " + floor
            fobj["location"] = loc
            fobj["bldgid"] = fave.building.id
            fobj["bldgnum"] = fave.building.number
            fobj["bldg"] = str(fave.building)
            fobj["age"] = humanize.naturaltime(fave.age)
            #fobj["age"] = humanize.naturaltime(fave.age) if datetime.today()-fave.age > timedelta(seconds=15) else "Now"
        else:
            fobj["location"] = "Location not available"
        faves.append(fobj)
    return faves
Пример #53
0
    def _handle_events(self, results, user):
        total_count = results[0]
        user_count = results[4]

        if total_count in MILESTONES_FLAT:
            Event.objects.create(description="API has logged %s total requests."
                                             % total_count)
        if user.is_authenticated:
            if user_count in self.milestones:
                Event.objects.create(
                    description="User '%s' has placed their %s API request." %
                                (user.username, intcomma(ordinal(user_count))),
                    user=user,
                )
            if user_count == SEND_API_WELCOME_EMAIL_COUNT:
                email = emails['new_api_user']
                send_mail(
                    email['subject'],
                    email['body'] % user.first_name or 'there',
                    email['from'],
                    [user.email],
                )
Пример #54
0
def grade_to_name(grade):
    try:
        return ['freshman', 'sophomore', 'junior', 'senior'][grade - 9]
    except IndexError:
        return ordinal(grade) + " Grade"
Пример #55
0
 def get_description(self):
     """A description of this role, e.g. Delegate for District of Columbia At Large."""
     
     from django.contrib.humanize.templatetags.humanize import ordinal
     
     if self.role_type == RoleType.president:
         return self.get_title_name(False)
     if self.role_type == RoleType.vicepresident:
         return self.get_title_name(False)
     if self.role_type == RoleType.senator:
         return self.get_title_name(False) + " from " + statenames[self.state]
     if self.role_type == RoleType.representative:
         if self.district == -1:
             return self.get_title_name(False) + " for " + statenames[self.state]
         elif self.district == 0:
             return self.get_title_name(False) + " for " + statenames[self.state] + " At Large"
         else:
             return self.get_title_name(False) + " for " + statenames[self.state] + "'s " + ordinal(self.district) + " congressional district"
Пример #56
0
 def get_number_display(self):
     if self.number == 0:
         return u'basement'
     else:
         return ordinal(self.number) + u' floor'
Пример #57
0
 def __unicode__(self):
     return '%s - %s' % (ordinal(self.position), self.boat.name)