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')
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')
def main(): recruiter1 = Recruiter() programmer1 = Programmer() programmer2 = Programmer() candidate1 = Candidate() candidate2 = Candidate() candidate3 = Candidate() vacancy1 = Vacancy() vacancy2 = Vacancy()
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')
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()
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)
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 })
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})
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 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 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 __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
async def recieve_resume(message: types.Message, state: FSMContext): if message.document.mime_type == 'application/pdf': file_id = message.document.file_id file_path = settings.resumes_path_base + str(file_id) + '.pdf' await bot.download_file_by_id(file_id, file_path) text_pdf = parser_from_pdf.extract_text_from_pdf(file_path) json_obj = json.dumps(text_pdf) async with state.proxy() as s: vacancy_id = s['id'] candidate = Candidate(user=User.get(User.chat_id == message.chat.id), vacancy=Vacancy.get(Vacancy.id == vacancy_id), resume_file_id=file_id, resume_json=json_obj, status='Резюме обрабатывается') candidate.save() await message.answer(messages.resume_in_treatment) treatment_result = await treatment_resume(candidate.id) if treatment_result: candidate.status = 'Резюме одобрено' candidate.save() await message.answer(messages.resume_is_good) vacancy = Vacancy.get(Vacancy.id == vacancy_id) if vacancy.test_task: keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton(buttons.menu, callback_data='menu')) await bot.send_document(message.chat.id, open(vacancy.test_task, 'rb'), caption=messages.here_is_task, reply_markup=keyboard) candidate.status = 'Отправлено тестовое задание' candidate.save() await state.finish() else: keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton(buttons.menu, callback_data='menu')) await message.answer(messages.there_is_no_task, reply_markup=keyboard) candidate.status = 'Контакты отправлены работодателю' candidate.save() # resume = json.loads(candidate.resume_json)['info'] await bot.send_message( candidate.vacancy.creator.chat_id, messages.user_without_task.format(candidate.user.username, candidate.vacancy.name)) await state.finish() else: candidate.status = 'Резюме отклонено' candidate.save() await message.answer(messages.resume_is_bad) await FindVacancy.id.set() else: keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton(buttons.back, callback_data='back_to_find_vacancies')) await message.answer(messages.something_wrong, reply_markup=keyboard)
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)
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
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 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]
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")
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'))
def test_election(self): """Test the public ``add_candidate'' function provided by the Election() class. """ el = Election() con1 = Constituency("test") con2 = Constituency("test2") party1 = Party("party1") party2 = Party("party2") candidate1 = Candidate("candidate1", party1, con1) candidate2 = Candidate("candidate2", party2, con1) candidate3 = Candidate("candidate3", party2, con2) el.add_candidate(candidate1) self.assertTrue(candidate1 in el.candidates) self.assertTrue(party1 in el.parties) self.assertTrue(con1 in el.constituencies) with self.assertRaises(AssertionError): el.add_candidate(candidate1) el.add_candidate(candidate2) self.assertTrue(candidate2 in el.candidates) self.assertTrue(party1 in el.parties) self.assertTrue(con1 in el.constituencies) self.assertEqual(len(el.candidates), 2) self.assertEqual(len(el.parties), 2) self.assertEqual(len(el.constituencies), 1) el.add_candidate(candidate3) self.assertTrue(candidate3 in el.candidates) self.assertTrue(party2 in el.parties) self.assertTrue(con2 in el.constituencies) self.assertEqual(len(el.candidates), 3) self.assertEqual(len(el.parties), 2) self.assertEqual(len(el.constituencies), 2)
def _create_or_add_assignmentgroup(self, group_name, parentnode, extras): if AssignmentGroup.objects.filter(parentnode=parentnode, name=group_name).count() == 1: group = AssignmentGroup.objects.get(parentnode=parentnode, name=group_name) else: group = AssignmentGroup(parentnode=parentnode, name=group_name) try: group.full_clean() group.save() except ValidationError as e: raise ValueError("Assignmentgroup not created!: {}".format(e)) # add the extras (only admins allowed in subject) for candidate in extras['candidate']: try: candidate_name, cid = candidate.split(';', 1) except ValueError: candidate_name = candidate cid = None group.candidates.add( Candidate(student=self._create_or_add_user(candidate_name))) cand = group.candidates.order_by('-id')[0] # cand.candidate_id = cid if cid != None else str(cand.student.id) cand.candidate_id = cid cand.full_clean() cand.save() for examiner in extras['examiner']: group.examiners.create(user=self._create_or_add_user(examiner)) for tag in extras['tags']: group.tags.create(tag=tag) group.full_clean() group.save() vars(self)[parentnode.parentnode.parentnode.short_name + '_' + # subject_ parentnode.parentnode.short_name + '_' + # period_ parentnode.short_name + '_' + # assignment_ group_name] = group # # create the default deadline, deadline0, variable # vars(self)[parentnode.parentnode.parentnode.short_name + '_' + # subject_ # parentnode.parentnode.short_name + '_' + # period_ # parentnode.short_name + '_' + # assignment_ # group_name + '_deadline0'] = group.deadlines.all()[0] return group
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
def get_or_add_candidate(self, candidate): try: query_result = self.session.query(Candidate).filter_by( FilerId=candidate['FilerId'], Firstname=candidate['Firstname'], Lastname=candidate['Lastname']).first() if query_result: return query_result.CandidateId candidate = Candidate(**candidate) self.session.add(candidate) self.session.commit() return candidate.CandidateId except Exception as e: self.session.rollback() logging.info(e)
def test_add_winner(self): """Test the public ``add_winner'' function provided by the Outcome() class. """ con = Constituency("test") con2 = Constituency("test2") party1 = Party("party1") party2 = Party("party2") candidate1 = Candidate("candidate1", party1, con) candidate2 = Candidate("candidate2", party2, con2) outcome = Outcome() outcome.add_winner(candidate1) self.assertEqual(len(outcome.winners), 1) self.assertTrue(candidate1 in outcome.winners) # attempt to add the same candidate with self.assertRaises(AssertionError): outcome.add_winner(candidate1)
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())
def parse_text(self, text: str) -> List[Mention]: if not isThreadAttachedToJVM(): attachThreadToJVM() parsed_result = self.solve_conflict( self.format_output(self.parser.parseText(text), text)) mention_list = [] # type: List[Mention] for item in parsed_result: mention = Mention(int(item[0]), int(item[1]), item[2]) mention.candidates = [] for cand_id in item[3]: candidate = Candidate(cand_id) mention.add_candidate(candidate) mention.parse_from = self.param_config.name mention_list.append(mention) return mention_list
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)
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 run_STV(ballots, numSeats, candidates): c = [] b = [] for i in candidates: c.append(Candidate(i)) ba = ballots[0] for ba in ballots: tempb = [] for i in range(int(max(ba))): for j in range(len(ba)): if ba[j] == str(i + 1): tempb.append(c[j]) # print(ba) # print(tempb) # print(Ballot(ranked_candidates = tempb)) # print("======================================") b.append(Ballot(ranked_candidates=tempb)) election_result = multiple_seat_ranking_methods.single_transferable_vote( c, b, number_of_seats=numSeats) return election_result
def save_candidate(): try: print "save_candidate(): :", request.form user_id = request.form['user_id'] name = request.form['name'] email = request.form['email'] pswd = request.form['pswd'] age = request.form['age'] phone = request.form['phone'] address = request.form['address'] gender = request.form['gender'] encodepassword = md5.new(pswd).hexdigest() # save candidate in db candidate = Candidate(user_id, name, email, encodepassword, age, phone, address, gender) db.session.add(candidate) db.session.commit() except Exception as exp: print "save_candidate(): : Got Exception: %s" % exp print(traceback.format_exc()) return "Candidate Data Saved"