当前位置: 首页>>代码示例>>Python>>正文


Python State.select方法代码示例

本文整理汇总了Python中models.State.select方法的典型用法代码示例。如果您正苦于以下问题:Python State.select方法的具体用法?Python State.select怎么用?Python State.select使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.State的用法示例。


在下文中一共展示了State.select方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: produce_bop_json

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def produce_bop_json():
    """
    Loops through houses/parties to count seats and calculate deltas.
    """
    # Party mapping.
    parties = [('republicans', 'r'), ('democrats', 'd'), ('other', 'o')]

    # House/seats/delta mapping.
    houses = [('house', 'H'), ('senate', 'S')]

    # Blank dataset.
    data = bootstrap_bop_data()

    # President.
    for state in State.select().where(State.called == True):
        for party, abbr in parties:
            if state.winner == abbr:
                data['president'][party] = calculate_president_bop(data['president'][party], state.electoral_votes)

    # House/senate.
    for office, short in houses:
        for race in Race.select().where(
            (Race.ap_called == True) | (Race.npr_called == True), Race.office_code == short):
            for party, abbr in parties:
                if race.winner == abbr:
                    if short == 'H':
                        data[office][party] = calculate_house_bop(data[office][party])
                    if short == 'S':
                        data[office][party] = calculate_senate_bop(race, data[office][party])

            if short == 'S':
                data[office] = calculate_net_pickups(race, data[office])

        # Write the number of uncalled races.
        # First, the races where we accept AP calls but no calls have come in.
        data[office]['not_called'] += Race.select()\
            .where(
                Race.accept_ap_call == True,
                Race.ap_called == False,
                Race.office_code == short)\
            .count()

        # Second, the races where we don't accept AP calls and no NPR calls are in.
        data[office]['not_called'] += Race.select()\
            .where(
                Race.accept_ap_call == False,
                Race.npr_called == False,
                Race.office_code == short)\
            .count()

    return data
开发者ID:imclab,项目名称:electris,代码行数:53,代码来源:output.py

示例2: parse_president_district

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def parse_president_district(state_code, row):
    race_data = dict(zip(DISTRICT_RACE_FIELDS, row[:len(DISTRICT_RACE_FIELDS)]))
    candidate_count = (len(row) - len(DISTRICT_RACE_FIELDS)) / len(DISTRICT_CANDIDATE_FIELDS)

    i = 0
    obama_data = None
    romney_data = None
    total_vote_count = 0

    while i < candidate_count:
        first_field = len(DISTRICT_RACE_FIELDS) + (i * len(DISTRICT_CANDIDATE_FIELDS))
        last_field = first_field + len(DISTRICT_CANDIDATE_FIELDS)

        candidate_data = dict(zip(DISTRICT_CANDIDATE_FIELDS, row[first_field:last_field]))

        if candidate_data['last_name'] == 'Obama':
            obama_data = candidate_data
        elif candidate_data['last_name'] == 'Romney':
            romney_data = candidate_data

        total_vote_count += int(candidate_data['vote_count'])

        i += 1

    assert obama_data and romney_data

    if race_data['district_name'] == state_code:
        q = (State.id == state_code.lower())
    else:
        district_number = race_data['district_name'][-1:]
        q = (State.id == state_code.lower() + district_number)

    state = State.select().where(q).get()
    ap_call = 'r' if romney_data['ap_winner'] else 'd' if obama_data['ap_winner'] else 'u'

    ap_called_at = state.ap_called_at

    if ap_call != state.ap_call:
        ap_called_at = datetime.datetime.now(tz=pytz.utc)

    state.ap_call = ap_call
    state.ap_called_at = ap_called_at
    state.total_precincts = race_data['total_precincts']
    state.precincts_reporting = race_data['precincts_reporting']
    state.rep_vote_count = romney_data['vote_count']
    state.dem_vote_count = obama_data['vote_count']
    state.total_vote_count = total_vote_count

    state.save()
开发者ID:imclab,项目名称:electris,代码行数:51,代码来源:input.py

示例3: bootstrap_president

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def bootstrap_president():
    """
    Creates/overwrites presidential state results with initial data.
    """
    with open('initial_data/president_bootstrap.csv') as f:
        reader = csv.DictReader(f)
        for row in reader:
            for field in ['total_precincts', 'precincts_reporting', 'rep_vote_count', 'dem_vote_count']:
                if row[field] == '':
                    row[field] = 0
            try:
                state = State.select().where(
                    State.id == row['id']
                ).get()
                state.update(**row)
            except State.DoesNotExist:
                state = State.create(**row)

            state.save()
开发者ID:imclab,项目名称:electris,代码行数:21,代码来源:input.py

