def test_searchmanager(self):
     sm = SearchManager(Thing)
     sm.add_option('color')
     form = sm.form()
     self.assertTrue(
         isinstance(form.fields['color'], SmartChoiceField))
     for key, value in form.fields['color'].choices[1:]:
         value.endswith('(%d)' % COLOR_COUNTS[key])
     req = RequestMockup()
     req.GET = {'color': [str(RED)]}
     form = sm.form(req)
     qs = form.queryset()
     self.assertEqual(len(qs), COLOR_COUNTS[RED])
Exemplo n.º 2
0
def vote_search_manager():
    sm = SearchManager(Vote, qs=Vote.objects.order_by('-created'))

    # show sessions as year+session for non-year-based sessions,
    # and then just the session number (the year) for year-based
    # sessions.
    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)"

    session_choices = reversed([(i, format_session(cs))
                                for (i, cs) in enumerate(get_all_sessions())
                                if cs[2] <= datetime.now().date()])

    sm.add_option(
        'session',
        type="select",
        choices=session_choices,
        filter=session_filter,
        help="Note: Even-year sessions extend a few days into the next year.")
    sm.add_option('chamber')
    sm.add_option('category')

    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")

    sm.set_template("""
    	<div><a href="{{object.get_absolute_url}}">{{object.question|truncatewords_html:50}}</a></div>
		{% if object.question_details %}<div>{{object.question_details}}</div>{% endif %}
		<div>{{object.name}}</div>
		<div>{{object.created|date}} {{object.created|time|cut:"midnight"}}</div>
    	<div>{{object.summary}}</div>
	""")

    return sm
def vote_search_manager():
    sm = SearchManager(Vote, qs=Vote.objects.order_by('-created'))
    
    # show sessions as year+session for non-year-based sessions,
    # and then just the session number (the year) for year-based
    # sessions.
    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)"
    	
    session_choices = reversed([(i, format_session(cs)) for (i,cs) in enumerate(get_all_sessions()) if cs[2] <= datetime.now().date()])
    
    sm.add_option('session', type="select", choices=session_choices, filter=session_filter, help="Note: Even-year sessions extend a few days into the next year.")
    sm.add_option('chamber')
    sm.add_option('category')
    
    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")

    sm.set_template("""
    	<div><a href="{{object.get_absolute_url}}">{{object.question|truncatewords_html:50}}</a></div>
		{% if object.question_details %}<div>{{object.question_details}}</div>{% endif %}
		<div>{{object.name}}</div>
		<div>{{object.created|date}} {{object.created|time|cut:"midnight"}}</div>
    	<div>{{object.summary}}</div>
	""")

    return sm
Exemplo n.º 4
0
 def test_searchmanager(self):
     sm = SearchManager(Thing)
     sm.add_option('color')
     form = sm.form()
     self.assertTrue(isinstance(form.fields['color'], SmartChoiceField))
     for key, value in form.fields['color'].choices[1:]:
         value.endswith('(%d)' % COLOR_COUNTS[key])
     req = RequestMockup()
     req.GET = {'color': [str(RED)]}
     form = sm.form(req)
     qs = form.queryset()
     self.assertEqual(len(qs), COLOR_COUNTS[RED])
