示例#1
0
    def _create_population(self, initial_infected):
        #  This method should be called when the simulation
        # begins, to create the population that will be used. This method should return
        # an array filled with Person objects that matches the specifications of the
        # simulation (correct number of people in the population, correct percentage of
        # people vaccinated, correct number of initially infected people).
        population = []
        infected_count = 0
        while len(population) != pop_size:
            if infected_count != initial_infected:

                new_infected_person = person.Person(self.next_person_id, False,
                                                    virus)
                population.append(new_infected_person)
                infected_count += 1
            else:
                # Every time a new person will be created, generate a random number between
                # 0 and 1.  If this number is smaller than vacc_percentage, this person
                # should be created as a vaccinated person. If not, the person should be
                # created as an unvaccinated person.
                chance_of_being_vaccinated = random.random()
                if chance_of_being_vaccinated < self.vacc_percentage:
                    population.append(person.Person(self.next_person_id, True))
                else:
                    population.append(person.Person(self.next_person_id,
                                                    False))
                # After any Person object is created, whether sick or healthy,
                # you will need to increment self.next_person_id by 1. Each Person object's
                # ID has to be unique!
            self.next_person_id += 1

        return population
示例#2
0
def test():
    p1 = person.Person("Sally")
    p2 = person.Person("Bob")
    p3 = person.Person("John")
    p1.speaker.connect(p2.listen)
    p2.speaker.connect(p3.listen)
    p1.gossip("hello")
示例#3
0
  def testAnnualSetupInvoluntaryRetirement(self, _):
    strategy = self.default_strategy._replace(planned_retirement_age=65)

    # Forced retirement at age 60
    j_canuck = person.Person(strategy=strategy)
    j_canuck.involuntary_retirement_random = 0.05
    j_canuck.age = 60
    year_rec = j_canuck.AnnualSetup()
    self.assertTrue(year_rec.is_retired)
    self.assertTrue(j_canuck.retired)

    # Forced retirement at 61 shouldn't kick in at 60
    j_canuck = person.Person(strategy=strategy)
    j_canuck.involuntary_retirement_random = 0.1
    j_canuck.age = 60
    year_rec = j_canuck.AnnualSetup()
    self.assertFalse(year_rec.is_retired)
    self.assertFalse(j_canuck.retired)

    # Forced retirement at age 61
    j_canuck = person.Person(strategy=strategy)
    j_canuck.involuntary_retirement_random = 0.1
    j_canuck.age = 61
    year_rec = j_canuck.AnnualSetup()
    self.assertTrue(year_rec.is_retired)
    self.assertTrue(j_canuck.retired)
示例#4
0
  def testAnnualSetupReaper(self, mock_random):
    # Female, random variate < mortality probability at age 30
    j_canuck = person.Person(strategy=self.default_strategy, gender=person.FEMALE)
    j_canuck.age = 30
    mock_random.return_value = 0.0003
    year_rec = j_canuck.AnnualSetup()
    self.assertTrue(year_rec.is_dead)

    # Female, random variate > mortality probability at age 30
    j_canuck = person.Person(strategy=self.default_strategy, gender=person.FEMALE)
    j_canuck.age = 30
    mock_random.return_value = 0.0004
    year_rec = j_canuck.AnnualSetup()
    self.assertFalse(year_rec.is_dead)

    # Male, random variate < mortality probability at age 30
    j_canuck = person.Person(strategy=self.default_strategy, gender=person.MALE)
    j_canuck.age = 30
    mock_random.return_value = 0.0008
    year_rec = j_canuck.AnnualSetup()
    self.assertTrue(year_rec.is_dead)

    # Male, random variate > mortality probability at age 30
    j_canuck = person.Person(strategy=self.default_strategy, gender=person.MALE)
    j_canuck.age = 30
    mock_random.return_value = 0.0009
    year_rec = j_canuck.AnnualSetup()
    self.assertFalse(year_rec.is_dead)
示例#5
0
  def testCreatePersonParameters(self):
    j_canuck = person.Person(strategy=self.default_strategy)
    self.assertEqual(j_canuck.strategy, self.default_strategy)
    self.assertEqual(j_canuck.gender, person.FEMALE)

    j_canuck = person.Person(strategy=self.default_strategy, gender=person.MALE)
    self.assertEqual(j_canuck.gender, person.MALE)
