Example #1
0
    def test_update_results(self):
        with test_database(test_db, [Race, Candidate]):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')
            data.load_updates('data/tests/update.json')
            race = Race.get(Race.race_id == '38529-OR')

            candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR')
            candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR')
            candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR')

            self.assertEqual(race.precincts_reporting, 1970)
            self.assertEqual(race.precincts_total, 2288)
            self.assertTrue(race.is_reporting())

            self.assertEqual(candidate_4848.vote_count, 150000)
            self.assertEqual(candidate_4642.vote_count, 200000)
            self.assertEqual(candidate_4979.vote_count, 250000)
            self.assertEqual(race.count_votes(), 600000)

            self.assertEqual(candidate_4848.vote_percent(), Decimal('25.0'))
            self.assertAlmostEqual(candidate_4642.vote_percent(),
                                   Decimal('33.333'), 3)
            self.assertAlmostEqual(candidate_4979.vote_percent(),
                                   Decimal('41.667'), 3)

            # Results does not call races
            self.assertFalse(candidate_4848.ap_winner)
            self.assertFalse(candidate_4642.ap_winner)
            self.assertFalse(candidate_4979.ap_winner)
Example #2
0
    def test_update_results(self):
        with test_database(test_db, [Race, Candidate]):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')
            data.load_updates('data/tests/update.json')
            race = Race.get(Race.race_id == '38529-OR')

            candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR')
            candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR')
            candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR')

            self.assertEqual(race.precincts_reporting, 1970)
            self.assertEqual(race.precincts_total, 2288)
            self.assertTrue(race.is_reporting())

            self.assertEqual(candidate_4848.vote_count, 150000)
            self.assertEqual(candidate_4642.vote_count, 200000)
            self.assertEqual(candidate_4979.vote_count, 250000)
            self.assertEqual(race.count_votes(), 600000)

            self.assertEqual(candidate_4848.vote_percent(), Decimal('25.0')) 
            self.assertAlmostEqual(candidate_4642.vote_percent(), Decimal('33.333'), 3) 
            self.assertAlmostEqual(candidate_4979.vote_percent(), Decimal('41.667'), 3) 

            # Results does not call races
            self.assertFalse(candidate_4848.ap_winner)
            self.assertFalse(candidate_4642.ap_winner)
            self.assertFalse(candidate_4979.ap_winner)
Example #3
0
def voting_edit(request,vot_id):
    #zabezpieczenie przed edycja glosowanie juz rozpoczetego oraz glosowania,ktorego nie jestesmy wlascicielami
    voting = get_object_or_404(Voting, pk=vot_id,moderator__user=request.user,od__gt =timezone.now().date()) #zmiana na date()
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = VotingForm(request.POST,instance=voting,user=request.user)
        # check whether it's valid:
        if form.is_valid():

            vot = form.save(commit=False);
            vot.save()
            vot.candidate_set.all().delete()
            vot.voter_set.all().delete()

            for k in form.cleaned_data['kandydaci']:
                kan = Candidate(glosowanie=vot,osoba=k)
                kan.save()

            for u in form.cleaned_data['uprawnieni']:
                upr = Voter(glosowanie=vot,osoba=u)
                upr.save()

            #form.save_m2m() ## zamiast tego dodac reczny zapis do bazy
            return render(request, 'editVotingSuccess.html')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = VotingForm(instance=voting,user=request.user)
        #form.fields["kandydaci"].queryset = UserProfile.objects.exclude(user=request.user) ##modyfikujemy liste kandydatow
    return render(request, 'editVoting.html', {'regform': form,'vot_id':voting.id})
Example #4
0
    def apply_job():
        request_value = request.get_json()
        job_id = request_value['job_id']
        company_id = request_value['company_id']
        job = Job.query.filter_by(id=job_id).one_or_none()
        if job is None:
            abort(404)

        company = Company.query.filter_by(id=company_id).one_or_none()
        if company is None:
            abort(404)

        candidate = Candidate(
            job_id,
            company_id,
            request_value['name'],
            request_value['email'],
            request_value['phone']
        )

        candidate.insert()

        return jsonify({
            'message': 'Your application was successfully sent.',
            'status_code': 200,
            'success': True
        })
Example #5
0
def add_candidate(request):

    if request.user.is_authenticated():
        user_id = request.user.id
        fname   = request.GET.get('fname')
        lname   = request.GET.get('lname')
        date    = request.GET.get('date')
        jd_name = request.GET.get('jd').split('-')[0]
        email   = request.GET.get('email')
        mobile  = request.GET.get('mobile')
        remarks = request.GET.get('remarks')
        if remarks:
            pass
        else:
            remarks = "New"
        jd_id   = JobDesTable.objects.filter(job_title=jd_name).values('id')
        date    = date_parser.parse(date.replace(' GMT ',' GMT+'))
        date    = date_parser.parse('-'.join(str(date).split('-')[:-1]))
        agent_id        = Agent.objects.filter(name_id = user_id).values_list('id', flat= True)[0]

        new_can = Candidate(jd_id = jd_id[0]['id'], location="",fname = fname,lname = lname,walk_in_date = date,email_id = email,
                  mobile_number = mobile,status_id = 1,agent_id = agent_id, remarks = remarks)
        new_can.save()
        data = {'status':'success'}

    else:
        data = {'status':'failed'}

    return HttpResponse(data)