Exemplo n.º 5
0
def vote_search_manager():
    sm = SearchManager(Vote, qs=Vote.objects.select_related('oursummary', 'related_bill__oursummary'))
    
    # show sessions as year+session for non-year-based sessions,
    # and then just the session number (the year) for year-based
    # sessions.
    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)"
        
    session_choices = reversed([(i, format_session(cs)) for (i,cs) in enumerate(get_all_sessions()) if cs[2] <= datetime.now().date()])
    
    sm.add_option('session', type="select", choices=session_choices, filter=session_filter, help="Note: Even-year sessions extend a few days into the next year.")
    sm.add_option('chamber')
    sm.add_option('category')
    sm.add_option('passed')
    sm.add_sort('Date (Latest First)','-created', default=True)
    sm.add_sort('Most Supported','-percent_plus', func=lambda qs : qs.order_by('-percent_plus', '-total_plus').exclude(percent_plus=None))
    sm.add_sort('Most Opposed','percent_plus', func=lambda qs : qs.order_by('percent_plus', '-total_minus').exclude(percent_plus=None))
    sm.add_sort('Widest Margin','-margin', func=lambda qs : qs.order_by('-margin', '-total_plus').exclude(margin=None))
    sm.add_sort('Narrowest Margin','margin', func=lambda qs : qs.order_by('margin', 'total_plus').exclude(margin=None))
    sm.add_sort('Most Supported by Majority Party','-mp', func=lambda qs : qs.order_by('-majority_party_percent_plus', '-total_plus').exclude(majority_party_percent_plus=None))
    sm.add_sort('Most Opposed by Majority Party','mp', func=lambda qs : qs.order_by('majority_party_percent_plus', 'total_plus').exclude(majority_party_percent_plus=None))
    
    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")

    sm.set_template("""
    <div class="row">
        <div class="col-xs-2 col-md-1" style="padding-right: 0">
            <img src="{{object.get_absolute_url}}/thumbnail" class="img-responsive"/>
        </div>
        <div class="col-xs-10 col-md-11">

    <div class="row">
        <div class="col-xs-12">
            <div style="margin-bottom: .2em"><a href="{{object.get_absolute_url}}">{{object.question|truncatewords_html:50}}</a></div>
        </div>
        <div style="font-size: 93%">
        <div class="col-xs-12 col-sm-6 col-md-4">
            <div><span class="fa fa-barcode fa-fw" aria-hidden="true" style="margin-left: 4px; color: #888"></span> {{object.name}}</div>
            <div><span class="fa fa-calendar fa-fw" aria-hidden="true" style="margin-left: 4px; color: #888"></span> {{object.created|date}} {{object.created|time|cut:"midnight"}}</div>
        </div>
        <div class="col-xs-12 col-sm-6 col-md-8">
            <div><span class="fa fa-info fa-fw" aria-hidden="true" style="color: #888"></span> {{object.summary}}</div>
        </div>
        <div class="col-xs-12">
          <div style="margin-left: 5px">
            {% if object.question_details and not object.oursummary %}<div style="margin-top: .25em">{{object.question_details}}</div>{% endif %}
            {% if object.get_summary %}<div style="margin-top: .25em; font-style: italic; line-height: 126%;">{{object.get_summary.plain_text|truncatewords:50}}</div>{% endif %}
          </div>
        </div>
        </div>
    </div>

    </div>
    </div>
    """)

    return sm