def test_infection():
    normal_person_1 = person.Person(1, False)
    normal_person_2 = person.Person(2, False)
    deadly_person_3 = person.Person(3, False, "Deadly Virus")
    deadly_person_4 = person.Person(4, False, "Deadly Virus")

    assert normal_person_1.resolve_infection(0) == None
    assert normal_person_1.alive == True
    assert normal_person_1.infected == None
    assert normal_person_1.vaccinated == False

    assert normal_person_2.resolve_infection(1) == None
    assert normal_person_2.alive == True
    assert normal_person_2.infected == None
    assert normal_person_2.vaccinated == False

    assert deadly_person_3.resolve_infection(0) == True
    assert deadly_person_3.alive == True
    assert deadly_person_3.infected == "Deadly Virus"
    assert deadly_person_3.vaccinated == True

    assert deadly_person_4.resolve_infection(1) == False
    assert deadly_person_4.alive == False
    assert deadly_person_4.infected == "Deadly Virus"
    assert deadly_person_4.vaccinated == False
示例#7
0
def DefUsers(batch_file_path):
    batch_file = open(batch_file_path)
    l = 0
    users = {}
    for i, line in enumerate(batch_file.readlines()):
        json_dict = json.loads(line, object_pairs_hook=OrderedDict)
        if l > 1:
            if json_dict['event_type'] == 'purchase':
                if (json_dict['id']) not in users.keys():
                    users[(json_dict['id'])] = Person.Person((json_dict['id']))
            if json_dict['event_type'] == 'befriend':
                if (json_dict['id1']) not in users.keys():
                    users[(json_dict['id1'])] = Person.Person(
                        (json_dict['id1']))
                if (json_dict['id2']) not in users.keys():
                    users[(json_dict['id2'])] = Person.Person(
                        (json_dict['id2']))
            if json_dict['event_type'] == 'unfriend':
                if json_dict['id1'] not in users.keys():
                    users[json_dict['id1']] = Person.Person(json_dict['id1'])
                if json_dict['id2'] not in users.keys():
                    users[json_dict['id2']] = Person.Person(json_dict['id2'])

        l += 1

    batch_file.close()

    return users
def evaluate_personal_satisfaction(plan):

    residential_buildings = bt.find_buildings_in_type(bt.RESIDENTIAL, plan)

    people = []
    people.append(p.Person(CHILD, False))
    people.append(p.Person(SINGLE, False))
    people.append(p.Person(SINGLE, True))
    people.append(p.Person(PARENT, False))
    people.append(p.Person(ELDERLY, True))
    personal_satisfaction_raw = []
    max_sat = 0
    for person in people:
        curr_person_type_score = []
        for j in range(50):
            person.set_residence(residential_buildings[np.random.randint(
                len(residential_buildings))])
            # curr_sat = round(person.set_satisfaction(),4)
            curr_sat = person.set_satisfaction()
            curr_person_type_score.append(curr_sat)
        curr_person_type_sat = np.mean(curr_person_type_score)
        personal_satisfaction_raw.append(curr_person_type_sat)

        if (curr_person_type_sat > max_sat):
            max_sat = curr_person_type_sat

    personal_satisfaction = []
    for i in range(len(people)):
        curr_sat = round(personal_satisfaction_raw[i] / max_sat, 4)
        personal_satisfaction.append(
            (people[i].get_type(), str(people[i].get_religious()),
             people[i].get_residence(), curr_sat))
    return personal_satisfaction