Example #6
0
def addVoting(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = VotingForm(request.POST,user=request.user)
        # check whether it's valid:
        if form.is_valid():
            vot = form.save(commit=False);
            vot.moderator = UserProfile.objects.filter(user=request.user)[0]
            vot.save() ## zrobic zapisywanie wiele do wielu
            for k in form.cleaned_data['kandydaci']:
                kan = Candidate(glosowanie=vot,osoba=k)
                kan.save()

            for u in form.cleaned_data['uprawnieni']:
                upr = Voter(glosowanie=vot,osoba=u)
                upr.save()

            #form.save_m2m() ## zamiast tego dodac reczny zapis do bazy
            return render(request, 'AddVotingSuccess.html')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = VotingForm(user=request.user)
        #form.fields["kandydaci"].queryset = UserProfile.objects.exclude(user=request.user) ##modyfikujemy liste kandydatow
    return render(request, 'addVoting.html', {'regform': form,})
def fill_candidate_table():
    """Load the state json file, iterate over all the reps in the state
        for each rep, look up their id in the candidate json file
        use info in candidate json to fill out the State section of the candidate,
        for the other relations, query the already created tables for the values stored in json
    """
    for state in STATE_JSON.keys():
        reps = STATE_JSON[state]['representatives']
        for rep in reps.keys():
            temp_candidate = Candidate(
                name=CANDIDATE_JSON[rep]['name'],
                dob=str(CANDIDATE_JSON[rep]['birthday']),
                job=CANDIDATE_JSON[rep]['position'],
                contact=CANDIDATE_JSON[rep]['contact'],
                poll=CANDIDATE_JSON[rep]['favorability'])
            candidate_state_query = State.query.filter(
                State.name == STATE_JSON[state]['name']).first()
            candidate_election_query = Election.query.filter(
                Election.name == CANDIDATE_JSON[rep]['election']).first()
            candidate_party = party_parser(CANDIDATE_JSON[rep]['party'])
            candidate_party_query = Party.query.filter(
                Party.name == candidate_party).first()
            temp_candidate.states = candidate_state_query
            temp_candidate.party = candidate_party_query
            temp_candidate.elections = candidate_election_query
            database.session.add(temp_candidate)
    database.session.commit()
Example #8
0
def add_candidate(request):

    if request.user.is_authenticated():
        user_id = request.user.id
        fname   = request.GET.get('fname')
        lname   = request.GET.get('lname')
        date    = request.GET.get('date')
        date    = date.replace('India Standard Time', 'IST')
        #jd_name = request.GET.get('jd').split('-')[0]
        jd = request.GET.get('jd')
        email   = request.GET.get('email')
        mobile  = request.GET.get('mobile')
        remarks = request.GET.get('remarks')
        if remarks:
            pass
        else:
            remarks = "New"
        date    = date_parser.parse(date.replace(' GMT ',' GMT+'))
        date    = date_parser.parse('-'.join(str(date).split('-')[:-1]))
        agent_id        = Agent.objects.filter(name_id = user_id).values_list('id', flat= True)[0]

        new_can = Candidate(jd_id = jd, location="",fname = fname,lname = lname,walk_in_date = date,email_id = email,
                  mobile_number = mobile,status_id = 21,agent_id = agent_id, remarks = remarks)
        try:
            new_can.save()
        except:
            traceback.print_exc()
            return HttpResponse("Duplicate Mobile number","1")
        data = {'status':'success'}

    else:
        data = {'status':'failed'}

    return HttpResponse(data)
Example #9
0
def main():
    recruiter_1 = Recruiter('Bon Jovi', '*****@*****.**', 20)
    programmer_1 = Programmer('Jason Stathem', '*****@*****.**', 50)
    programmer_2 = Programmer('Vin Diesel', '*****@*****.**', 60)
    candidate_1 = Candidate('John Snow', '*****@*****.**', 'Jaba-Java', 'trainee')
    candidate_2 = Candidate('Hodor', '*****@*****.**', 'Hodor', 'hodor')
    candidate_3 = Candidate('Groot', 'iamgroot@groot', '01001101 programmer', 'guardian of senior')
    vacancy_1 = Vacancy('Python')
    vacancy_2 = Vacancy('01001101 programmer')
Example #10
0
def main():
    recruiter1 = Recruiter('Natali', nata @ gmail.com, 20)
    programmer1 = Programmer('Alex', alex @ mail.ru, 50)
    programmer2 = Programmer('Roman', roman @ gmail.com, 60)
    candidate1 = Candidate('Vasil', vasyok @ gmail.com, 'Python')
    candidate2 = Candidate('Grisha', grigor @ rambler.ru, 'Python')
    candidate3 = Candidate('Katya', kate @ gmail.com, 'FrontEnd')
    vacancy1 = Vacancy('Python')
    vacancy2 = Vacancy('FrontEnd')
Example #11
0
def main():
    recruiter1 = Recruiter()
    programmer1 = Programmer()
    programmer2 = Programmer()
    candidate1 = Candidate()
    candidate2 = Candidate()
    candidate3 = Candidate()
    vacancy1 = Vacancy()
    vacancy2 = Vacancy()
Example #12
0
def lookup_candidates_by_id():
    log("Getting all candidates")
    fs = Candidate.all().fetch(100)
    candidates_by_id = {}
    c = 0
    while fs:
        log("  getting batch from " + str(c))
        for f in fs:
            c = c + 1
            candidates_by_id[str(f.key())] = f
        fs = Candidate.all().filter('__key__ >', fs[-1].key()).fetch(100)
    return candidates_by_id
def lookup_candidates_by_id():
    log("Getting all candidates")
    fs = Candidate.all().fetch(100)
    candidates_by_id = {}
    c = 0
    while fs:
        log("  getting batch from " + str(c))
        for f in fs:
            c = c + 1
            candidates_by_id[str(f.key())] = f
        fs = Candidate.all().filter('__key__ >', fs[-1].key()).fetch(100)
    return candidates_by_id
Example #14
0
def get_pythoner(request):

    if request.POST.get('name'):
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        #存储
        c = Candidate(name=name, email=email, phone=phone)
        c.save()
        return render_to_response('success.html', RequestContext(request))

    return render_to_response('reg.html', RequestContext(request))
Example #15
0
    def test_vote_percent(self):
        with test_database(test_db, [Race, Candidate], create_tables=True):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')
            data.load_updates('data/tests/update.json')

            candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR')
            candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR')
            candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR')

            self.assertEqual(candidate_4848.vote_percent(), Decimal('25.0')) 
            self.assertAlmostEqual(candidate_4642.vote_percent(), Decimal('33.333'), 3) 
            self.assertAlmostEqual(candidate_4979.vote_percent(), Decimal('41.667'), 3) 
Example #16
0
def bulk_update(request):
    first_name = request.get('fname')
    last_name  = request.get('lname')
    mobile     = request.get('mobile')
    mobile     = int(float(mobile))
    walkin_date= request.get('walkindate')
    jd_id      = request.get('jdid')
    jd_id      = int(float(jd_id))
    mail_id    = request.get('mailid')
    agent_id   = request.get('agentid')
    agent_id   = int(float(agent_id))
    new_can = Candidate(jd_id=jd_id, fname=first_name, lname=last_name, mobile_number=mobile, walk_in_date=walkin_date, email_id=mail_id, agent_id=agent_id, status_id=1, location='', remarks='New')
    new_can.save()
def post_candidate():
    try:
        body = request.get_json()
        print(body)
        c =Candidate()
        c.deserialize(body)
        session.add(c)
        session.commit()
        return jsonify(c.serialize())
    except Exception as e:
        print(e)
    # finally:
        session.rollback()
        return jsonify({'Response': 'Not created'}), 500
Example #18
0
def main():

    recr_1 = Recruiter('Vika', '*****@*****.**', 24)
    emp_2 = Programmer('Sophia', '*****@*****.**', 30,
                       ['Python', 'SQL', 'CSS', 'PostgreSQL'])
    emp_3 = Programmer('Vlad', '*****@*****.**', 500,
                       ['Python', 'GitHub', 'Java'])
    cand_1 = Candidate('Valentin Zal', '@gmail.com', ['SQL', 'Java'],
                       'English', 'Magister')
    cand_2 = Candidate('Valentin Zal', '@gmail.com', ['SQL', 'Java'],
                       'English', 'Magister')
    cand_3 = Candidate('Valentin Zal', '@gmail.com', ['SQL', 'Java'],
                       'English', 'Magister')
    vak_1 = Vacancy('Programmer', ['C++', 'C#'], 'Midle')
    vak_2 = Vacancy('Desiner', ['Figma', 'C#'], 'Midle')
Example #19
0
def _factory_election_data(websafe_election_key):
    """ Factory database with data from settings.py """
    # create or update election
    if websafe_election_key is not None:
        election_key = ndb.Key(urlsafe=websafe_election_key)
        election = election_key.get()
    else:
        election = Election()
    election.populate(**ELECTION_DATA)
    election_key = election.put()

    for pos_data_orig in POSITION_DATA:
        # avoid directly delete on setting objects
        pos_data = pos_data_orig.copy()
        position_data = pos_data['data']
        del pos_data['data']

        position_name = pos_data['name']
        position = Position.query(ancestor=election_key).\
            filter(Position.name == position_name).get()
        if position is None:
            logger.debug('creating new position entity')
            position_id = ndb.Model.allocate_ids(
                    size=1, parent=election_key)[0]
            position_key = ndb.Key(Position, position_id, parent=election_key)
            position = Position(key=position_key)

        position.populate(**pos_data)
        position_key = position.put()

        # remove all roles under position
        ndb.delete_multi(position.candidate_keys)

        # create all roles from data
        candidates = []
        for index, data_dict in enumerate(position_data):
            candidate_id = ndb.Model.allocate_ids(
                    size=1, parent=position_key)[0]
            candidate_key = ndb.Key(
                    Candidate, candidate_id, parent=position_key)
            candidate = Candidate(key=candidate_key)
            data_dict['voting_index'] = index
            candidate.populate(**data_dict)
            candidates.append(candidate)
        position.candidate_keys = ndb.put_multi(candidates)
        position.put()

    return "update all data successfully"
Example #20
0
 def parse(self):
     xpath_ = "//*[@id='ctl00_ContentPlaceHolder1_Search_List']/tbody/tr[@class!='gridviewheader']"
     # returns a list of parsed links containing the ids of candidate profile links
     tree = html.fromstring(self.page_content)
     body = tree.xpath(xpath_)
     candidates = []
     link_ids = []
     if body is None:
         logging.info('No body content found')
         return [
             (),
         ]
     for tr in body:
         try:
             js_id = tr.xpath('.//td/a/@id').pop()
             candidate_name = tr.xpath('.//td[2]/span/text()').pop()
             name = HumanName(candidate_name)
             candidate = Candidate(firstname=name.first,
                                   middlename=name.middle,
                                   lastname=name.last)
             candidates.append(candidate)
             link_ids.append(js_id)
         except Exception as e:
             logging.info(e)
     return [(cand, link_id) for cand, link_id in zip(candidates, link_ids)]
def post_candidate(db):
    reqdata = request.json

    if request.content_type != "application/json":
        response.status = 400
        return "invalid request, expected header-content_type: application/json"

    try:
        candidate = Candidate(**reqdata)
        db.add(candidate)
        db.commit()
    except sqlalchemy.exc.IntegrityError as e:
        logger.error(e)
        response.status = 400
        return e
    return json.dumps(candidate.as_dict())
Example #22
0
def insert(engine):
    fake = Faker('ru_RU')
    Session = sessionmaker(bind=engine)
    session = Session()

    for i in range(CANDIDATE_NUMBER):
        session.add(
            Candidate(id=i,
                      fio=fake.name(),
                      gender=random.choice(list(GenderEnum)),
                      birth=fake.date_this_decade(),
                      deputat=fake.pybool()))

    for i in range(POSITION_NUMBER):
        session.add(Position(id=i, name=fake.job()))
        session.add(
            PositionDetails(id=i,
                            staff_cat=random.choice(list(StaffCatEnum)),
                            salary=fake.pyint(),
                            position_id=i))

    for i in range(CANDIDATE_NUMBER * 2):
        session.add(
            Employee(id=i,
                     tab_num=fake.isbn10(),
                     candidate_id=(fake.pyint() % CANDIDATE_NUMBER),
                     position_id=(fake.pyint() % POSITION_NUMBER)))
    session.commit()
    def get_results(self):
        #r = requests.get(self.href)
        #data = r.text
        #reader = csv.DictReader(data.splitlines(), delimiter='\t')

        data = open('local_elections/WA/test_data/MediaResults.txt', 'r')
        reader = csv.DictReader(data, delimiter='\t')

        reader.next()  # Skip header now
        for row in reader:
            raw_candidate_name = row['BallotName']
            candidate_name_split = raw_candidate_name.split()
            candidate_first_name = candidate_name_split[0]
            candidate_last_name = ' '.join(candidate_name_split[1:])

            raw_candidate_party = row['PartyName']
            party_regex = re.compile("Prefers (\w+) Party")
            party_result = party_regex.findall(raw_candidate_party)
            party_name = ''
            party_abbreviation = ''
            if party_result:
                party_name = party_result[0]
                party_abbreviation = party_name[0].upper()

            p = Party(party_name, party_abbreviation)

            c = Candidate(candidate_first_name, candidate_last_name,
                          row['Votes'])

            r = Race(row['RaceName'], row['RaceJurisdictionTypeName'],
                     row['TotalBallotsCastByRace'])

            race, created = self.get_or_create_race(r)
            race.add_candidate(c)
Example #24
0
def wipe_status():
    """
    Blanks the status fields for congress and presidential races.
    """

    rq = Race.update(
        precincts_reporting=0,
        ap_called=False,
        ap_called_time=None,
        npr_called=False,
        npr_called_time=None
    )
    rq.execute()

    cq = Candidate.update(
        vote_count=0,
        ap_winner=False,
        npr_winner=False
    )
    cq.execute()

    sq = State.update(
        ap_call='u',
        ap_called_at=None,
        npr_call='u',
        npr_called_at=None,
        precincts_reporting=0,
        rep_vote_count=0,
        dem_vote_count=0
    )
    sq.execute()
    write_www_files()
Example #25
0
    def __init__(self, path):
        self.path = path

        i = 1
        with open(path) as f:
            for line in f:
                app.log('candidate: {}'.format(i), level=3)
                candidate_record = dict(
                    zip(self.keys, [x.strip() for x in line.split('|')]))
                app.log(candidate_record, level=5)

                try:
                    Candidate(**candidate_record)
                    if i % app.BATCH_SIZE == 0:
                        app.log('commit!', level=5)
                        pony.commit()
                except pony.core.CacheIndexError:
                    pass
                except pony.core.TransactionIntegrityError:
                    pass

                i += 1

        try:
            pony.commit()
        except pony.core.CacheIndexError:
            pass
        except pony.core.TransactionIntegrityError:
            pass
Example #26
0
async def menu(query: callback_query, state: FSMContext):
    if state:
        await state.finish()
    keyboard = InlineKeyboardMarkup()
    keyboard.add(
        InlineKeyboardButton(buttons.create_vacancy,
                             callback_data='create_vacancy'),
        # InlineKeyboardButton(buttons.find_vacancies, callback_data='find_vacancies')
    )
    vacancies = Vacancy.select().where(Vacancy.creator == User.get(
        User.chat_id == query.message.chat.id))
    if vacancies:
        keyboard.add(
            InlineKeyboardButton(buttons.placed_vacancies,
                                 callback_data='placed_vacancies'))

    candidate = Candidate.select().where(Candidate.user == User.get(
        User.chat_id == query.message.chat.id))
    for i in candidate:
        if i.status == 'Отправлено тестовое задание':
            keyboard.add(
                InlineKeyboardButton(
                    f'Тестовое - {i.vacancy.name}',
                    callback_data=f'send_test_task_solution_{i.vacancy.id}'))
    await query.message.answer(messages.menu, reply_markup=keyboard)
Example #27
0
def model_to_cadidate(model):
    if isinstance(model, Album):
        return Candidate(title=model.album,
                         artist=model.albumartist,
                         year=model.year)
    if isinstance(model, Item):
        return Candidate(title=model.title,
                         artist=model.artist,
                         year=model.year)
    if isinstance(model, AlbumMatch):
        return Candidate(title=model.info.album,
                         artist=model.info.artist,
                         year=model.info.year)
    if isinstance(model, TrackMatch):
        return Candidate(title=model.info.title,
                         artist=model.info.artist,
                         year=None)
Example #28
0
async def treatment_resume(candidate_id):
    candidate = Candidate.get(Candidate.id == candidate_id)
    required_key_skills = candidate.vacancy.key_skills
    preformed_key_skills = json.loads(
        candidate.resume_json)['key_skills']['skills']
    ratio = fuzz.WRatio(required_key_skills, preformed_key_skills)
    if ratio > 50:
        return True
    return False
Example #29
0
def chamber_call(chamber):
    from flask import request

    race_slug = request.form.get('race_slug', None)

    race = Race.get(Race.slug == race_slug)

    # Toggling accept AP call
    accept_ap_call = request.form.get('accept_ap_call', None)

    if accept_ap_call != None:
        if accept_ap_call.lower() == 'true':
            accept_ap_call = True
        else:
            accept_ap_call = False

    if race_slug != None and accept_ap_call != None:
        race.accept_ap_call = accept_ap_call
        race.save()

        if accept_ap_call == True:
            Candidate.update(npr_winner=False).where(
                Candidate.race == race).execute()

    # Setting NPR winner
    first_name = request.form.get('first_name', None)
    last_name = request.form.get('last_name', None)
    clear_all = request.form.get('clear_all', None)

    if race_slug != None and clear_all != None:
        if clear_all == 'true':
            Candidate.update(npr_winner=False).where(
                Candidate.race == race).execute()

            race.npr_called = False
            race.save()

    if race_slug != None and first_name != None and last_name != None:
        Candidate.update(npr_winner=False).where(
            Candidate.race == race).execute()

        Candidate.update(npr_winner=True).where(
            Candidate.race == race, Candidate.first_name == first_name,
            Candidate.last_name == last_name).execute()

        race.npr_called = True

        if race.accept_ap_call == False:
            if race.npr_called_time == None:
                race.npr_called_time = datetime.datetime.utcnow()

        race.save()

    return 'Success'
Example #30
0
async def start_handler(message: types.Message, state: FSMContext):
    if state:
        await state.finish()
    text = message.text.split(' ')
    if len(text) > 1:
        payload = decode_payload(text[1])
        vacancy_id = int(payload)
        if not message.from_user.username:
            await CheckUsername.payload.set()
            await state.update_data(payload=vacancy_id)
            await state.update_data(user_id=message.from_user.id)
            await set_username(message.chat.id)
            return
        user = User.get_or_none(User.chat_id == message.chat.id)
        if not user:
            user = User(username=message.from_user.username,
                        first_name=message.from_user.first_name,
                        second_name=message.from_user.last_name,
                        chat_id=message.chat.id)
            user.save()
        # await FindVacancy.name.set()
        await show_vacancy_pure(message.chat.id, vacancy_id)
    else:
        user = User.get_or_none(User.chat_id == message.chat.id)
        if not user:
            user = User(username=message.from_user.username,
                        first_name=message.from_user.first_name,
                        second_name=message.from_user.last_name,
                        chat_id=message.chat.id)
            user.save()
            await message.answer(messages.start_message)

        keyboard = InlineKeyboardMarkup()
        keyboard.add(
            InlineKeyboardButton(buttons.create_vacancy,
                                 callback_data='create_vacancy'),
            # InlineKeyboardButton(buttons.find_vacancies, callback_data='find_vacancies')
        )
        vacancies = Vacancy.select().where(Vacancy.creator == User.get(
            User.chat_id == message.chat.id))
        if vacancies:
            keyboard.add(
                InlineKeyboardButton(buttons.placed_vacancies,
                                     callback_data='placed_vacancies'))

        candidate = Candidate.select().where(Candidate.user == User.get(
            User.chat_id == message.chat.id))
        for i in candidate:
            if i.status == 'Отправлено тестовое задание':
                keyboard.add(
                    InlineKeyboardButton(
                        buttons.test_task.format(i.vacancy.name),
                        callback_data=f'send_test_task_solution_{i.vacancy.id}'
                    ))

        await message.answer(messages.menu, reply_markup=keyboard)
Example #31
0
def chamber_call(chamber):
    from flask import request

    race_slug = request.form.get('race_slug', None)

    race = Race.get(Race.slug == race_slug)

    # Toggling accept AP call
    accept_ap_call = request.form.get('accept_ap_call', None)

    if accept_ap_call != None:
        if accept_ap_call.lower() == 'true':
            accept_ap_call = True
        else:
            accept_ap_call = False

    if race_slug != None and accept_ap_call != None:
        race.accept_ap_call = accept_ap_call
        race.save()

        if accept_ap_call == True:
            Candidate.update(npr_winner=False).where(Candidate.race == race).execute()

    # Setting NPR winner
    first_name = request.form.get('first_name', None)
    last_name = request.form.get('last_name', None)
    clear_all = request.form.get('clear_all', None)

    if race_slug != None and clear_all != None:
        if clear_all == 'true':
            Candidate.update(npr_winner=False).where(Candidate.race == race).execute()

            race.npr_called = False
            race.save()

    if race_slug != None and first_name != None and last_name != None:
        Candidate.update(npr_winner=False).where(Candidate.race == race).execute()

        Candidate.update(npr_winner=True).where(
            Candidate.race == race,
            Candidate.first_name == first_name,
            Candidate.last_name == last_name
        ).execute()

        race.npr_called = True

        if race.accept_ap_call == False:
            if race.npr_called_time == None:
                race.npr_called_time = datetime.datetime.utcnow()

        race.save()

    return 'Success'
Example #32
0
    def test_update_calls(self):
        with test_database(test_db, [Race, Candidate]):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')
            data.load_calls('data/tests/calls.json')

            race = Race.get(Race.race_id == '38529-OR')
            candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR')
            candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR')
            candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR')

            self.assertTrue(race.is_called())
            self.assertTrue(race.ap_called)
            self.assertEqual(race.ap_called_time, datetime(2014, 9, 25, 17, 8, 14))
            self.assertEqual(race.get_called_time(), datetime(2014, 9, 25, 17, 8, 14))

            self.assertFalse(candidate_4848.ap_winner)
            self.assertFalse(candidate_4642.ap_winner)
            self.assertTrue(candidate_4979.ap_winner)
Example #33
0
def build_candidate(c):
    if isinstance(c, AlbumMatch):
        return Candidate(title=c.info.album,
                         artist=c.info.artist,
                         year=c.info.year,
                         percentage=int((1 - c.distance) * 100),
                         isAlbum=True,
                         albumtype=c.info.albumtype,
                         label=c.info.label,
                         country=c.info.country,
                         media=c.info.media)
    elif isinstance(c, TrackMatch):
        return Candidate(title=c.info.title,
                         artist=c.info.artist,
                         year=None,
                         percentage=int((1 - c.distance) * 100),
                         isAlbum=False)
    else:
        return None
Example #34
0
    def test_add_candidate(self):
        """Test the public ``add_candidate'' function provided by the
        Constituency() class.
        """

        con = Constituency("test")
        con2 = Constituency("test2")

        party1 = Party("party1")
        party2 = Party("party2")
        party3 = Party("party3")

        candidate1 = Candidate("candidate1", party1, con)
        candidate2 = Candidate("candidate2", party2, con)
        candidate3 = Candidate("candidate3", party3, con2)
        candidate4 = Candidate("candidate4", party2, con)

        con.add_candidate(candidate1)
        self.assertTrue(candidate1 in con.candidates)
        self.assertEqual(len(con.candidates), 1)

        # attempt to add a candidate twice
        with self.assertRaises(AssertionError):
            con.add_candidate(candidate1)
        self.assertEqual(len(con.candidates), 1)
        self.assertEqual(len(con.parties), 1)

        con.add_candidate(candidate2)
        self.assertTrue(candidate1 in con.candidates)
        self.assertTrue(candidate2 in con.candidates)
        self.assertEqual(len(con.candidates), 2)
        self.assertEqual(len(con.parties), 2)

        # attempt to add a candidate with the wrong constituency
        with self.assertRaises(AssertionError):
            con.add_candidate(candidate3)
        self.assertEqual(len(con.candidates), 2)

        # attempt to add a candidate with the same party
        with self.assertRaises(AssertionError):
            con.add_candidate(candidate4)
        self.assertEqual(len(con.candidates), 2)
    def add_candidate_profile(payload):
        try:
            body = request.get_json()

            new_name = body.get('name')
            new_surname = body.get('surname')
            new_date_of_birth = body.get('date_of_birth')
            new_city = body.get('city')
            new_region = body.get('region')
            new_email = body.get('email')
            new_phone = body.get('phone')
            new_facebook_link = body.get('facebook_link')
            new_linkedin_link = body.get('linkedin_link')
            new_address = body.get('address')
            new_work_experience = body.get('work_experience')
            new_education = body.get('education')
            new_seeking_job = body.get('seeking_job')
            new_desired_salary = body.get('desired_salary')
            new_desired_industry = body.get('desired_industry')

            candidate = Candidate(name=new_name,
                                  surname=new_surname,
                                  date_of_birth=new_date_of_birth,
                                  city=new_city,
                                  region=new_region,
                                  email=new_email,
                                  phone=new_phone,
                                  facebook_link=new_facebook_link,
                                  linkedin_link=new_linkedin_link,
                                  address=new_address,
                                  work_experience=new_work_experience,
                                  education=new_education,
                                  seeking_job=new_seeking_job,
                                  desired_salary=new_desired_salary,
                                  desired_industry=new_desired_industry)

            candidate.insert()
            return jsonify({'success': True})
        except Exception:
            print(sys.exc_info())
            abort(422)
Example #36
0
def main():
    vasilyev = Programmer(
        ['js', 'python', 'make good coffee'],
        'Vasya',
        'Vasilyev',
        '*****@*****.**',
        '+322223322',
        32,
    )

    gunko = Programmer(['js', 'python', 'kubernetes', 'docker'], 'petr',
                       'gunko', '*****@*****.**', '+322227772', 30)

    tatarinova = Recruiter('Lena', 'Tatarinova', '*****@*****.**', '+372223322',
                           32)
    gagarin = Candidate('Yuriy Gagarin', '*****@*****.**',
                        ['spaceman', 'pilot'], 'pilot', 100)
    peterson = Candidate('Jim Peterson', 'jim_peterson.gmail.com',
                         ['python', 'js'], 'python', 79)
    vorghol = Candidate('Anastasia Vorghol', 'vorghol_a1952.gmail.com',
                        ['python', 'js'], 'js', 68)
    js_junior = Vacancy('JS Junior', 'js', 45)
    python_middle = Vacancy('Python Middle', 'python', 60)

    print(vasilyev, gunko, tatarinova, sep='\n')
    print(f'{vasilyev.name} salary: {vasilyev.check_salary()}')
    print(vasilyev.surname, 'said:', vasilyev.work())
    print(vasilyev > tatarinova)
    print(vasilyev >= tatarinova)
    print(vasilyev.tech_stack)
    print(gunko)
    print(vasilyev < gunko)
    print(vasilyev + gunko)
    print(js_junior)
    print(peterson)
    print(vorghol)
    print(gagarin)
    print(python_middle)
    print(vasilyev.about_person)
    data = Candidate.make_candidates_from_csv()
    [print(i) for i in data]
Example #37
0
File: app.py Project: Allinka1/OOP
def main():
    employee_1 = Programmer('Alinka', '*****@*****.**', 100,
                            ['Python', 'HTML', 'CSS', 'PostgreSQL'])
    employee_2 = Programmer('Nikita', '*****@*****.**', 500,
                            ['Python', 'GitHub'])
    recruiter_1 = Recruiter('Dasha', '*****@*****.**', 100)
    candidate_1 = Candidate('Maria Klukina', '*****@*****.**',
                            ['Python', 'Java Script'], 'Python', 'middle')
    candidate_2 = Candidate('Dima Mironin', '*****@*****.**',
                            ['Ruby', 'C#', 'Java'], 'Ruby', 'senior')
    candidate_3 = Candidate('Vladislav Limov', '*****@*****.**',
                            ['HTML', 'CSS', 'C++'], 'C++', 'junior')
    vacancy_1 = Vacancy('Python Developer', 'Python', 'middle')
    vacancy_2 = Vacancy('Ruby Developer', 'Ruby', 'senior')
    # candidate_1.work()
    # print(recruiter_1.full_info)
    # print(employee_1.full_info)
    # print(Candidate.from_csv('candidates.csv'))
    print(
        Candidate.from_csv(
            'https://bitbucket.org/ivnukov/lesson2/raw/master/candidates.csv'))
Example #38
0
def add_candidate():
    candidate_name = request.form['candidate_name']

    if not candidate_name:
        flash("Please enter a Candidate Name.")
        return render_template("add-candidate.html", candidates=candidates)
    else:
        newCandidate = Candidate(candidate_name)
        db.session.add(newCandidate)
        db.session.commit()
        flash("Candidate added to Database.")
        return redirect("/add-candidates")
Example #39
0
def _election_health_check(websafe_election_key):
    """ Checks election vote integrity """
    election_key = ndb.Key(urlsafe=websafe_election_key)
    election = election_key.get()
    if not election:
        return "no such election %s" % websafe_election_key

    all_user_query = VotingUser.query(ancestor=election_key)

    # aggregate votes
    dirty = []
    results = {}
    for user in all_user_query.iter():
        student_id = user.student_id
        clean_student_id = _clean_id(student_id)
        if student_id != clean_student_id:
            dirty.append(student_id)
            continue

        for vote_key in user.votes:
            try:
                results[vote_key] += 1
            except KeyError:
                results[vote_key] = 1

    # save results as readable json string
    readable_results = {}
    for candidate_key, count in results.iteritems():
        candidate = candidate_key.get()
        readable_results[candidate.name] = {'calc_cnt': count}

    # get vote count in database
    candidate_query = Candidate.query(ancestor=election_key)
    for candidate in candidate_query.iter():
        name = candidate.name
        count = candidate.num_votes
        try:
            readable_results[name]['db_cnt'] = count
        except KeyError:
            readable_results[name] = {'db_cnt': count, 'calc_cnt': 0}

    diff_data = {}
    for name, data in readable_results.iteritems():
        if data['calc_cnt'] != data['db_cnt']:
            diff_data[name] = data['db_cnt'] - data['calc_cnt']

    message = {
        'raw_data': readable_results,
        'diff_data': diff_data,
        'dirty': dirty
    }
    json_str = json.dumps(message)
    return json_str
Example #40
0
    def test_load_candidates(self):
        with test_database(test_db, [Race, Candidate]):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')

            candidate = Candidate.select().get()

            self.assertEqual(candidate.first_name, 'Aelea')
            self.assertEqual(candidate.last_name, 'Christofferson')
            self.assertEqual(candidate.party, 'Dem')
            self.assertIsNotNone(candidate.race)
            self.assertEqual(candidate.candidate_id, '4848-OR')
Example #41
0
    def test_update_calls(self):
        with test_database(test_db, [Race, Candidate]):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')
            data.load_calls('data/tests/calls.json')

            race = Race.get(Race.race_id == '38529-OR')
            candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR')
            candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR')
            candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR')

            self.assertTrue(race.is_called())
            self.assertTrue(race.ap_called)
            self.assertEqual(race.ap_called_time,
                             datetime(2014, 9, 25, 17, 8, 14))
            self.assertEqual(race.get_called_time(),
                             datetime(2014, 9, 25, 17, 8, 14))

            self.assertFalse(candidate_4848.ap_winner)
            self.assertFalse(candidate_4642.ap_winner)
            self.assertTrue(candidate_4979.ap_winner)
Example #42
0
    def test_load_candidates(self):
        with test_database(test_db, [Race, Candidate]):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')

            candidate = Candidate.select().get()

            self.assertEqual(candidate.first_name, 'Aelea')
            self.assertEqual(candidate.last_name, 'Christofferson')
            self.assertEqual(candidate.party, 'Dem')
            self.assertIsNotNone(candidate.race)
            self.assertEqual(candidate.candidate_id, '4848-OR')
Example #43
0
 def _show(self, user):
   data = {
     'user': user,
     'devices': [{
       'id': device.key.id(),
       'added': device.added.strftime('%c'),
       'make': device.make,
       'model': device.model,
       'zip': device.home_zip5,
     } for device in models.Device.by_owner(user)],
     'registration_id': Candidate.acquire_id(user)
   }
   template = JINJA_ENVIRONMENT.get_template('templates/manage.html')
   self.response.write(template.render(data))
Example #44
0
 def _show(self, user):
     data = {
         "user": user,
         "devices": [
             {
                 "id": device.key.id(),
                 "added": device.added.strftime("%c"),
                 "make": device.make,
                 "model": device.model,
                 "zip": device.home_zip5,
             }
             for device in models.Device.by_owner(user)
         ],
         "registration_id": Candidate.acquire_id(user),
     }
     template = JINJA_ENVIRONMENT.get_template("templates/manage.html")
     self.response.write(template.render(data))
Example #45
0
def parse_house(row):
    race_data = dict(zip(RACE_FIELDS, row[:len(RACE_FIELDS)]))
    race_data['slug'] = u'%s%s' % (
        race_data['state_postal'].lower(), race_data['district_id'])
    candidate_count = (len(row) - len(RACE_FIELDS)) / len(CANDIDATE_FIELDS)

    rq = Race.update(
        precincts_reporting=race_data['precincts_reporting'],
    ).where(Race.slug == race_data['slug'])
    rq.execute()

    i = 0

    while i < candidate_count:
        first_field = len(RACE_FIELDS) + (i * len(CANDIDATE_FIELDS))
        last_field = first_field + len(CANDIDATE_FIELDS)

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

        if candidate_data['ap_winner'] == 'X':
            candidate_data['ap_winner'] = True
        else:
            candidate_data['ap_winner'] = False

        if candidate_data['incumbent'] == "1":
            candidate_data['incumbent'] = True
        else:
            candidate_data['incumbent'] = False

        if candidate_data['ap_winner'] == True:
            rq = Race.update(
                ap_called=True,
                ap_called_time=datetime.datetime.now(tz=pytz.utc))\
            .where(Race.slug == race_data['slug'], Race.ap_called == False)
            rq.execute()

        cq = Candidate.update(
                ap_winner=candidate_data['ap_winner'],
                vote_count=candidate_data['vote_count']
            ).where(
            Candidate.npid == candidate_data['npid'])
        cq.execute()

        i += 1
Example #46
0
def _generate_json(house):
    """
    Generates JSON from rows of candidates and a house of congress.
    * House is a two-tuple ('house', 'H'), e.g., URL slug and DB representation.
    """
    data = {}
    data['balance_of_power'] = produce_bop_json()
    data['results'] = []

    for timezone in settings.CLOSING_TIMES:
        timezone_dict = {}
        timezone_dict['gmt_epoch_time'] = time.mktime(timezone.timetuple())
        timezone_dict['districts'] = []

        races = Race.select().where(
            Race.office_code == house[1],
            Race.poll_closing_time == timezone,
            Race.featured_race == True)

        for district in races:

            # Set up the race information.
            district_dict = {}
            district_dict['district'] = u'%s %s' % (
                district.state_postal,
                district.district_id)
            district_dict['sorter'] = (district.state_postal, district.district_id)
            district_dict['candidates'] = []
            district_dict['district_slug'] = district.slug

            # Percent reporting.
            district_dict['percent_reporting'] = district.percent_reporting()

            # Call times.
            district_dict['called_time'] = None
            if district.accept_ap_call == True:
                district_dict['called'] = district.ap_called
                if district.ap_called_time != None:
                    call_time = utc.normalize(utc.localize(district.ap_called_time))
                    call_time = call_time.astimezone(eastern)
                    district_dict['called_time'] = call_time.strftime('%I:%M').lstrip('0')
            elif district.accept_ap_call == False:
                district_dict['called'] = district.npr_called
                if district.npr_called_time != None:
                    call_time = utc.normalize(utc.localize(district.npr_called_time))
                    call_time = call_time.astimezone(eastern)
                    district_dict['called_time'] = call_time.strftime('%I:%M').lstrip('0')

            # Status field.
            if district_dict['called'] == True:
                district_dict['status_tag'] = 'Called time.'
                district_dict['status'] = district_dict['called_time']
            else:
                if district.precincts_reporting > 0:
                    district_dict['status_tag'] = 'Percent reporting.'
                    pct = district.percent_reporting()

                    if pct < 1:
                        district_dict['status'] = u'< 1%'
                    elif pct > 99 and pct < 100:
                        district_dict['status'] = u'99%'
                    else:
                        district_dict['status'] = u'%.0f%%' % district.percent_reporting()
                else:
                    district_dict['status_tag'] = 'No precincts reporting.'
                    if district.total_votes() > 0:
                        district_dict['status'] = u'< 1%'
                    else:
                        district_dict['status'] = u'&nbsp;'
            # Flips.
            district_dict['swap'] = False
            if district.has_flipped:
                if district.flipped[0]:
                    district_dict['swap'] = True

            # Candidates.
            for candidate in Candidate.select().where(Candidate.race == district):
                    if (
                    candidate.party == u'Dem'
                    or candidate.party == u'GOP'
                    or candidate.first_name == 'Angus'
                    or candidate.first_name == 'Bernie'):
                        candidate_dict = candidate._data

                        if (candidate_dict['party'] == 'NPA'
                        or candidate_dict['party'] == 'Ind'):
                            candidate_dict['party'] = 'Alt'

                        candidate_dict['vote_percent'] = candidate.vote_percent()
                        candidate_dict['winner'] = False

                        if district.accept_ap_call == True:
                            if candidate_dict['ap_winner'] == True:
                                candidate_dict['winner'] = True
                        else:
                            if candidate_dict['npr_winner'] == True:
                                candidate_dict['winner'] = True

                        # By default, all candidates are not swaps.
                        candidate_dict['swap'] = False

                        # First, check if there's a winner. Can't have a swap
                        # without a winner.
                        if candidate_dict['winner'] == True:

                            # Hardcoding an edge-case for IA3 and OH16.
                            if district_dict['district_slug'] == 'ia3':
                                candidate_dict['swap'] = True

                            if district_dict['district_slug'] == 'oh16':
                                candidate_dict['swap'] = True

                            # Second, check if this is the incumbent. Can't have
                            # an incumbent win AND this be a swap.
                            if candidate_dict['incumbent'] == False:

                                # The first swap type is the easiest.
                                # If there IS an incumbent AND this candidate
                                # isn't the incumbent, then there's a swap.

                                if district.has_incumbents() == True:
                                    candidate_dict['swap'] = True

                                # The second swap type is slightly harder.
                                # If there isn't an incumbent but there IS a
                                # predicted winner (e.g., seat held by a party)
                                # and this candidate's party doesn't match the
                                # prediction, then there's a swap.
                                else:
                                    if candidate_dict['party'] == 'GOP':
                                        party = u'republicans'
                                    elif candidate_dict['party'] == 'Dem':
                                        party = u'democrats'
                                    else:
                                        party = u'other'

                                    if district.flipped[0]:
                                        if party == district.flipped[0]:
                                            candidate_dict['swap'] = True

                        district_dict['called_time'] = None

                        if candidate.last_name != 'Dill':
                            district_dict['candidates'].append(
                                candidate_dict)

            district_dict['candidates'] = sorted(
                district_dict['candidates'],
                key=lambda candidate: candidate['party'])

            timezone_dict['districts'].append(district_dict)

        timezone_dict['districts'] = sorted(
            timezone_dict['districts'],
            key=lambda district: district['sorter'])

        if races.count() > 1:
            data['results'].append(timezone_dict)

    return json.dumps(data)
Example #47
0
def house(house, featured=None):
    """
    Read/update list of house candidates.
    """

    house_slug = u'H'
    if house == 'senate':
        house_slug = u'S'

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

    if request.method == 'GET':

        # Get all of the candidates that match this race which are either
        # Republicans or Democrats or have the first name Angus or Bernie and
        # we ignore the Democrat in the Maine race.
        candidates = Candidate\
            .select()\
            .join(Race)\
            .where(
                Race.office_code == house_slug,
                (Candidate.party == 'Dem') | (Candidate.party == 'GOP') | (Candidate.first_name == 'Angus') | (Candidate.first_name == 'Bernie'),
                Candidate.last_name != 'Dill')

        if is_featured:
            candidates = candidates.where(Race.featured_race == True)

        candidates = candidates.order_by(
                Race.state_postal.desc(),
                Race.district_id.asc(),
                Candidate.party.asc())

        race_count = Race.select().where(Race.office_code == house_slug)

        if is_featured:
            race_count = race_count.where(Race.featured_race == True)

        context = {
            'candidates': candidates,
            'count': race_count.count(),
            'house': house,
            'settings': settings
        }

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

    # Alternately, what if someone is POSTing?
    if request.method == 'POST':

        # Everything needs a race slug.
        race_slug = request.form.get('race_slug', None)
        race = Race.select().where(Race.slug == race_slug).get()

        # 1.) Perhaps we're trying to set the accept_ap_call flag on some races?
        accept_ap_call = request.form.get('accept_ap_call', None)

        if accept_ap_call != None:
            if accept_ap_call.lower() == 'true':
                accept_ap_call = True
            else:
                accept_ap_call = False

        if race_slug != None and accept_ap_call != None:
            aq = Race.update(accept_ap_call=accept_ap_call).where(Race.slug == race.slug)
            aq.execute()

            if accept_ap_call == True:
                rq = Candidate.update(npr_winner=False).where(Candidate.race == race)
                rq.execute()

        # 2.) Perhaps we're trying to set an NPR winner?
        first_name = request.form.get('first_name', None)
        last_name = request.form.get('last_name', None)
        clear_all = request.form.get('clear_all', None)

        if race_slug != None and clear_all != None:
            if clear_all == 'true':
                rq = Candidate.update(npr_winner=False).where(Candidate.race == race)
                rq.execute()

                rq2 = Race.update(npr_called=False).where(Race.slug == race_slug)
                rq2.execute()

        if race_slug != None and first_name != None and last_name != None:

            rq = Candidate.update(npr_winner=False).where(Candidate.race == race)
            rq.execute()

            cq = Candidate.update(npr_winner=True).where(
                Candidate.race == race,
                Candidate.first_name == first_name,
                Candidate.last_name == last_name)
            cq.execute()

            race_update = {}
            race_update['npr_called'] = True
            if race.accept_ap_call == False:
                if race.npr_called_time == None:
                    race_update['npr_called_time'] = datetime.datetime.utcnow()

            rq2 = Race.update(**race_update).where(Race.slug == race_slug)
            rq2.execute()

        # 3.) Perhaps we're trying to set this as a featured race?
        featured_race = request.form.get('featured_race', None)
        if featured_race:
            if featured_race.lower() == 'true':
                featured_race = True
            else:
                featured_race = False

        if race_slug != None and featured_race != None:
            fq = Race.update(featured_race=featured_race).where(Race.slug == race_slug)
            print fq.execute()

        if settings.DEBUG:
            o.write_house_json()
            o.write_senate_json()
            o.write_bop_json()

        # TODO
        # Return a 200. This is probably bad.
        # Need to figure out what should go here.
        return "Success."