Exemplo n.º 6
0
def person_search_manager(mode):
    sm = SearchManager(Person, connection="person")

    sm.add_option('text', label='name', type="text")

    if mode == "current":
        sm.add_filter('current_role_type__in',
                      [RoleType.representative, RoleType.senator])
        sm.add_option('current_role_type',
                      label="serving in the...",
                      type="radio",
                      formatter=lambda v: RoleType.by_value(int(v)).
                      congress_chamber_long)
        sm.add_option('current_role_title', label="title", type="radio")
        sm.add_option('current_role_state',
                      label="state",
                      type="select",
                      formatter=format_state,
                      sort="LABEL")
        sm.add_option('current_role_district',
                      label="district",
                      type="select",
                      formatter=format_district,
                      visible_if=lambda form: "current_role_state" in form,
                      sort="KEY")
        sm.add_option('current_role_party',
                      label="party",
                      type="select",
                      formatter=lambda v: v.capitalize())
    elif mode == "all":
        sm.add_filter('all_role_types__in',
                      [RoleType.representative, RoleType.senator])
        sm.add_filter(
            'all_role_states__in', list(statenames)
        )  # only to filter the facet so an empty state value doesn't appear for MoCs that have also served as prez/vp
        sm.add_option('all_role_types',
                      label="ever served in the...",
                      type="radio",
                      formatter=lambda v: getattr(
                          RoleType.by_value(int(v)), 'congress_chamber_long',
                          RoleType.by_value(int(v)).label))
        sm.add_option('all_role_states',
                      label="ever represented...",
                      type="select",
                      formatter=format_state,
                      sort="LABEL")
        sm.add_option('all_role_districts',
                      label="district...",
                      type="select",
                      formatter=format_statedistrict,
                      visible_if=lambda form: "all_role_states" in form,
                      sort="KEY")
        sm.add_option('all_role_parties', label="party", type="select")

    sm.add_option('gender')

    sm.add_sort("Name", "sortname", default=True)
    if mode == "current":
        sm.add_sort("Seniority (Oldest First)", "first_took_office")
        sm.add_sort("Seniority (Newest Members First)", "-first_took_office")
    elif mode == "all":
        sm.add_sort("First Took Office (Oldest First)", "first_took_office")
        sm.add_sort("First Took Office (Newest First)", "-first_took_office")
        sm.add_sort("Left Office", "-left_office")

    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" alt="Photo of {{object.name}}"/>
			{% 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
Exemplo n.º 7
0
def vote_search_manager():
    sm = SearchManager(Vote, qs=Vote.objects.select_related('oursummary'))

    # show sessions as year+session for non-year-based sessions,
    # and then just the session number (the year) for year-based
    # sessions.
    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)"

    session_choices = reversed([(i, format_session(cs))
                                for (i, cs) in enumerate(get_all_sessions())
                                if cs[2] <= datetime.now().date()])

    sm.add_option(
        'session',
        type="select",
        choices=session_choices,
        filter=session_filter,
        help="Note: Even-year sessions extend a few days into the next year.")
    sm.add_option('chamber')
    sm.add_option('category')
    sm.add_sort('Date (Latest First)', '-created', default=True)
    sm.add_sort('Most Supported',
                '-percent_plus',
                func=lambda qs: qs.order_by('-percent_plus', '-total_plus').
                exclude(percent_plus=None))
    sm.add_sort('Most Opposed',
                'percent_plus',
                func=lambda qs: qs.order_by('percent_plus', '-total_minus').
                exclude(percent_plus=None))
    sm.add_sort('Widest Margin',
                '-margin',
                func=lambda qs: qs.order_by('-margin', '-total_plus').exclude(
                    margin=None))
    sm.add_sort('Narrowest Margin',
                'margin',
                func=lambda qs: qs.order_by('margin', 'total_plus').exclude(
                    margin=None))

    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")

    sm.set_template("""
    <div class="row">
        <div class="col-xs-12">
            <div style="margin-bottom: .2em"><a href="{{object.get_absolute_url}}">{{object.question|truncatewords_html:50}}</a></div>
        </div>
        <div style="font-size: 93%">
        <div class="col-xs-12 col-sm-6 col-md-4">
            <div><span class="fa fa-barcode fa-fw" aria-hidden="true" style="margin-left: 4px; color: #888"></span> {{object.name}}</div>
            <div><span class="fa fa-calendar fa-fw" aria-hidden="true" style="margin-left: 4px; color: #888"></span> {{object.created|date}} {{object.created|time|cut:"midnight"}}</div>
        </div>
        <div class="col-xs-12 col-sm-6 col-md-8">
        	<div><span class="fa fa-info fa-fw" aria-hidden="true" style="color: #888"></span> {{object.summary}}</div>
        </div>
        <div class="col-xs-12">
          <div style="margin-left: 5px">
            {% if object.question_details and not object.oursummary %}<div style="margin-top: .25em">{{object.question_details}}</div>{% endif %}
            {% if object.get_summary %}<div style="margin-top: .25em; font-style: italic; line-height: 126%;">{{object.get_summary.plain_text|truncatewords:50}}</div>{% endif %}
          </div>
        </div>
        </div>
    </div>
	""")

    return sm