示例#9
0
 def OnSubgenius(self, e):
     self.game.cult = cult.Cult()
     self.game.leader = person.Person()
     self.game.cult.name = "Church of the SubGenius"
     self.game.cult.short_name = "SubGenius"
     self.game.cult.members_name = "SubGenii"
     self.game.cult.founding_date = date(1998, 07, 05)
     self.game.cult.doctrines = ["ufo", "apocalyptic", "funny"]
     self.game.leader.name = 'J.R. "Bob" Dobbs'
     self.game.leader.gender = 'm'
     self.game.leader.morale = 55
     self.game.leader.birthday = date(1959, 4, 1)
     self.game.leader.rank = person.Person.RANK_LEADER
     self.game.cult.leader = self.game.leader
     self.game.cult.membership.append(self.game.leader)
     self.game.date = date.today() + timedelta(days=32)
     self.game.date = self.game.date.replace(day=1)
     for ii in range(25):
         self.game.cult.membership.append(person.Person())
     for ii in range(25):
         p = person.Person()
         p.rank = person.Person.RANK_OUTER_CIRCLE
         p.morale = 75
         p.fanaticism = 40
         self.game.cult.membership.append(p)
     self.GameStartedPages()
示例#10
0
def simulate2():
  dayNumber = 1 #We only simulate 1 day in this scenario

  # Create actors Bob and Alice. In this scenario, we assume Alice is infected with Covid-19.
  bob = person.Person("Bob")
  alice = person.Person("Alice")

  # Both Bob and Alice set their daily trace keys for a specified day.
  # The proximity IDs for their 24-hour of daily activity is automatially set 
  # when this function is called.
  bob.setDailyTraceKey(dayNumber)
  alice.setDailyTraceKey(dayNumber)

  # Uncomment below functions to print all keys produced by Alice and Bob in this simulation
  bob.printResults()  
  alice.printResults() 

  # We simulate Alice coming into contact with Bob at time interval 5 to 7 on Day Number 1
  # Both Alice and Bob store each others respective prox IDs observed during these time intervals.

  for i in range(5, 8):
    alice.setContact(bob.prox_ids[i])
    bob.setContact(alice.prox_ids[i])
    print("Simulation of contact between Bob and Alice has occurred (Day Number: %d; Time Interval: %d;)" % (dayNumber, i))

  print("\nAlice is tested positive for Covid-19 and her diagnosis keys are released to Bob via a third party.")
  aliceDiagnosisKeys = alice.getDiagnosisKeys()

  print("\nBob performs contact tracing to determine when he came into contact with Alice. His results show:")
  bobContactTracingResult = bob.doContactTracing(aliceDiagnosisKeys)  

  for t in bobContactTracingResult:
    print("Bob came into contact with a Covid-19 infected individual (Day Number: %d; Time Interval: %d; Matching Prox ID: %s" % (t[0], t[1], binascii.hexlify(t[2]).decode()))    
    def test_mixInProbabilities(self):
        p1 = person.Person(TEST_PERSON)
        p2 = person.Person(TEST_PERSON)

        p2.identify(0, 1)  # 100% identified as id = 0
        p1.mixInProbabilities(p2, 0.6)
        # probability for id = 0 is combined as: 0.6 * 1 + 0.4 * 0.25 = 0.7
        self.assertListEqual(p1.idProbs, [0.7, 0.1, 0.1, 0.1])
示例#12
0
def scrap(username):
    '''
        scrapes data from facebook for the available user in db
        print favourites
        print and store name and city
    '''
    query1 = f"SELECT scrape,name,city FROM users WHERE username = \"{username}\""
    config.cursor.execute(query1)
    credentials = config.cursor.fetchall()[0]
    scrape = credentials[0]

    if scrape == 0:
        fb_url = "https://en-gb.facebook.com/{}".format(username)
        # print(fb)
        page = urllib.request.urlopen(fb_url)
        soup = BeautifulSoup(page, features="html.parser")

        for uname in soup.find_all('a', class_='_2nlw _2nlv'):
            name = uname.text.strip()

        city = []
        for cityname in soup.find_all('span', class_='_2iel _50f7'):
            city.append(cityname.text.strip())

        current_city = city[0]

        works = []
        for work in soup.find_all('div', class_='_2lzr _50f5 _50f7'):
            works.append(work.text.strip())

        keys = []
        for key in soup.find_all('div', class_='labelContainer'):
            keys.append(key.text.strip())

        if bool(keys):
            fav = {}
            i = 0
            for value in soup.find_all('div', class_='mediaPageName'):
                fav[keys[i]] = value.text.strip()
                i = i + 1
        else:
            fav = "There are no favourites"

        if bool(current_city):
            person1 = person.Person(name, current_city, works)
        else:
            person1 = person.Person(name, None, works)
        # print(works)
        print(fav)
        query = f"UPDATE users SET scrape=1,name=\'{person1.name}\',city=\'{person1.city}\' WHERE username=\'{username}\'"
        config.cursor.execute(query)
        config.cnx.commit()
        # print(query)
        # print("Info Updated")

    else:
        person1 = person.Person(credentials[1], credentials[2])
        person1.show()
