def test_list_user_story(self): person_1 = Person("Ilahiya", "Musayeva", '123421') person_2 = Person("Amar", "Musayev", "265571") pb = PhoneBook() pb.add_person(person_1) pb.add_person(person_2) keyword = "show_list" List = ListUserStory(pb) resualt = List.run(keyword) return self.assertTrue([person_1, person_2], resualt)
def test_get_ids_by_last_name(): mock_store = mockredis.mock_redis_client(strict=True) person_index = PersonIndex(mock_store) person1 = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person1) person2 = Person(2, 'first', 'last', 30, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person2) ids = person_index.get_ids_by_last_name(person1.last_name) assert ids is not None assert str(1) in ids assert str(2) in ids
async def get_by_ids(self, person_ids: List[UUID]) -> Optional[List[Person]]: """ Возвращает персоны по списку id. """ persons = OrderedDict.fromkeys(person_ids, None) # проверяем есть ли полученные жанры в кеше по их ID for person_id in persons.keys(): data = await self.cache.get(person_id) if data: persons[person_id] = Person.parse_raw(data) # не найденные в кеше персоны запрашиваем в эластике и кладём в кеш not_found = [ person_id for person_id in persons.keys() if persons[person_id] is None ] if not_found: docs = await self.storage.get_by_ids(self._index, not_found) for doc in docs: person = Person(**doc) await self.cache.put(person.id, person.json()) persons[person.id] = person return list(persons.values())
def check_for_first(self, person): print("--Checking for first_name--") self.first_name = person[0].strip() self.establish_new_connection() try: self.cursor.execute(queries.check_for_person_first( self.first_name)) except Exception as e: print("Exception has occured 99: " + str(e)) result = self.cursor.fetchall() person_to_check = 0 list_result = [list(i) for i in result] if self.check_exists_result(list_result): person = list_result[0] person_dictionary = self.create_person_dict(person) self.person = Person(person_dictionary) user_input = input( f"Oh is this {self.person.first_name} {self.person.last_name}? " ) word_or_phrase = user_input.split()[0] if Word_Manager.is_confirmation( word_or_phrase) or Phrase_Manager.is_confirmation( word_or_phrase): self.update_latest_interaction(self.person) else: return False else: return False
def investor_person(): """ Display investors subscription for a person form """ if request.method == "POST": info = request.form obj = User() obj.username = info['username'] obj.email = info['email'] obj.psswd = info['password'] obj.status = "active" data = Person() data.user = obj.id data.first_name = info['fname'] data.last_name = info['lname'] data.type_id = info['tipo-identificacion'] data.number_identification = info['numberID'] data.born_date = info['date'] inv = Investor() inv.investor = data.id mka = storage mka.reload() mka.new(obj) mka.save() mka.new(data) mka.save() mka.new(inv) mka.save() mka.close() return redirect('/profile-investor/{}'.format(obj.id), code=302) return render_template('signup_naturalperson.html', id=str(uuid.uuid4()))
def investor_company(): """ Display investors subscription for a company form """ if request.method == "POST": info = request.form print("hola, cómo estás?") print(info) obj = User() obj.username = info['username'] print(obj.username) obj.email = info['email'] obj.psswd = info['password'] obj.status = "active" data = Person() data.user = obj.id data.name_company = info['ncompany'] data.business_name = info['bname'] data.tradename = info['tname'] data.legal_status = info['lstatus'] data.legal_repre_full_name = info['lrepre_name'] data.legal_repre_type_id = info['tipo-identificacion'] data.legal_repre_number_id = info['lrepre_id'] data.born_date = info['date'] inv = Investor() inv.investor = data.id mka = storage mka.reload() mka.new(obj) mka.save() mka.new(data) mka.save() mka.new(inv) mka.save() mka.close() return redirect('/profile-investor/{}'.format(obj.id), code=302) return render_template('signup_company.html', id=str(uuid.uuid4()))
def test_with_person(self): person_a = Person("User", "1", None) person_b = Person("User", "2", person_a) print_depth({ 'key1': 1, 'key2': { 'key3': 1, 'key4': { 'key5': 4, 'user': person_b } } }) value = self.capturedOutput.getvalue() value = value.strip().split('\n')[-1] self.assertEqual(value, 'father 5', "Should pass with person")
def generate(population=100): print("Genereerin {} inimest".format(population)) print("Loen andmed sisse ...") model = get_model() print("Andmed loetud, hakkan genereerima") data = [] first_time = True for i in range(population): start_date = date(1920, 1, 1) end_date = date(2020, 1, 1) time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_number_of_days = random.randrange(days_between_dates) random_date = start_date + timedelta(days=random_number_of_days) person = Person(i + 1, random.choice(['M', 'F']), random_date) person.live(model) data.append(person) print(i + 1) if (i + 1) % 1000 == 0: print("Lisan andmed faili") save_into_file(data, first_time) first_time = False data = [] if len(data) != 0: print("Lisan andmed faili") save_into_file(data, first_time)
def createListOfPpl(self, usr, num): i = 0 usr.listOfPpl = [] while i < num: usr.listOfPpl.append(Person(i)) i += 1 logging.info(len(usr.listOfPpl))
def test_get_ids_by_last_name_none(): mock_store = mockredis.mock_redis_client(strict=True) person_index = PersonIndex(mock_store) person = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person) ids = PersonIndex(mock_store).get_ids_by_last_name('some_other_id') assert len(ids) is 0
def create_person(name, sid): person = Person(person_id=Game.person_id, name=name, position=flask_app.config.get('SPAWN')) Game.person_id += 1 Game.people.append(person) Game.sid_to_person[sid] = person return person
def createNewPerson(self, name, lastName, phone, login, password, calification): self.lastPersonId += 1 person = Person(self.lastOrderId, name, lastName, phone, login, password, 0, "no eny role") jsonString = json.dumps(person) with open("Person" + str(person.id) + ".txt", "w") as text_file: text_file.write(jsonString) return person
def add_by_user_loyalty_id(user_id, loyalty_id): answer = -1 loyalty = PaymentLoyalty.query.filter_by( id=loyalty_id).first() if not loyalty: return False user_wallets = PaymentWallet.query.filter_by(user_id=user_id).all() for wallet in user_wallets: wl = WalletLoyalty.query.filter_by( loyalty_id=loyalty_id, status=WalletLoyalty.STATUS_ON, wallet_id=wallet.id).first() if not wl: continue person = Person.query.filter_by( firm_id=loyalty.firm_id, payment_id=wallet.payment_id).first() if not person: person = Person() person.name = 'Участник промо-кампании' person.firm_id = loyalty.firm_id person.hard_id = wallet.hard_id person.payment_id = wallet.payment_id person.save() if not loyalty.terms_id: continue timeout = PersonEvent.LIKE_TIMEOUT if loyalty.timeout: timeout = loyalty.timeout terms = json.loads(loyalty.terms_id) for term in terms: event = PersonEvent.query.filter_by( person_id=person.id, term_id=term, event_id=loyalty.event_id, firm_id=loyalty.firm_id).first() if event: if event.timeout > timeout: event.status = PersonEvent.STATUS_BANNED event.save() else: event = PersonEvent() event.person_id = person.id event.term_id = term event.event_id = loyalty.event_id event.firm_id = loyalty.firm_id event.timeout = PersonEvent.LIKE_TIMEOUT if loyalty.timeout: event.timeout = loyalty.timeout event.save() answer = event.id return answer
def test_person(): mock_store = mockredis.mock_redis_client(strict=True) person = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store) assert person.id == 1 assert person.first_name == 'first' assert person.last_name == 'last' assert person.age == 20 assert person.github_account == 'github_account' assert person.third_grade_graduation == '3rd_grade_grad_date'
def create(): person = Person() person.id = uuid.uuid4() person.vorname = request.json["vorname"] person.nachname = request.json["nachname"] person.email = request.json["email"] person.handy = request.json["handy"] person.save(force_insert=True) return json.dumps(map_to_dict(person), indent=4)
def add_person(): # currentUserId = get_jwt_identity() data = json.loads(request.get_data()) data = check_data(PersonSchema, data) # person = Person(entries=data) person.user_id = currentUserId person.id = generateID() print(person.serialize()) mongo.db.person.insert_one(person.serialize()) return person.serialize()
def init_table_values(self): Person.drop_table(self.database) Person.create_table(self.database) for i in range(self.rows): response_id = int(self.df['respid'][i]) book_count = int(self.df['books1'][i]) state = int(self.df['state'][i]) person = Person(response_id, book_count, state, self.database) person.save()
def get_current_row(self) -> Person: button = self.sender() if button: cur_row = self.table.currentRow() id = int((self.table.item(cur_row, 0).text())) username = self.table.item(cur_row, 1).text() nome = self.table.item(cur_row, 2).text() sobrenome = self.table.item(cur_row, 3).text() email = self.table.item(cur_row, 4).text() tipo = self.table.item(cur_row, 5).text() return Person(id, nome, sobrenome, tipo, username, email)
def build_persons(self): response = requests.get(config.get('api') + '/board/persons', auth=HTTPBasicAuth( config.get('auth').get('username'), config.get('auth').get('password'))) payload = json.loads(response.text) self.persons.clear() for person in payload: person = Person(json.dumps(person)) self.persons.append(person)
def test_all(): mock_store = mockredis.mock_redis_client(strict=True) person_index = PersonIndex(mock_store) person1 = Person(1, 'first', 'last', sys.maxint, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person1) person2 = Person(2, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person2) person3 = Person(3, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person3) people = person_index.all() assert people is not None assert next((person for person in people if person.id == str(1)), None) is not None assert next((person for person in people if person.id == str(2)), None) is not None assert next((person for person in people if person.id == str(3)), None) is not None
def insert_person(): name = request.json['name'] cpf = request.json['cpf'] password = request.json['password'] email = request.json['email'] person = Person(name, cpf, password, email) db.session.add(person) db.session.commit() return "Pessoa inserida com sucesso!"
def person_by_id(self, id): connection = MySQLdb.connect(host="mysql.zuplae.com", user="******", passwd="lendas19", database="zuplae04") cursor = connection.cursor() cursor.execute( "SELECT ID, NOME, SOBRENOME FROM PESSOA WHERE ID = {}".format(id)) p = cursor.fetchone() person = Person(p[1], p[2], p[0]) connection.close() return person
def load_table_data(self): con = connect_database() cur = con.cursor() cur.execute( 'SELECT id_user, nome_usuario, sobrenome_usuario, username, email, tipo FROM usuarios' ) all_rows = cur.fetchall() if len(all_rows) > 0: for idx, row in enumerate(all_rows): self.table.insertRow(idx) item = Person(row[0], row[1], row[2], row[5], row[3], row[4]) self.set_table_data(item, idx) con.close()
def list_all(self): connection = MySQLdb.connect(host="mysql.zuplae.com", user="******", passwd="lendas19", database="zuplae04") cursor = connection.cursor() cursor.execute("SELECT ID, NOME, SOBRENOME FROM PESSOA") list_person = [] for p in cursor.fetchall(): person = Person(p[1], p[2], p[0]) list_person.append(person.__dict__) connection.close() return list_person
def main(): """Main function to be called when executing the script""" franks_city = City().set_name('City') franks_address = Address()\ .set_street('Sample street')\ .set_zip('01234')\ .set_city(franks_city) frank = Person().set_first_name('Frank')\ .set_last_name('Lastname')\ .set_address(franks_address) print str(frank)
def update_person(self, args): uid = input('Input person uid: ') old_person: Person = self.__person_service.get_person(uid) print('New person data:') new_person = self.input_person(self.__person_service.generate_uid()) new_name = old_person.name if new_person.name == '' else new_person.name new_phone_number = old_person.phone_number if new_person.phone_number == '' else new_person.phone_number new_person = Person(uid, new_name, new_phone_number) self.__person_service.update_person(uid, new_person) print('Person updated successfully!')
def createPerson(personCalled): person = Person(called=personCalled) print( "Enter more details of the person: given name, maiden name, birth date, has user account, team member" ) print("Press Enter if not present.") person.givenName = getStrInput("Given name") person.surName = getStrInput("Surname") person.maidenName = getStrInput("Maiden name") person.gender = getStrInput("Gender") person.birthDate = getDateInput("Birth date") # person.hasUserAccount = getBoolInput("Do they have user account") # person.isTeamMember = getBoolInput("Are they a team member") person.addToDB() return person
def query_person(id): is_admin = get_jwt()['is_admin'] print(is_admin) currentUserId = get_jwt_identity() persons = mongo.db.person.find_one_or_404({'_id': id}) person = Person(entries=persons) print(person.family) family = mongo.db.family.find_one_or_404({"_id": person.family}) family = Family(entries=family) print(currentUserId) if person.user_id == currentUserId or check_family_read_auth( family, currentUserId, is_admin): return person.serialize() else: raise ApiError(NO_AUTH, 403)
def _parse_csv(csv_path): ''' Parses the CSV file :param csv_path: path to CSV, including filename :return: ''' print "Reading data, please wait..." person_index = PersonIndex(store) with open(csv_path) as csvfile: row_reader = csv.reader(csvfile) headers = row_reader.next() _validate_headers(headers) for row in row_reader: person = Person(*row, store=store) person_index.add_person_to_index(person) print "Finished reading data"
def process_file(): if request.method == 'GET': return redirect(url_for('home')) else: file = request.files['file_to_upload'] data = get_data(file) first_index = next(iter(data)) matrix = data[first_index][1:] person_class = Person(matrix) genetic_class = Genetic(person_class, 3) genetic_class.calculate() return render_template("results.html", genetic_class=genetic_class, person_class=genetic_class.person_class, groups=genetic_class.get_sub_groups( genetic_class.groups))