Exemplo n.º 8
0
def state_bill_browse(request, state):
    if state != "" and state.upper() not in us.statenames:
        raise Http404()

    sm = SearchManager(StateBill, connection="states")

    if state: sm.add_filter('state', state)

    sm.add_option('text',
                  label='search title & summary',
                  type="text",
                  choices="NONE")
    if not state:
        sm.add_option('state',
                      label="state",
                      type="select",
                      sort="KEY",
                      formatter=lambda k: k.upper())
    sm.add_option('state_session',
                  label="session",
                  type="select",
                  sort=lambda k: (datetime.now().date() - k.startdate)
                  if k.startdate else timedelta(days=0),
                  visible_if=lambda post: state or "state" in post,
                  formatter=lambda k: k.name)  # use now to make reverse sort
    sm.add_option('chamber', label="chamber")

    sm.add_sort('Last Action', '-last_action_date', default=True)

    sm.set_template("""
    	<a href="{{object.get_absolute_url}}" style="font-size: 15px">{{object|truncatewords_html:50}}</a>
    	<div>{{object.state_session}}</div>
    	<div>{{object.last_action_date}}: {{object.last_action_text}}</div>
	""")

    return sm.view(
        request,
        "states/bill_search.html",
        defaults={
            "text": request.GET.get("text", ""),
        },
        noun=("state bill", "state bills"),
        context={
            "state":
            state.upper(),
            "statename":
            us.statenames.get(state.upper(), None),
            "feed":
            Feed.objects.get_or_create(feedname="states_allbills"
                                       if not state else "states_%s_bills" %
                                       state.upper())[0]
        },
    )
def bill_search_manager():
    sm = SearchManager(Bill, connection="bill")
    
    sm.add_option('similar_to', type="text", label="similar to (enter bill number)", visible_if=lambda form : False, filter=similar_to)
    sm.add_option('usc_cite', type="text", label="cites", visible_if=lambda form : False, orm_field_name='usc_citations_uptree', filter=usc_cite)
    
    sm.add_option('text', label='search title & full text', type="text", choices="NONE")
    sm.add_option('congress', type="select", formatter=format_congress_number, sort="KEY-REVERSE")
    sm.add_option('sponsor', type="select", sort="LABEL", formatter=lambda p : p.sortname)
    sm.add_option('current_status', label="current status", sort=lambda s : BillStatus.by_value(s).sort_order)
    sm.add_option('cosponsors', label="cosponsor", type="select", sort="LABEL", formatter=lambda p : p.sortname)
    sm.add_option('committees', label="committee", type="select", sort="LABEL", formatter=lambda c : c.shortname)
    sm.add_option('terms', type="select", label="subject", choices=get_terms(BillTerm.objects.exclude(parents__id__gt=0)))
    sm.add_option('terms2', type="select", label="subject 2", choices=sub_terms, visible_if=lambda post:"terms" in post, filter=sub_term_filter)
    sm.add_option('sponsor_party', label="party of sponsor", type="select")
    sm.add_option('bill_type', label="bill or resolution type")
    
    #sm.add_sort("Popularity", "-total_bets", default=True)
    sm.add_sort("Secret Sauce", "-proscore", default=True)
    sm.add_sort("Introduced Date (Newest First)", "-introduced_date")
    sm.add_sort("Introduced Date (Oldest First)", "introduced_date")
    sm.add_sort("Last Major Action (Recent First)", "-current_status_date")

    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")
    
    sm.set_template("""
    	<a href="{{object.get_absolute_url}}" style="font-size: 15px">{{object|truncatewords_html:50}}</a>
    	{% if object.sponsor %}<div>Sponsor: {{object.sponsor}}</div>{% endif %}
    	{% if object.source != "statutesatlarge" %}<div>Introduced: {{object.introduced_date}}</div>{% endif %}
    	{% if object.source != "americanmemory" %}<div>{% if object.source != "statutesatlarge" %}{{object.get_current_status_display}}{% else %}Enacted/Agreed to{% endif %}: {{object.current_status_date}}</div>{% endif %}
	""")
    
    return sm