示例#13
0
def main():
    import person

    # testing
    pickledb = ShelveDB({
            'oleg': person.Person('Oleg', 16, 35000, 'designer'),
            'ivan': person.Person('Ivan', 33, 78000, 'programmer')
    })
    pickledb.save()
    pickledb.load()
    print(pickledb)
 def test_log_interaction_fail_to_infect_vacc(self):
     _logger = logger.Logger('what.txt')
     _virus = virus.Virus("Tuberculosis", 0.67, 0.55)
     _person = person.Person(1, False, _virus)
     _person2 = person.Person(2, False)
     _logger.write_metadata(100, 0.5, 'Virus', 0.5, 0.5)
     _logger.log_interaction(_person, _person2, None, True, None)
     file = open(_logger.file_name, 'r')
     assert file.read(
     ) == f'''{str(100)}\t{str(0.5)}\t{'Virus'}\t{str(0.5)}\t{str(0.5)}\n{1} did not infect vaccinated person {2} \n'''
     file.close()
     os.remove("what.txt")
示例#15
0
def testCount():
    print("testing count")
    person1 = person.Person(1, (300, 300))
    person2 = person.Person(2, (400, 400))
    person3 = person.Person(3, (500, 500))

    personList = [person1, person2, person3]
    crosslingLine = defineCrossingLine()
    prevCount = 0

    d = point_to_line_dist((840, 122), crosslingLine)
    print("dist ", d)
def test_person():
    normal_person = person.Person(0, False)
    assert normal_person.alive == True
    assert normal_person.identity == 0
    assert normal_person.vaccinated == False
    assert normal_person.infected == None

    deadly_person = person.Person(1, False, "Deadly Virus")
    assert deadly_person.alive == True
    assert deadly_person.identity == 1
    assert deadly_person.vaccinated == False
    assert deadly_person.infected == "Deadly Virus"
示例#17
0
def testCount():
	print("testing count")
	person1 = person.Person((300, 300), 1)
	person2 = person.Person((400, 400), 2)
	person3 = person.Person((500, 500), 3)

	personList = [person1, person2, person3]
	crosslingLine = defineCrossingLine()
	prevCount = 0

	n, l = countPersons(personList, prevCount, crosslingLine)
	print(n)
	print(l)
 def _create_population(self, initial_infected):
     # TODO: Finish this method!  This method should be called when the simulation
     # begins, to create the population that will be used. This method should return
     # an array filled with Person objects that matches the specifications of the
     # simulation (correct number of people in the population, correct percentage of
     # people vaccinated, correct number of initially infected people).
     population = []
     infected_count = 0
     rest_of_the_people = []
     # pop_size = 100 # comment after testing
     while len(population) != pop_size:
         if infected_count !=  initial_infected:
             # TODO: Create all the infected people first, and then worry about the rest.
             # Don't forget to increment infected_count every time you create a
             # new infected person!
             infected_count += 1
             new_infected_person = person.Person(self.next_person_id, False, self.virus)
             self.newly_infected.append(new_infected_person)
             population.append(new_infected_person)
             self.current_infected += 1
             # self.next_person_id += 1
             # print("New infected: ", len(self.newly_infected))
         else:
             # Now create all the rest of the people.
             # Every time a new person will be created, generate a random number between
             # 0 and 1.  If this number is smaller than vacc_percentage, this person
             # should be created as a vaccinated person. If not, the person should be
             # created as an unvaccinated person.
             randomNumber = random.randint(0,1)
             if randomNumber < self.logger.vacc_percentage:
                  not_infected_person = person.Person(self.next_person_id, True, None)
                  rest_of_the_people.append(not_infected_person)
                  population.append(not_infected_person)
                 #  self.next_person_id += 1
             else:
                  not_infected_person = person.Person(self.next_person_id, False, None)
                  rest_of_the_people.append(not_infected_person)
                  population.append(not_infected_person)
                 #  self.next_person_id += 1
     
         # TODO: After any Person object is created, whether sick or healthy,
         # you will need to increment self.next_person_id by 1. Each Person object's
         # ID has to be unique!
         self.next_person_id += 1
         # print("IDs: ", self.next_person_id)  
         # population = self.newly_infected + rest_of_the_people
     # print("Population: ", len(population))
     self.population = population
     return population