示例4: write_electris_json

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def write_electris_json():
    """
    Rewrites JSON files from the DB for president.
    """
    output_states = []

    for state in State.select().order_by(State.electoral_votes.desc(), State.name.asc()):
        state = state._data

        if state['npr_call'] != 'n' and state['npr_call'] != 'u':
            state['call'] = state['npr_call']
            state['called_at'] = state['npr_called_at']
            state['called_by'] = 'npr'
        elif state['accept_ap_call'] and state['ap_call'] != 'u':
            state['call'] = state['ap_call']
            state['called_at'] = state['ap_called_at']
            state['called_by'] = 'ap'
        else:
            state['call'] = None
            state['called_at'] = None
            state['called_by'] = None

        del state['npr_call']
        del state['npr_called_at']
        del state['ap_call']
        del state['ap_called_at']

        del state['called_by']
        del state['accept_ap_call']
        del state['rowid']
        del state['prediction']

        output_states.append(state)

    output = json.dumps({
        'balance_of_power': produce_bop_json(),
        'states': output_states
    })

    with open(settings.PRESIDENT_FILENAME, 'w') as f:
        f.write(output)
开发者ID:imclab,项目名称:electris,代码行数:43,代码来源:output.py

示例5: update_polls

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def update_polls():
    pollster = Pollster()

    for state in State.select().where(State.electoral_votes > 1):
        charts = pollster.charts(topic='2012-president', state=state.id)

        if charts:
            chart = charts[0]
        else:
            print 'NO DATA FOR %s' % state.id.upper()
            continue

        obama = 0
        romney = 0

        if chart.estimates:
            for estimate in chart.estimates:
                if estimate['choice'] == "Obama":
                    obama = estimate['value']
                elif estimate['choice'] == "Romney":
                    romney = estimate['value']
        else:
            print 'NO ESTIMATES FOR %s' % state.id.upper()
            continue

        prediction = "t"

        if abs(obama - romney) > 15:
            if obama > romney:
                prediction = "sd"
            else:
                prediction = "sr"
        elif abs(obama - romney) > 7.5:
            if obama > romney:
                prediction = "ld"
            else:
                prediction = "lr"

        uq = State.update(prediction=prediction).where(State.id == state)
        uq.execute()
开发者ID:imclab,项目名称:electris,代码行数:42,代码来源:input.py

示例6: write_replay_json

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def write_replay_json():
    def _scale_time(time):
        first_time = datetime.datetime(2012, 11, 06, 19, 04, 02)
        delta = time - first_time
        return round(delta.seconds * 0.00321, 0) * 1000

    output = []
    states = sorted(State.select(), key=lambda state: state.called_time)
    for state in states:
        state_dict = state._data
        state_dict['scaled_time'] = _scale_time(state.called_time)

        if state_dict['npr_call'] != 'n' and state_dict['npr_call'] != 'u':
            state_dict['call'] = state_dict['npr_call']
            state_dict['called_at'] = state_dict['npr_called_at']
            state_dict['called_by'] = 'npr'
        elif state_dict['accept_ap_call'] and state_dict['ap_call'] != 'u':
            state_dict['call'] = state_dict['ap_call']
            state_dict['called_at'] = state_dict['ap_called_at']
            state_dict['called_by'] = 'ap'
        else:
            state_dict['call'] = None
            state_dict['called_at'] = None
            state_dict['called_by'] = None

        del state_dict['npr_call']
        del state_dict['npr_called_at']
        del state_dict['ap_call']
        del state_dict['ap_called_at']

        del state_dict['called_by']
        del state_dict['accept_ap_call']
        del state_dict['rowid']
        del state_dict['prediction']

        output.append(state_dict)

    with open('www/replay.json', 'w') as f:
        f.write(json.dumps(output))
开发者ID:imclab,项目名称:electris,代码行数:41,代码来源:output.py