Exemplo n.º 10
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
Exemplo n.º 11
0
def person_search_manager(mode):
    sm = SearchManager(Person, connection="person")

    sm.add_option('text', label='name', type="text")

    if mode == "current":
        sm.add_filter('current_role_type__in', [RoleType.representative, RoleType.senator])
        sm.add_option('current_role_type', label="serving in the...", type="radio", formatter=lambda v : RoleType.by_value(int(v)).congress_chamber_long)
        sm.add_option('current_role_title', label="title", type="radio")
        sm.add_option('current_role_state', label="state", type="select", formatter=format_state, sort="LABEL")
        sm.add_option('current_role_district', label="district", type="select", formatter=format_district, visible_if=lambda form:"current_role_state" in form, sort="KEY")
        sm.add_option('current_role_party', label="party", type="select", formatter=lambda v : v.capitalize())
    elif mode == "all":
        sm.add_filter('all_role_types__in', [RoleType.representative, RoleType.senator])
        sm.add_filter('all_role_states__in', list(statenames)) # only to filter the facet so an empty state value doesn't appear for MoCs that have also served as prez/vp
        sm.add_option('all_role_types', label="ever served in the...", type="radio", formatter=lambda v : getattr(RoleType.by_value(int(v)), 'congress_chamber_long', RoleType.by_value(int(v)).label))
        sm.add_option('all_role_states', label="ever represented...", type="select", formatter=format_state, sort="LABEL")
        sm.add_option('all_role_districts', label="district...", type="select", formatter=format_statedistrict, visible_if=lambda form:"all_role_states" in form, sort="KEY")
        sm.add_option('all_role_parties', label="party", type="select")

    sm.add_option('gender')

    sm.add_sort("Name", "sortname", default=True)
    if mode == "current":
        sm.add_sort("Seniority (Oldest First)", "first_took_office")
        sm.add_sort("Seniority (Newest Members First)", "-first_took_office")
    elif mode == "all":
        sm.add_sort("First Took Office (Oldest First)", "first_took_office")
        sm.add_sort("First Took Office (Newest First)", "-first_took_office")
        sm.add_sort("Left Office", "-left_office")
    
    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
Exemplo n.º 12
0
def vote_search_manager():
    sm = SearchManager(Vote, qs=Vote.objects.order_by('-created').select_related('oursummary'))
    
    # show sessions as year+session for non-year-based sessions,
    # and then just the session number (the year) for year-based
    # sessions.
    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)"
    	
    session_choices = reversed([(i, format_session(cs)) for (i,cs) in enumerate(get_all_sessions()) if cs[2] <= datetime.now().date()])
    
    sm.add_option('session', type="select", choices=session_choices, filter=session_filter, help="Note: Even-year sessions extend a few days into the next year.")
    sm.add_option('chamber')
    sm.add_option('category')
    sm.add_sort('Percentage Yes','percent_yes')
    
    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")

    sm.set_template("""
    <div class="row">
        <div class="col-xs-12">
            <div style="margin-bottom: .2em"><a href="{{object.get_absolute_url}}">{{object.question|truncatewords_html:50}}</a></div>
        </div>
        <div style="font-size: 93%">
        <div class="col-sm-6 col-md-4">
            <div><span class="fa fa-barcode fa-fw" aria-hidden="true" style="margin-left: 4px; color: #888"></span> {{object.name}}</div>
            <div><span class="fa fa-calendar fa-fw" aria-hidden="true" style="margin-left: 4px; color: #888"></span> {{object.created|date}} {{object.created|time|cut:"midnight"}}</div>
        </div>
        <div class="col-sm-6 col-md-8">
        	<div><span class="fa fa-info fa-fw" aria-hidden="true" style="color: #888"></span> {{object.summary}}</div>
        </div>
        <div class="col-xs-12" style="padding-top: .25em">
            {% if object.question_details and not object.oursummary %}<div style="margin-left: 5px">{{object.question_details}}</div>{% endif %}
            {% if object.oursummary %}<div style="font-style: italic">{{object.oursummary.plain_text|truncatewords:50}}</div>{% endif %}
        </div>
        </div>
    </div>
	""")

    return sm