示例#19
0
def scan(name, subject):
    import xlrd, person
    workbook = xlrd.open_workbook(name)
    sheet = workbook.sheet_by_name('Sheet 1')
    num_rows = sheet.nrows
    num_cells = sheet.ncols
    data = []
    times = []
    for curr_row in range(num_rows):  #iterate through each row (student)
        if curr_row < 1:
            for i in range(num_cells - 5):
                times.append(sheet.cell_value(0, i + 4))
        else:
            temp1 = []
            avail = []  #time slots
            for curr_cell in range(num_cells):
                if (curr_cell > 3) and (
                        curr_cell < num_cells - 1
                ):  #group time slots together, the last row of data is preference so -1
                    avail.append(sheet.cell_value(curr_row, curr_cell))
                else:
                    temp1.append(sheet.cell_value(curr_row, curr_cell))
            student = person.Person(
                temp1[0], temp1[1], temp1[2], temp1[3], subject, temp1[4],
                avail)  #assign all the values to person class
            data.append(student)  #add back to data
    return (data, times)
 def testCreatePersonHasIncomes(self):
     j_canuck = person.Person(strategy=self.default_strategy)
     self.assertCountEqual([inc.income_type for inc in j_canuck.incomes], [
         incomes.INCOME_TYPE_EARNINGS, incomes.INCOME_TYPE_EI,
         incomes.INCOME_TYPE_CPP, incomes.INCOME_TYPE_OAS,
         incomes.INCOME_TYPE_GIS
     ])
示例#21
0
def test_multiple_give_raise():
    bruce = manager.Manager('Bruce', 'Programmer', 100)
    sue = person.Person('Sue', 'Assistant', 100)
    for obj in (bruce, sue):
        obj.give_raise(.10)
    assert bruce.pay == 120
    assert sue.pay == 110
示例#22
0
def fill_team_schedules(crew_names, schedules, number_of_working_days, person_per_day, person_per_night):
    """Funkcja służąca do automatycznego wypełniania grafuku pracy.

    Funkcja wypełnia automatycznie grafiki pracy (schedule) dla poszczególnych osób z załogi (crew)
    Wszystkie osoby (w postaci instancji Person) należy zebrać w listę (team).
    Wypełnianie grafiku pracy odbywa się na podstawie ustawionych parametrów.

    :param crew_names: załoga
    :param schedules: lista grafików pracy dla poszczególnych osób z crew

    :param number_of_working_days: maksymalna liczba dni pracujących w miesiącu dla jednej osoby
    :param person_per_day: - liczba osób pracujących w dzień
    :param person_per_night: - liczba osób pracujących w nocy
    """

    # tworzenie drużyny złożonej z instancji Person
    team = [person.Person(name, schedule) for name, schedule in zip(crew_names, schedules)]

    # TODO poniżej Twoje rozwiązanie

    for day_nr in range(31):
        while find_cnt_day_shifts(team, day_nr) < person_per_day:
            for person_ in team:
                if person_.is_day_free and not person_.month_is_full(number_of_working_days):
                    person_.take_one_day_work(day_nr, 'D')

        while find_cnt_night_shifts(team, day_nr) < person_per_night:
            for person_ in team:
                if person_.is_day_free and not person_.month_is_full(number_of_working_days):
                    person_.take_one_day_work(day_nr, 'N')