示例7: president

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def president(featured=None):
    """
    Read/update list of presidential state winners.
    """

    is_featured = False
    if featured == 'featured':
        is_featured = True

    if request.method == 'GET':

        states = State.select().order_by(State.name.asc())

        if is_featured == True:
            states = states.where(State.prediction == 't').order_by(State.name.asc())

        context = {
            'states': states,
            'settings': settings
        }

        return render_template('president.html', **context)

    if request.method == 'POST':
        # First, try and get the state.
        race_slug = request.form.get('race_slug', None)
        race_slug = race_slug.strip()

        # Next, try to get the AP call.
        accept_ap_call = request.form.get('accept_ap_call', None)

        if accept_ap_call != None:
            # Figure out which direction we're going and send an appropriate message.
            if accept_ap_call.lower() == 'true':
                accept_ap_call = True
            else:
                accept_ap_call = False

        # Accumulate changes so we only execute a single update
        update_dict = {}

        # If all the pieces are here, do something.
        if race_slug != None and accept_ap_call != None:

            # Run some SQL to change the status of this set of candidate's accept_ap_call column.
            sq = State.update(accept_ap_call=accept_ap_call).where(State.id == race_slug)
            sq.execute()

            # Clear the NPR winner status of candidates who we accept AP calls for.
            if accept_ap_call == True:
                update_dict['npr_call'] = 'n',
                update_dict['npr_called_at'] = None

        # Try and get the winner.
        party = request.form.get('party', None)

        # Try and get a clear_all.
        clear_all = request.form.get('clear_all', None)

        if race_slug != None and clear_all != None:
            # If we're passing clear_all as true ...
            if clear_all == 'true':
                update_dict['npr_call'] = 'n',
                update_dict['npr_called_at'] = None

        # If all of the pieces are here, do something.
        if race_slug != None and party != None:
            update_dict['npr_call'] = party,
            update_dict['npr_called_at'] = datetime.datetime.utcnow()

        if update_dict:
            uq = State.update(**update_dict).where(State.id == race_slug)
            uq.execute()

        if settings.DEBUG:
            o.write_electris_json()
            o.write_president_json()
            o.write_bop_json()

        # TODO
        # Return a 200. This is probably bad.
        # Need to figure out what should go here.
        return "Success."
开发者ID:imclab,项目名称:electris,代码行数:85,代码来源:cms.py

示例8: write_president_json

# 需要导入模块: from models import State [as 别名]
# 或者: from models.State import select [as 别名]
def write_president_json():
    """
    Outputs the president json file for bigboard's frontend.
    """

    data = {}
    data['balance_of_power'] = produce_bop_json()
    data['results'] = []

    for timezone in time_zones.PRESIDENT_TIMES:
        timezone_dict = {}
        timezone_dict['gmt_epoch_time'] = timezone['time']
        timezone_dict['states'] = []
        for s in timezone['states']:
            for state in State.select():
                if state.id == s.lower():
                    state_dict = state._data
                    state_dict['rep_vote_percent'] = state.rep_vote_percent()
                    state_dict['dem_vote_percent'] = state.dem_vote_percent()
                    state_dict['human_gop_vote_count'] = state.human_rep_vote_count()
                    state_dict['human_dem_vote_count'] = state.human_dem_vote_count()
                    state_dict['called'] = state.called
                    state_dict['winner'] = state.winner

                    if state_dict['npr_call'] != 'n' and state_dict['npr_call'] != 'u':
                        state_dict['call'] = state_dict['npr_call']
                        state_dict['called_at'] = state_dict['npr_called_at']
                        state_dict['called_by'] = 'npr'
                    elif state_dict['accept_ap_call'] and state_dict['ap_call'] != 'u':
                        state_dict['call'] = state_dict['ap_call']
                        state_dict['called_at'] = state_dict['ap_called_at']
                        state_dict['called_by'] = 'ap'
                    else:
                        state_dict['call'] = None
                        state_dict['called_at'] = None
                        state_dict['called_by'] = None

                    call_time = None
                    if state_dict['called_at'] != None:
                        call_time = datetime.datetime.strptime(state_dict['called_at'].split('+')[0], '%Y-%m-%d %H:%M:%S.%f')
                        call_time = utc.normalize(utc.localize(call_time))

                    if state_dict['called_at'] != None:
                        state_dict['status_tag'] = 'Called time.'
                        state_dict['status'] = call_time.astimezone(eastern).strftime('%I:%M').lstrip('0')
                    else:
                        if state.precincts_reporting > 0:
                            state_dict['status_tag'] = 'Percent reporting.'
                            pct = state.percent_reporting()

                            if pct < 1:
                                state_dict['status'] = u'< 1%'
                            elif pct > 99 and pct < 100:
                                state_dict['status'] = u'99%'
                            else:
                                state_dict['status'] = u'%.0f%%' % pct
                        else:
                            state_dict['status_tag'] = 'No precincts reporting.'
                            if state_dict['dem_vote_count'] + state_dict['rep_vote_count'] > 0:
                                state_dict['status'] = u'< 1%'
                            else:
                                state_dict['status'] = u'&nbsp;'

                    timezone_dict['states'].append(state_dict)
            timezone_dict['states'] = sorted(timezone_dict['states'], key=lambda state: state['name'])
        data['results'].append(timezone_dict)

    with open('www/president.json', 'w') as f:
        f.write(json.dumps(data))
开发者ID:imclab,项目名称:electris,代码行数:71,代码来源:output.py


注:本文中的models.State.select方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。