Exemplo n.º 13
0
def bill_search_manager():
    sm = SearchManager(Bill, connection="bill", bulk_loader=bill_bulk_loader)
    
    sm.add_option('similar_to', type="text", label="similar to (enter bill number)", visible_if=lambda form : False, filter=similar_to)
    sm.add_option('usc_cite', type="text", label="cites", visible_if=lambda form : False, orm_field_name='usc_citations_uptree', filter=usc_cite)
    
    sm.add_option('text', label='search title & full text', type="text", choices="NONE")
    sm.add_option('congress', type="select", formatter=format_congress_number, sort="KEY-REVERSE")
    sm.add_option('sponsor', type="select", sort="LABEL", formatter=lambda p : p.sortname)
    sm.add_option('current_status', label="current status", sort=lambda s : BillStatus.by_value(s).sort_order)
    sm.add_option('enacted_ex', type="boolean", label="Enacted \u2014 Including by Incorporation into Other Bills")
    sm.add_option('cosponsors', label="cosponsor", type="select", sort="LABEL", formatter=lambda p : p.sortname)
    sm.add_option('committees', label="committee", type="select", sort="LABEL", formatter=lambda c : c.shortname)
    sm.add_option('terms', type="select", label="subject", choices=get_terms(BillTerm.objects.exclude(parents__id__gt=0)))
    sm.add_option('terms2', type="select", label="subject 2", choices=sub_terms, visible_if=lambda post:"terms" in post, filter=sub_term_filter)
    sm.add_option('sponsor_party', label="party of sponsor", type="select")
    sm.add_option('bill_type', label="bill or resolution type")
    
    #sm.add_sort("Popularity", "-total_bets", default=True)
    # default sort order is handled by the view
    sm.add_sort("Relevance of Title/Text", "relevance", func=lambda x : x) # no-op to use Solr default
    sm.add_sort("Secret Sauce", "-proscore")
    sm.add_sort("Introduced Date (Newest First)", "-introduced_date")
    sm.add_sort("Introduced Date (Oldest First)", "introduced_date")
    sm.add_sort("Last Major Action (Recent First)", "-current_status_date")
    sm.add_sort("Cosponsors (Most First)", "-cosponsor_count")
    sm.add_sort("Cosponsors (Fewest First)", "cosponsor_count")

    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")
    
    sm.set_template("""
	<div class="row">
		<div class="col-xs-2 col-md-1" style="padding-right: 0">
			<img src="{{object.get_absolute_url}}/thumbnail?aspect=1.2&width=125" class="img-responsive"/>
		</div>
		<div class="col-xs-10 col-md-11">
    	<div style="margin-bottom: 3px"><a href="{{object.get_absolute_url}}" style="font-size: 15px; line-height: 125%;">{{object|truncatewords_html:50}}</a></div>
		<div style="font-size: 90%">
    	{% if object.sponsor %}<div style="margin-bottom: 3px">Sponsor: {{object.sponsor_name}}</div>{% endif %}
		<table width="100%"><tr valign="top">
    	{% if object.source != "statutesatlarge" %}<td width="25%" style="padding-right: 1.5em">Introduced<br>{{object.introduced_date}}</td>{% else %}<td/>{% endif %}
    	{% if object.source != "americanmemory" and object.get_current_status_display_simple != "Introduced" %}<td width="25%" style="padding-right: 1.5em">{% if object.source != "statutesatlarge" %}{{object.get_current_status_display_simple}}{% else %}Enacted/Agreed to{% endif %}<br>{{object.current_status_date}}</td>{% else %}<td/>{% endif %}
		{% if 1 %}<td width="25%" style="padding-right: 1.5em">Cosponsors<br>{{object.cosponsor_counts_summary}}</td>{% else %}<td/>{% endif %}
		{% if object.is_alive and object.get_prognosis %}<td width="25%" style="padding-right: 1.5em">Prognosis<br>{{object.get_prognosis.prediction|floatformat:0}}%</td>{% else %}<td/>{% endif %}
		</tr></table>
        {% with b_list=object.was_enacted_ex %}
        {% for b in b_list %}
            {% if b and b != object %}
                <div>Enacted via <a href="{{b.get_absolute_url}}" style="text-decoration: none">{{b.title}}</a></div>
            {% endif %}
        {% endfor %}
		</div>
		</div>
	</div>
        {% endwith %}
	""")
    
    return sm
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
Exemplo n.º 15
0
def bill_search_manager():
    sm = SearchManager(Bill, connection="bill", bulk_loader=bill_bulk_loader)
    
    sm.add_option('similar_to', type="text", label="similar to (enter bill number)", visible_if=lambda form : False, filter=similar_to)
    sm.add_option('usc_cite', type="text", label="cites", visible_if=lambda form : False, orm_field_name='usc_citations_uptree', filter=usc_cite)
    
    sm.add_option('text', label='search title & full text', type="text", choices="NONE")
    sm.add_option('congress', type="select", formatter=format_congress_number, sort="KEY-REVERSE")
    sm.add_option('sponsor', type="select", sort="LABEL", formatter=lambda p : p.sortname)
    sm.add_option('current_status', label="current status", sort=lambda s : BillStatus.by_value(s).sort_order)
    sm.add_option('enacted_ex', type="boolean", label="Enacted \u2014 Including by Incorporation into Other Bills")
    sm.add_option('cosponsors', label="cosponsor", type="select", sort="LABEL", formatter=lambda p : p.sortname)
    sm.add_option('committees', label="committee", type="select", sort="LABEL", formatter=lambda c : c.shortname)
    sm.add_option('terms', type="select", label="subject", choices=get_terms(BillTerm.objects.exclude(parents__id__gt=0)))
    sm.add_option('terms2', type="select", label="subject 2", choices=sub_terms, visible_if=lambda post:"terms" in post, filter=sub_term_filter)
    sm.add_option('sponsor_party', label="party of sponsor", type="select")
    sm.add_option('bill_type', label="bill or resolution type")
    
    #sm.add_sort("Popularity", "-total_bets", default=True)
    # default sort order is handled by the view
    sm.add_sort("Secret Sauce", "-proscore")
    sm.add_sort("Introduced Date (Newest First)", "-introduced_date")
    sm.add_sort("Introduced Date (Oldest First)", "introduced_date")
    sm.add_sort("Last Major Action (Recent First)", "-current_status_date")
    sm.add_sort("Cosponsors (Most First)", "-cosponsor_count")
    sm.add_sort("Cosponsors (Fewest First)", "cosponsor_count")

    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")
    
    sm.set_template("""
	<div class="row">
		<div class="col-xs-2 col-md-1" style="padding-right: 0">
			<img src="{{object.get_absolute_url}}/thumbnail?aspect=1.2&width=125" class="img-responsive"/>
		</div>
		<div class="col-xs-10 col-md-11">
    	<div style="margin-bottom: 3px"><a href="{{object.get_absolute_url}}" style="font-size: 15px; line-height: 125%;">{{object|truncatewords_html:50}}</a></div>
		<div style="font-size: 90%">
    	{% if object.sponsor %}<div style="margin-bottom: 3px">Sponsor: {{object.sponsor_name}}</div>{% endif %}
		<table width="100%"><tr valign="top">
    	{% if object.source != "statutesatlarge" %}<td width="25%" style="padding-right: 1.5em">Introduced<br>{{object.introduced_date}}</td>{% else %}<td/>{% endif %}
    	{% if object.source != "americanmemory" and object.get_current_status_display_simple != "Introduced" %}<td width="25%" style="padding-right: 1.5em">{% if object.source != "statutesatlarge" %}{{object.get_current_status_display_simple}}{% else %}Enacted/Agreed to{% endif %}<br>{{object.current_status_date}}</td>{% else %}<td/>{% endif %}
		{% if 1 %}<td width="25%" style="padding-right: 1.5em">Cosponsors<br>{{object.cosponsor_counts_summary}}</td>{% else %}<td/>{% endif %}
		{% if object.is_alive and object.get_prognosis %}<td width="25%" style="padding-right: 1.5em">Prognosis<br>{{object.get_prognosis.prediction|floatformat:0}}%</td>{% else %}<td/>{% endif %}
		</tr></table>
        {% with b_list=object.was_enacted_ex %}
        {% for b in b_list %}
            {% if b and b != object %}
                <div>Enacted via <a href="{{b.get_absolute_url}}" style="text-decoration: none">{{b.title}}</a></div>
            {% endif %}
        {% endfor %}
		</div>
		</div>
	</div>
        {% endwith %}
	""")
    
    return sm