示例#23
0
def test_department_give_raises():
    bruce = manager.Manager('Bruce', 'Programmer', 100)
    sue = person.Person('Sue', 'Assistant', 100)
    accounting = department.Department(bruce, sue)
    accounting.give_raises(.10)
    assert bruce.pay == 120
    assert sue.pay == 110
示例#24
0
 def test2():
     """对象引用"""
     p1 = person.Person("tom")
     p2 = p1
     p1.name = "jim"
     p1.sayhello()  # Hello jim
     p2.sayhello()  # Hello jim
示例#25
0
  def SetupYearRecForIncomeTax(
      self, earnings=0, oas=0, gis=0, cpp=0, ei=0,
      rrsp=0, bridging=0,nonreg=0, gains=0, eoy_gains=0,
      unapplied_losses=0, rrsp_contributions=0,
      age=30, retired=False, cpi=1):
    """Set up a person and a year record in one go for testing income tax."""
    j_canuck = person.Person(strategy=self.default_strategy)
    j_canuck.capital_loss_carry_forward = unapplied_losses
    j_canuck.age += age - world.START_AGE
    j_canuck.year += age - world.START_AGE
    j_canuck.retired = retired

    year_rec = utils.YearRecord()
    year_rec.is_retired = j_canuck.retired
    year_rec.year = j_canuck.year
    year_rec.incomes.append(incomes.IncomeReceipt(earnings, incomes.INCOME_TYPE_EARNINGS))
    year_rec.incomes.append(incomes.IncomeReceipt(oas, incomes.INCOME_TYPE_OAS))
    year_rec.incomes.append(incomes.IncomeReceipt(gis, incomes.INCOME_TYPE_GIS))
    year_rec.incomes.append(incomes.IncomeReceipt(cpp, incomes.INCOME_TYPE_CPP))
    year_rec.incomes.append(incomes.IncomeReceipt(ei, incomes.INCOME_TYPE_EI))
    year_rec.withdrawals.append(funds.WithdrawReceipt(nonreg, gains, funds.FUND_TYPE_NONREG))
    year_rec.withdrawals.append(funds.WithdrawReceipt(rrsp, 0, funds.FUND_TYPE_RRSP))
    year_rec.withdrawals.append(funds.WithdrawReceipt(bridging, 0, funds.FUND_TYPE_BRIDGING))
    year_rec.tax_receipts.append(funds.TaxReceipt(eoy_gains, funds.FUND_TYPE_NONREG))
    year_rec.deposits.append(funds.DepositReceipt(rrsp_contributions, funds.FUND_TYPE_RRSP))
    year_rec.cpi = cpi

    year_rec = j_canuck.CalcPayrollDeductions(year_rec)

    return (j_canuck, year_rec)
示例#26
0
  def SetupForMeddleWithCash(self, age=30, cpi=1, retired=False, employed=True,
                             rrsp=0, rrsp_room=0, tfsa=0, tfsa_room=0, nonreg=0):
    j_canuck = person.Person()
    year_rec = utils.YearRecord()

    # Set working period fund amounts (these may be split later on)
    j_canuck.funds["wp_rrsp"].amount = rrsp
    j_canuck.funds["wp_tfsa"].amount = tfsa
    j_canuck.funds["wp_nonreg"].amount = nonreg

    # The following section roughly approximates Person.AnnualSetup()
    j_canuck.age = age
    year_rec.age = age
    j_canuck.year = age - world.START_AGE + world.BASE_YEAR
    year_rec.year = age - world.START_AGE + world.BASE_YEAR
    j_canuck.cpi = cpi
    year_rec.cpi = cpi

    j_canuck.retired = retired
    if retired:
      j_canuck.OnRetirement()
    year_rec.is_retired = retired
    year_rec.is_employed = employed and not retired

    year_rec.growth_rate = world.MEAN_INVESTMENT_RETURN

    j_canuck.tfsa_room = tfsa_room
    year_rec.tfsa_room = tfsa_room
    j_canuck.rrsp_room = rrsp_room
    year_rec.rrsp_room = rrsp_room

    return j_canuck, year_rec