Exemplo n.º 16
0
def bill_search_manager():
    sm = SearchManager(Bill, connection="bill")

    sm.add_option('similar_to',
                  type="text",
                  label="similar to (enter bill number)",
                  visible_if=lambda form: False,
                  filter=similar_to)
    sm.add_option('usc_cite',
                  type="text",
                  label="cites",
                  visible_if=lambda form: False,
                  orm_field_name='usc_citations_uptree',
                  filter=usc_cite)

    sm.add_option('text',
                  label='search title & full text',
                  type="text",
                  choices="NONE")
    sm.add_option('congress',
                  type="select",
                  formatter=format_congress_number,
                  sort="KEY-REVERSE")
    sm.add_option('sponsor',
                  type="select",
                  sort="LABEL",
                  formatter=lambda p: p.sortname)
    sm.add_option('current_status',
                  label="current status",
                  sort=lambda s: BillStatus.by_value(s).sort_order)
    sm.add_option(
        'enacted_ex',
        type="boolean",
        label=u"Enacted \u2014 Including by Incorporation into Other Bills")
    sm.add_option('cosponsors',
                  label="cosponsor",
                  type="select",
                  sort="LABEL",
                  formatter=lambda p: p.sortname)
    sm.add_option('committees',
                  label="committee",
                  type="select",
                  sort="LABEL",
                  formatter=lambda c: c.shortname)
    sm.add_option('terms',
                  type="select",
                  label="subject",
                  choices=get_terms(
                      BillTerm.objects.exclude(parents__id__gt=0)))
    sm.add_option('terms2',
                  type="select",
                  label="subject 2",
                  choices=sub_terms,
                  visible_if=lambda post: "terms" in post,
                  filter=sub_term_filter)
    sm.add_option('sponsor_party', label="party of sponsor", type="select")
    sm.add_option('bill_type', label="bill or resolution type")

    #sm.add_sort("Popularity", "-total_bets", default=True)
    # default sort order is handled by the view
    sm.add_sort("Secret Sauce", "-proscore")
    sm.add_sort("Introduced Date (Newest First)", "-introduced_date")
    sm.add_sort("Introduced Date (Oldest First)", "introduced_date")
    sm.add_sort("Last Major Action (Recent First)", "-current_status_date")

    #def safe_strftime(date, format):
    #    return date.replace(year=3456).strftime(format).replace("3456", str(date.year)).replace(" 12:00AM", "")

    sm.set_template("""
    	<a href="{{object.get_absolute_url}}" style="font-size: 15px; line-height: 125%;">{{object|truncatewords_html:50}}</a>
    	{% if object.sponsor %}<div>Sponsor: {{object.sponsor}}</div>{% endif %}
    	{% if object.source != "statutesatlarge" %}<div>Introduced: {{object.introduced_date}}</div>{% endif %}
    	{% if object.source != "americanmemory" %}<div>{% if object.source != "statutesatlarge" %}{{object.get_current_status_display}}{% else %}Enacted/Agreed to{% endif %}: {{object.current_status_date}}</div>{% endif %}
        {% with b_list=object.was_enacted_ex %}
        {% for b in b_list %}
            {% if b and b != object %}
                <div>Enacted via <a href="{{b.get_absolute_url}}">{{b.title}}</a></div>
            {% endif %}
        {% endfor %}
        {% endwith %}
	""")

    return sm
Exemplo n.º 17
0
def state_bill_browse(request, state):
	if state != "" and state.upper() not in us.statenames:
		raise Http404()
	
	sm = SearchManager(StateBill, connection="states")

	if state: sm.add_filter('state', state)

	sm.add_option('text', label='search title & summary', type="text", choices="NONE")
	if not state: sm.add_option('state', label="state", type="select", sort="KEY", formatter=lambda k : k.upper())
	sm.add_option('state_session', label="session", type="select", sort=lambda k : (datetime.now().date() - k.startdate) if k.startdate else timedelta(days=0), visible_if=lambda post:state or "state" in post, formatter=lambda k : k.name) # use now to make reverse sort
	sm.add_option('chamber', label="chamber")

	sm.set_template("""
    	<a href="{{object.get_absolute_url}}" style="font-size: 15px">{{object|truncatewords_html:50}}</a>
    	<div>{{object.state_session}}</div>
    	<div>{{object.last_action_date}}: {{object.last_action_text}}</div>
	""")

	return sm.view(request, "states/bill_search.html",
		defaults={
			"text": request.GET.get("text", ""),
		},
		noun = ("state bill", "state bills"),
		context = {
			"state": state.upper(),
			"statename": us.statenames.get(state.upper(), None),
		},
		)