def extract_data(tree):
    person = p.Person()
    for elem in tree.xpath(
            '/html/body/table/tr/td/table/tr[5]/td/table[1]/tr[2]/td/table/tr'
    ):
        text = etree.tostring(elem, method="text", encoding="unicode")
        text = text.replace('\n', '').replace('\t', '').lower()
        pairs = text.split(':', 1)
        if (len(pairs) < 2):
            # TODO: check if voted on dec 16 and/or oct7
            text
        else:  # two elements in pairs list
            if (pairs[0] == u'c\xe9dula'):
                person.cedula = pairs[1].replace('v-', '')
            elif (pairs[0] == u'nombre'):
                person.full_name = pairs[1]
            elif (pairs[0] == u'nombres'):
                names = pairs[1].split()
                if (len(names) == 4):
                    person.first_name = names[0]
                    person.second_name = names[1]
                    person.first_surname = names[2]
                    person.second_surname = names[3]
            elif (pairs[0] == u'estado'):
                person.voting_center.state = pairs[1]
            elif (pairs[0] == u'municipio'):
                person.voting_center.municipality = pairs[1]
            elif (pairs[0] == u'parroquia'):
                person.voting_center.parish = pairs[1]
            elif (pairs[0] == u'centro'):
                person.voting_center.center = pairs[1]
            elif (pairs[0] == u'direcci\xf3n'):
                person.voting_center.address = pairs[1]
    print person
    return person
示例#28
0
def main():

    peep = person.Person('Emily Darin', '1206 Mary Ave Okemos, MI 48917',
                         '517-123-4564')

    print("Name:", peep.get_name())
    print("Address:", peep.get_address())
    print("Phone Number:", peep.get_phone_num(), '\n')

    peep = person.Customer('Teresa M. Potts',
                           '1206 Mary Ave Grand Ledge, MI 60126',
                           '517-123-4564', 1221)

    print("Name:", peep.get_name())
    print("Address:", peep.get_address())
    print("Phone Number:", peep.get_phone_num())
    print("Customer ID:", peep.get_cust_id(), '\n')

    peep = person.Vendor('Tim Belcher',
                         '1500 Abbot Rd Ste 100 East Lansing, MI 48823',
                         '517-456-4564', 4231)

    print("Name:", peep.get_name())
    print("Address:", peep.get_address())
    print("Phone Number:", peep.get_phone_num())
    print("Vendor ID:", peep.get_vendor_id())
示例#29
0
  def testAnnualSetupVoluntaryRetirement(self, _):
    strategy = self.default_strategy._replace(planned_retirement_age=65)

    j_canuck = person.Person(strategy=strategy)
    j_canuck.age = 64
    j_canuck.involuntary_retirement_random = 1.0
    year_rec = j_canuck.AnnualSetup()
    self.assertFalse(year_rec.is_retired)
    self.assertFalse(j_canuck.retired)
    
    j_canuck = person.Person(strategy=strategy)
    j_canuck.age = 65
    j_canuck.involuntary_retirement_random = 1.0
    year_rec = j_canuck.AnnualSetup()
    self.assertTrue(year_rec.is_retired)
    self.assertTrue(j_canuck.retired)
示例#30
0
def get(block, room):
    "Get request to kn.vutbr.cz and retrieve person's data"

    URL = 'http://kn.vutbr.cz/search/index.html?str=' + str(block) + '-' + str(
        room)

    get_request = requests.get(URL)

    if get_request.status_code != 200:
        print("ERROR:\tStatus code of HTTP GET request is",
              get_request.status_code, "-", responses[get_request.status_code])

        print("\tURL:", URL)
        return None
    elif "Data nenalezena" in get_request.text:
        return None

    matches = re.finditer(r"<\/font>\s(.*)\s(.*)<\/th>", get_request.text)

    names = list()

    for match in matches:
        p_name = str(match.group(1))  # firstname and middlename
        p_surname = str(match.group(2))
        p_gender = const.MALE

        first_name = p_name.split()[0]  # ignore middle name

        if first_name.endswith(('a', 'A', 'e', 'E')) or p_surname.endswith(
            ('á', 'Á')):
            p_gender = const.FEMALE

        names.append(person.Person(p_name, p_surname, p_gender))

    return names