def end_choice(self): John = Person('John','22','male','China','None','None','Basketball') #选择1的数量大于2,则和好,否则再也不见 if gl.END1 > gl.END2: John.talk('好,我们重新开始!') if gl.END1 < gl.END2: John.talk('我们已经回不到过去了!再也不见!')
def get_data(): url = next_urls.pop().replace('\n', '') if url in seen_urls: return print(url) person = Person(url, session) try: person.get_all_info() except: print('Get user data error!') return print(person.id, person.name, person.url, person.gender, person.location, person.business, person.employment, person.position, person.education, person.education_extra, person.description, person.hash_id, person.follower_num, person.followee_num, person.asks, person.answers, person.posts, person.collections, person.logs, person.agrees, person.thanks) data = (person.id, person.name, person.url, person.gender, person.location, person.business, person.employment, person.position, person.education, person.education_extra, person.description, person.hash_id, person.follower_num, person.followee_num, person.asks, person.answers, person.posts, person.collections, person.logs, person.agrees, person.thanks) try: db.insert_data(data) except pymysql.err.DataError as E: print(E) return next_urls.update(person.follow()) seen_urls.add(url) print(len(next_urls)) # 爬取一百人之后更新一次next_urls.txt文件,实时保存进度 if len(next_urls) % 100 == 0: save_next_urls() save_seen_urls(url)
def read(fName): Log.trace(__class__, "read()") pCollection = PersonCollection() try: file = open(fName, 'r') isHeader = True #SEP = ',*' SEP = "[\,,\s]*" EMB = "\"" regEx = re.compile(EMB + '([^' + EMB + ']*)' + EMB + SEP) for line in file: i = 0 person = Person() for col in regEx.findall(line): if(isHeader): pCollection.addHeader(col) #self._headerNames.append(col) else: person.setAttribute(pCollection.getHeaderNames()[i], col) i += 1 if(isHeader): isHeader = False else: pCollection.addPerson(person) file.close() return pCollection except IOError: Log.error(__class__, "IOError with file > " + fName) return None
def _merge(pcMerge, pcMaster, pcSlave): Log.trace(__class__, "_merge() called") # add headerNames in pcNew for kMaster in pcMaster.getHeaderNames(): pcMerge.addHeader(kMaster) # Merge attributes of pcMaster to pcNew for pMaster in pcMaster.getPersons(): pMerge = Merge.getPerson(pcMerge, pMaster) if(pMerge == None): pMerge = Person() pcMerge.addPerson(pMerge) pSlave = Merge.getPerson(pcSlave, pMaster) if(pSlave == None): # do copy of pMaster pSlave = Person() for kMaster in pcMaster.getHeaderNames(): aMaster = pMaster.getAttribute(kMaster) aSlave = pSlave.getAttribute(kMaster) aMerge = Person.ATTR_NOT_AVAILABLE # Attribute is empty if((aMaster != "" or aMaster != Person.ATTR_NOT_AVAILABLE) and (aSlave == "" or aSlave == Person.ATTR_NOT_AVAILABLE)): aMerge = aMaster elif((aSlave != "" or aSlave != Person.ATTR_NOT_AVAILABLE) and (aMaster == "" or aMaster == Person.ATTR_NOT_AVAILABLE)): aMerge = aSlave # Attributes are not empty elif(aMaster == aSlave): aMerge = aMaster else: Log.warn(__class__, "merge conflict:\nMaster=" + aMaster + "\n Slave=" + aSlave) pMerge.setAttribute(kMaster, aMerge) Log.trace(__class__, "_merge() finished")
def get_people(path): import logging logging.basicConfig(filename='log.log', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') people = [] with codecs.open(path, "r", "iso-8859-1") as f: assert isinstance(path, str) ind = path.rindex(sep) fi = path[ind:] year = re.search("[0-9]{4}", fi).group() year = int(year) d = {} first = True for line in f: fields = line.split("|") if first: for i in range(len(fields)): field = fields[i] d[i] = field.replace("\r\n", "") first = False else: p = Person(year) for i in range(len(fields)): field = fields[i] try: r = d[i] method = switcher.get(r, None) if method is not None: method(p, field) except KeyError: print(fields) p.valid = False people.append(p) return people
def inheritance_two(): car = {} driver = Passenger() driver.setName('Bob') driver.setAge(30) driver.setSeatPosition(0) driver.setIsDriver(True) passenger = Passenger() passenger.setName('Jim') passenger.setAge(40) passenger.setSeatPosition(1) person = Person() person.setName('Jack') person.setAge(25) car['driver'] = driver car['passenger'] = passenger car['otherpassenger'] = person for key in car: occupant = car[key] try: print('Occupant ' + occupant.getName() + (', driving' if occupant.getIsDriver() else ', passenger' ) ) except AttributeError as ae: if isinstance(occupant, Human): print('Occupant ' + occupant.getName() ) else: print( 'Error : ' + ae.message)
class Scene(object): def __init__(self): self.person = Person() def enter(self): print "This scene is not yet configured. Subclass it amd implement enter()." exit(1) def get_action(self): action = raw_input("> ") if (action == "exit"): exit(0) self.get_action() elif (action == "read map" and self.person.has_item("map")): print " _~_ ___ " print "|_L_|---|_r_|" print " ___ _|_ " print "|_S_|---|_r_|" print " _|_ " print " |_x_|" return self.get_action() elif (action == "read paper" and self.person.has_item("paper")): print "*******" print "Hurry to the passage, the machines have" print "found us! If you encounter one then use the" print "trap we put in place by shouting the password" print "*******" return self.get_action() elif (action == "inventory"): print self.person.items return self.get_action() else: return action
def __init__(self, studentID, name = "Student X", gender = "m", leavingCertificate = 700): self.studentID = studentID Person.__init__(self, name, gender) self.modules = [] self.moduleEnrollments = {} self.semester = 1 self.leavingCertificate = leavingCertificate #TODO: check Irish system self.faculty = ""
def main(): collection_old = 'activities' collection_new = 'activity' address_old = '192.168.37.128' port_old = 27017 address_new = '192.168.6.254' port_new = 37017 Person.convert_person(address_old, port_old, address_new, port_new) print("OK")
def doMapping(self, pcSrc): pcDest = PersonCollection() # add headerNames to destination personCollection for kDest in self._mapping.values(): pcDest.addHeader(kDest) # add srcPersons to destPersons with new headerNames for pSrc in pcSrc.getPersons(): pDest = Person() for kSrc, kDest in self._mapping.items(): attr = pSrc.getAttribute(kSrc) if((attr == Person.ATTR_NOT_AVAILABLE or attr == "") and self._defaultValues[kDest] != ""): attr = self._defaultValues[kDest] pDest.setAttribute(kDest, attr) pcDest.addPerson(pDest) return pcDest
def getMatches(self): matchesURL = "https://api.gotinder.com/updates" result = self.session.post(matchesURL, headers=self.headers, proxies=None) result = result.json() matches = result["matches"] people = [] for match in matches: if "person" in match: person = Person(match["person"]) personInformationURL = "https://api.gotinder.com/user/" + person.personID personResult = self.session.get(personInformationURL, headers=self.headers, proxies=None).json() personResult = personResult["results"] person = Person(personResult) people.append(person) print(person.name + "\t" + person.getSchools())
def test_file_input(self): self.myModel = Model() self.myModel.data_handler.read_in("TestData.csv") self.expected = Person('D003', 'M', 12, 312, 'Normal', 123) self.assertEquals(self.myModel.data_handler.get_data()[0].get_id(), self.expected.get_id()) self.assertEquals(self.myModel.data_handler.get_data()[0].get_weight(), self.expected.get_weight()) self.assertEquals(self.myModel.data_handler.get_data()[0].get_age(), self.expected.get_age()) self.assertEquals(self.myModel.data_handler.get_data()[0].get_sales(), self.expected.get_sales()) self.assertEquals(self.myModel.data_handler.get_data()[0].get_income(), self.expected.get_income())
def __init__(self): Person.__init__(self, '', '', '') BaseWidget.__init__(self,'Person window') self.parent = None #Definition of the forms fields self._firstnameField = ControlText('First name') self._middlenameField = ControlText('Middle name') self._lastnameField = ControlText('Lastname name') self._fullnameField = ControlText('Full name') self._buttonField = ControlButton('Press this button') #Define the button action self._buttonField.value = self.buttonAction self._formset = ['_firstnameField', '_middlenameField', '_lastnameField', '_fullnameField', (' ','_buttonField', ' '), ' ']
def begin(self): John = Person('John',22,'M','China','None','None','Basketball') Liz = Person('Liz',22,'F','China','None','None','Dance') print ''' ======故事开始====== ''' Liz.talk('亲爱的!我考上了北京城市学院了') s.wait(2) John.talk('我没考上。。。不过我决定打工赚钱供你上大学!') s.wait(2) Liz.talk('你对我真好,我太爱你了!')
def modifier(filename): """Modifies a file CSV. Adds a new column in the data structure""" try: assert os.path.exists(filename) except: raise ValueError('file "'+str(filename)+'" does not exist!') try: persons = {} csv_file = open(filename, 'rU') csv_reader = csv.DictReader(csv_file, delimiter=',') for line in csv_reader: person_id = int(line['id']) surname = line['surname'] name = line['name'] birth_date = line['birthdate'] nickname = line['nickname'] person = Person(surname, name, birth_date, nickname) persons[person_id] = person csv_file.close() csv_file = open(filename, 'w') fieldnames = ['id', 'surname', 'name', 'fullname', 'birthdate', 'nickname', 'age'] csv_writer = csv.writer(csv_file, delimiter=',', lineterminator='\n') csv_writer.writerow(fieldnames) for person_id in persons.keys(): person = persons[person_id] record = [person_id, person.surname, person.first_name, person.get_fullname(), person.birth_date, person.nickname, person.get_age()] csv_writer.writerow(record) finally: csv_file.close()
def __init__(self, person_id, prefix, first_name, last_name, nick_name, thai_first_name, thai_last_name, birth_date, nationality, shirt_size, photo_path, email, kmitl_id, academic_year, department, faculty, password): Person.__init__(self, person_id, prefix, first_name, last_name, nick_name, thai_first_name, thai_last_name, birth_date, nationality, shirt_size, photo_path, email) self.kmitl_id = kmitl_id self.person_id = person_id self.academic_year = academic_year self.department = department self.faculty = faculty self.password = password # class Student(Person): # def __init__(self, stu_id=123, firstName = None, lastName = None, nickName = None, prefix = None, # gender = None, thaiFirst = None, thaiLast = None, photo = None, role = None, shirtSize = None , birth_d = None): # # Person.__init__(self, firstName, lastName, nickName, prefix, gender, thaiFirst, thaiLast, photo, role, shirtSize, birth_d) # # self.studentID = stu_id # # def printInfo(self): # return "In student:", self.studentID , Person.printInfo(self) # # # print(Student("560900xx", "Thitiwat", "Wata").printInfo())
def main(self, *args, **kwds): # print all the existing contacts print "dumping existing contacts:" for contact in self.retrieveContacts(): print " %s: %s" % (contact.id, contact) # create a new one print print "creating a new one" from Person import Person person = Person() person.id = 10002 person.first = "Keri" person.middle = "Ann" person.last = "Aivazis" print " %s: %s" % (person.id, person) self.storeContact(person) return
def test_employment(self): company = object() income = object() p = Person.create().works() \ .at(company).income(income) \ .build() self.assertIs(p.street, None) self.assertIs(p.city, None) self.assertIs(p.company, company) self.assertEqual(p.income, income)
def test_address(self): street = object() city = object() p = Person.create().lives() \ .at(street).city(city) \ .build() self.assertIs(p.street, street) self.assertIs(p.city, city) self.assertIs(p.company, None) self.assertEqual(p.income, 0)
def startScraping(): print(datetime.datetime.now()) persons = [] titles = [] personi = 0 titlei = 0 #Number of ids to retrieve numIds = 10 while (True): if len(persons) == 0: persons = getTopPersons(numIds) if len(titles) == 0: titles = getTopTitles(numIds) for personID in persons: print(personID) start = time.time() person = Person(personID) if not person.checkInDB(False, False, False): print("checked DB") personi += 1 person.scrapeData() person.commitDB() end = time.time() print("{} scraping person {} : {}".format( personi, person.name, (end - start))) persons = [] for titleID in titles: print(titleID) #start = time.time() title = Title(titleID) if not title.checkInDB(False): titlei += 1 title.scrapeData() title.commitDB() end = time.time() print("{} scraping title {} : {}".format( titlei, title.name, (end - start))) titles = []
def start(universes, data): '''prints start of simulation message''' line = '-' * 40 print('All universes', line, sep='\n') for universe in universes: print('{}'.format(universe)) print('All individuals', line, sep='\n') for u in data: for ind in u['individuals']: person = Person(ind[0], ind[1], u['universe_name'], ind[2], ind[3], ind[4], ind[5], u['universe_name']) temp = copy(person) print(temp) print('\nStart simulation\n{}'.format(line))
def wait_for_connection(): #start new thread when new client is connected while True: try: client, addr= SERVER.accept() person = Person(addr, client) persons.append(person) #adding person object o list of persons Thread(target=client_communication, args=(person,)).start() print("[Connection]",addr,"connected to server at",time.time()) except Exception as e: print("Error",e) break print("Server crashed")
def create_population(self): healthy_population = [] infected_population = [] position = [] for person_id in range(INITIAL_POPULATION): self.population.append(Person(person_id)) healthy_population.append(True if self.population[-1]. health_status == 'healthy' else False) infected_population.append(True if self.population[-1]. health_status == 'infected' else False) position.append(self.population[-1].pos) return np.array(healthy_population, dtype=np.bool), \ np.array(infected_population, dtype=np.bool), \ np.array(position, dtype=np.int32)
def ModifyPeople(): # instance of connection to the database conn = dbconn() # retrieve all the people in the people Table # people = conn.execute_read_query("SELECT * FROM people") if request.method == 'POST': person_name = request.form['name'] person_phone = request.form['phone'] person_email = request.form['email'] person_obj = Person(conn) # person object person_obj.add_person(person_name, person_phone, person_email) # person = person_obj.view_person(person_name) # retrieve plus the added people # people = conn.execute_read_query("SELECT * FROM people") return redirect('/people/list') else: return render_template('person.html')
def forward_one_week(People, testing, accuracy, rate): new_infections = [] if testing: _test_people(People, accuracy, rate) for person in People: if person.alive and person.infected and not person.tested: new_infections.append(Person()) person.weeksSick += 1 if person.weeksSick >= 2: _alive_or_dead(person) People = [person for person in People if person.infected] People.extend(new_infections) return People
def main(): # with open('test.txt','w') as file: # file.write("==================\n") start = Node(position=[0, 27]) end = Node(position=[150, 150]) kevin = Person(x=30, y=50, velocity=0, direction=0) john = Person(x=10, y=90, velocity=0, direction=0) sam = Person(x=80, y=20, velocity=0, direction=0) mike = Person(x=10, y=-20, velocity=0, direction=0) adjacencyList, listOfShape = createAdjacencyList_new(nodes=[start, end], people=[kevin, john]) for i, j in adjacencyList.items(): i.cost += calculateWeight(end, i) # plotAllPath(adjacencyList, listOfShape) listOfPath = a_star(start, end, adjacencyList, listOfShape) return listOfPath
def outputData(self): file_r = open(self.filepath, 'r') lines = file_r.readlines() file_r.close() people = [] for line in lines: person_data = line person_data = person_data.strip() datalist = person_data.split(',') people.append(Person(datalist[0], datalist[1], datalist[2])) for person in people: print(person)
def __init__(self, m, f, years=100): # 0 is male, 1 es female self.men = [Person(0) for _ in range(m)] self.women = [Person(1) for _ in range(f)] self.time = years * 12 # couples to break self.couples = [] # number of couples self.noc = 0 # kids to be born self.kids = collections.deque() # number of birth per year self.nobpy = 0 # list of number of birth per year self.lnobpy = [] # number of death per year self.nodpy = 0 # list of number of death per year self.lnodpy = [] # list of number of men per year self.nom = [] # list of number of men per year self.now = []
def getPeopleInfo(self, outputFile): divs = self.Soup.find_all("div", class_="c411Listing jsResultsList") if len(divs) == 0: raise Exception( "No more records found. Total {} records found.".format( str(Person.totalPeople))) for div in divs: person = Person() val2 = div.find_all("div", class_="listing__row") val3 = div.find("h2", class_="c411ListedName") name = val3.find("a") person.setName(name.text.strip()) phone_no = div.find("span", class_="c411Phone") person.setPhone(phone_no.text.strip()) val1 = div.find_all("span", class_="c411ListingGeo") address = div.find("span", class_="adr") person.setAddress(address.text.strip()) person.saveRecord(outputFile) sleep(0.1)
def test(data, cpt_calc): print("This is the test table we are using") print( "________________________________________________________________________________________________________________" ) bayes_network = get_bayesian_network(cpt_calc) # Testdatensatz data_test = pd.read_csv('test_daten.csv', sep=";") data_test = data_test.where(pd.notnull(data_test), None) print(data_test.head()) print( "________________________________________________________________________________________________________________" ) print("This is the formated result of the Bayesian Network") print( "________________________________________________________________________________________________________________" ) # Ausgabe der vorhergesagten Werte for index, row in data_test.iterrows(): p = Person(data_test.iloc[index, :]) array = bayes_network.model.predict([p.get_bayes_query()]) print( str(index) + " (" + str(array[0][0]) + ")(" + str(array[0][1]) + ")(" + str(array[0][2]) + ")(" + str(array[0][3]) + ")(" + str(array[0][4]) + ")(" + str(array[0][5]) + ")(" + str(array[0][6]) + ")(" + str(array[0][7]) + ")(" + str(array[0][8][20:]) + ")") print( "________________________________________________________________________________________________________________" ) print("And this are the real values of the real table") print( "________________________________________________________________________________________________________________" ) # Vergleich mit echten Werten print(data.head())
def get_people(path): import logging logging.basicConfig( filename='log.log', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') people = [] with codecs.open(path, "r", "iso-8859-1") as f: assert isinstance(path, str) ind = path.rindex(sep) fi = path[ind:] year = re.search("[0-9]{4}", fi).group() year = int(year) d = {} first = True for line in f: fields = line.split("|") if first: for i in range(len(fields)): field = fields[i] d[i] = field.replace("\r\n", "") first = False else: p = Person(year) for i in range(len(fields)): field = fields[i] try: r = d[i] method = switcher.get(r, None) if method is not None: method(p, field) except KeyError: print(fields) p.valid = False people.append(p) return people
def __init__(self, disease, population=75000, area=5, hospital_beds=150, num_infected=10): self.population = population # Total population of city self.area = area # Area of the city self.disease = disease self.hospital_beds = hospital_beds # Number of hospital beds self.water_stations = 0 # Water Stations deployed to area self.susceptible = deque() # list of susceptible people to disease self.infected_contagious = deque( ) # List of infected, but not hospitalized people self.infected_hospitalized = deque() # List of hospitalized people self.infected_needs_bed = deque( ) # List of infected people in need of hospital beds, but don't have access self.recovered = deque() # List of recovered people self.dead = deque() # List of dead people self.possible_spread = 1 # possible for disease to spread in city at the moment? self.cumulative_days_needing_bed = 0 # days someone has needed bed self.new_infections = 0 self.new_deaths = 0 # create num_infected persons for x in range(num_infected): person = Person(id=x, age=random.randint(0, 100)) person.infect(self.disease) self.infected_contagious.append(person) for x in range(population - num_infected): self.susceptible.append( Person(id=x + num_infected, age=random.randint(0, 100)))
def faceDetection(): # global declarations global _firstFrame global _frameText global _frame global _face_cascade global _thresh global _frameText global _horizontal global _people global _originalFeed # Content Start _i = 0 facesDectected = _face_cascade.detectMultiScale(_grayFrame, 1.3, 5) for (x, y, w, h) in facesDectected: # Add new person to people list if face detected _people.append(Person()) currentPerson = _people[_i] getColor(_i) cv2.rectangle(_frame, (x, y), (x + w, y + h), (currentPerson.color[0], currentPerson.color[1], currentPerson.color[2]), 2) topLeft = [(x + w, y), (x + int(round(2.5 * w)), y + int(round(1.5 * h)))] topRight = [(x, y), (x - int(round(1.5 * w)), y + int(round(1.5 * h)))] bottomLeft = [(x + int(round(1.5 * w)), y + int(round(2.5 * h)) + (h / 2)), (x + (2 * w) + w, y + int(round(5.5 * h)))] bottomRight = [(x - int(round(w / 2)), y + int(round(2.5 * h)) + (h / 2)), (x - (2 * w), y + int(round(5.5 * h)))] # top left cv2.rectangle(_frame, topLeft[0], topLeft[1], currentPerson.color, 2) # top right cv2.rectangle(_frame, topRight[0], topRight[1], currentPerson.color, 2) # bottom left cv2.rectangle(_frame, bottomLeft[0], bottomLeft[1], currentPerson.color, 2) # bottom right cv2.rectangle(_frame, bottomRight[0], bottomRight[1], currentPerson.color, 2) motionDetection(x, y, w, h, _i) _i += 1
def read_from_file(destinations, bus, person): ''' read all the information from files :param destinations: :param bus: :param person: :return: ''' scriptpath = os.path.dirname(__file__) filename = os.path.join(scriptpath, 'destination.txt') f = open(filename) lines = [line.rstrip('\n') for line in f] for item in lines: des = Station(item) destinations.append(des) del destinations[0] f.close() scriptpath = os.path.dirname(__file__) filename = os.path.join(scriptpath, 'bus.txt') f = open(filename) lines = [line.rstrip('\n') for line in f] for item in lines: item = item.split('\t') pos = len(item) - 1 tmp = Bus(item[0], item[2], item[4], item[pos - 2], item[pos]) bus.append(tmp) del bus[0] f.close() scriptpath = os.path.dirname(__file__) filename = os.path.join(scriptpath, 'person.txt') f = open(filename) lines = [line.rstrip('\n') for line in f] for item in lines: item = item.split('\t') end = len(item) - 1 status = False if item[end - 2] == 'Onboard': status = True num = item[end] if num == 'None': num = None else: num = str(num) tmp = Person(item[0], item[1], item[3], status, num) person.append(tmp) del person[0] f.close()
def create(self): """Create and add an object to the store.""" store = self._store p = Person() p.setId('bob') p.setFirstName('Robert') store.addObject(p) self.waitRandom() assert store.hasChangesForCurrentThread() store.saveChanges() assert p.isInStore() assert not store.hasChangesForCurrentThread() return p
def updatePeople(): print("entered thread") with open(cwd + '/Logs', 'a+') as outfile: while True: a = 1 for data in people_dict: a += 1 if a % 1000 == 0: print("======\n======") print(a) people = Person(data, people_dict[data]) # print("createPerson: ", (time.time()-t)*10000) dict = people.getData(route_dict, off_stop_dict, arrival_dict) # print("\n") # t=time.time() # json.dump(dict,outfile) # print("dump: ", (time.time()-t) * 10000) # t=time.time() st = json.dumps(dict) outfile.write(st + '\n')
def getInfo(): parameters = Parameters() folder = "s1" person = Person() path = os.path.abspath(os.getcwd( )) + "/" + parameters.folder + "/" + folder + "/" + "Info.txt" try: handle = open(path, "r") for line in handle: masSplit = line.split(":") if masSplit[0] == "FIO": person.firstName = masSplit[1] elif masSplit[0] == "DateBirth": person.dateBirth = masSplit[1] elif masSplit[0] == "Position": person.position = masSplit[1] print(person.firstName) print(person.dateBirth) print(person.position) handle.close() except Exception as inst: print(inst) print('Ошибка получения данных.')
def test_rand(self): from random import randint names = [ "john", "matt", "alex", "cam", "vinny", "joe", "steve", "mary", "ash", "joel", "henry", "brendan", "roger", "don", "whimpy", "chosen one", "master", "frog", "horse", "cat", "blop", "god", "morgan", "freeman", "sean", "shaun", "dick", "jeff", "leroy", "lee", "santa" ] for _ in range(40): name, age = names[randint(0, len(names) - 1)], randint(10, 99) person = Person(name, age) self.assertEqual(person.info, name + "s age is " + str(age), "Testing for %s and %s" % (repr(name), age))
class Request: action = "GET" person = Person(2,"Nitin",26) def __init__(self, action, person): self.action = action self.person = person def printRequest(self): print "action:", self.action self.person.showPersonRecord() def toJSON(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
def main(): s1 = UG('Hunter Schilb', 2017) s2 = UG('Wendy Posada', 2017) s3 = UG('Jason Wang', 2018) s4 = Grad('Matt Damon') s5 = UG('Mark Zuckerberg', 2019) p1 = BabsonPerson('Zhi Li') p2 = BabsonPerson('Shankar') p3 = BabsonPerson('Steve Gordon') q1 = Person('Bill Gates') q2 = Person('Beyonce') studentList = [s1, s2, s3, s5, s4] BabsonList = studentList + [p1, p2, p3] allList = BabsonList + [q1, q2] # for everyone in studentList: # print(everyone) # # for everyone in BabsonList: # # print(everyone) for everyone in allList: print(everyone)
def main(): # set a name to a feed yasmin = Feed.Feed("yasmin") esther = Feed.Feed("esther") vera = Feed.Feed("vera") # Feed erstellen yasmin.generateOwnFeed() esther.generateOwnFeed() vera.generateOwnFeed() # set person yasminPerson = Person.Person(yasmin.id, yasmin.name, yasmin) yasminPerson.follow(esther.id, esther.name) yasminPerson.follow(vera.id, vera.name) yasminPerson.printFollowList() yasminPerson.unfollow(vera.id) yasminPerson.printFollowList() veraPerson = Person.Person(vera.id, vera.name, vera) veraPerson.follow(esther.id, esther.name) veraPerson.follow(yasmin.id, yasmin.name) veraPerson.printFollowList()
def addPersonWithPermissions(self, admin=True): array = ["", "", "", "", admin] PersonList = ['First name', 'last name', 'username', 'password'] for i in range(len(array)): while array[i] == "": try: array[i] = str(input("What's the " + PersonList[i] + "? ")) except: print("something went wrong.") try: userId = int(self.__Users[:-1].getUserId()) + 1 except: userId = 1 self.__Users.append( Person(userId, array[0], array[1], array[2], array[3], array[4]))
def make_people_pair(save=True): """ Generates two peeps with each having valid keys. """ A = Person() B = Person() A_dump = json.dumps( { 'public_key': A.public_key, 'private_key': A.private_key }, indent=4) B_dump = json.dumps( { 'public_key': B.public_key, 'private_key': B.private_key }, indent=4) if save: with open('test_subject1.json', 'w') as f: f.write(A_dump) with open('test_subject2.json', 'w') as f: f.write(B_dump)
def create_person(field_lookup, data): """ Creates a Person object given data for a person and a dict containing mappings from field to index in list for data. :param field_lookup: (dict) dict mapping fields needed for person data to indices. :param data: (list) list of data to use for creating person. :return: (Person) new Person object with given data. """ return Person(data[field_lookup['first_name']], data[field_lookup['last_name']], data[field_lookup['year']], data[field_lookup['major']], data[field_lookup['academic_interests']], data[field_lookup['post_grad_goal']], data[field_lookup['software_experience']], data[field_lookup['hobbies']])
def Update(self): """ Updates the floor's state. Adds more people to the floor. """ numberOfNewPeople = np.random.poisson( Floor.ArrivalMeans[int(TickTimer.GetCurrentSecondsOfDay() / 3600), self.FloorNumber] / 3600) for i in range(numberOfNewPeople): self.__people.Push( Person(self.__selectDest(), self.FloorNumber, TickTimer.GetCurrentTick())) if numberOfNewPeople > 0: return True else: return False
def readFromFile(self, fileName): ''' reads the list from the text file ''' result = [] try: f = open(fileName, "r") line = f.readline().strip() while len(line) > 0: line = line.split(",") result.append(Person(int(line[0]), line[1], line[2])) line = f.readline().strip() f.close() except Exception as e: print("An error ocured-" + str(e)) self.__repo = result
def process_csv_file(filename): people = [] errors = [] with open(os.path.join(args.input_dir, filename)) as csv_file: reader = csv.DictReader(csv_file) row_id = 0 for row in reader: row_id += 1 try: person = Person(row['INTERNAL_ID'], row['FIRST_NAME'], row['MIDDLE_NAME'], row['LAST_NAME'], row['PHONE_NUM']) people.append(person) except Exception as e: errors.append((row_id, e)) return (people, errors)
def SIR_Model(S, I, R, D, reproduction_number, dailyDeathRate, rLen, IR, interactions, pop): pop = [Person(i, 'S') for i in range(int(totalpop))] pop[len(pop) - 1].type = 'I' for i in t: S[i] = sum([p.type == 'S' for p in pop]) I[i] = sum([p.type == 'I' for p in pop]) R[i] = sum([p.type == 'R' for p in pop]) D[i] = sum([p.type == 'D' for p in pop]) pop = M.addDay(pop.copy()) pop = M.dailyInfect(I[i], pop.copy(), IR, interactions, totalpop) pop = M.removed(pop.copy(), dailyDeathRate, rLen) l = M.daily_reproduction_number([p for p in pop if p.type == "I"], rLen) reproduction_number[i] = np.average(l) return S, I, R, D, reproduction_number, pop
def create_people_list(tsv_path_list): people = [] for tsv_file_path in tsv_path_list: with open(tsv_file_path, "r") as f: reader = csv.DictReader(f, delimiter='\t') # Skip header next(reader) for row in reader: try: people.append( Person.create_person(row["name"], row["abstract"])) except ValueError as e: logger.warning(e.args) return people
def choice2(self): John = Person('John','22','M','China','None','None','Basketball') Liz = Person('Liz','22','F','China','None','None','Dance') print ''' ======电话铃响~~====== 请选择: 1.接听 2.不接听 ''' ch2 = raw_input('请输入您的选择:').strip() if ch2 == '1': gl.END1 += 1 Liz.talk('我现在在xxx公司面试,等我的好消息!') John.talk('我在家做好饭等你回来庆祝!') if ch2 == '2': gl.END2 += 1 print '{0}发来的短信:我现在在xxx公司面试,等我的好消息!'.format(Liz.name) John.talk('祝你好运!')
def choice3(self): John = Person('John','22','M','China','None','None','Basketball') Liz = Person('Liz','22','F','China','None','None','Dance') Peter = Person('Peter','28','M','USA','Manager','30000','Golf') print ''' 请选择: 1.质问Liz 2.不质问 ''' ch3 = raw_input('请输入您的选择:').strip() if ch3 == '1': gl.END1 += 1 John.talk('约了谁?') print '{0}:{1}要带我去打{2}'.format(Liz.name,Peter.name,Peter.specialty) John.talk('为什么是他?') Liz.talk('他比你有钱比你帅,我不想过这种贫穷的日子了,我们分手吧!') if ch3 == '2': gl.END2 += 1 print '{0}:内心很难受!但他默默忍了下来!'.format(John.name)
def parseRoster(self,filename): rosterFile = open(filename) rosterReader = csv.reader(rosterFile) for row in rosterReader: person = Person(row[0]) person.gender = row[1] person.experience = int(row[2]) if row[3] == "Y": person.car = True person.addConflict(row[4]) self.roster.append(person)
def addPerson(person): print("New passenger's name:") name = input() print("New passenger's departure:") dep = input() print("New passenger's destination:") des = input() while des == dep: print("Destination is the same with departure! Input again, please.") des = input() tmp = Person(name, dep, des) for item in bus: # find if there are any buses have seat available for this passenger if tmp.getRoute() == item.getRoute() and not item.isFull(): tmp.boardSuccess() tmp.setBusnum(item.getNumber()) item.addPerson(tmp) print("Board successfully!") person.append(tmp) return # if no seats availble: print("All bus full or your route is not availble! You have to wait.") person.append(tmp)
def __str__(self): return ';'.join([Person.__str__(self),str(self.mn)])
def __init__(self,nn,vn,mn): Person.__init__(self,nn,vn) self.setMatrikelnummer(mn)
def __init__(self, classSchedule=None, **kwargs): Person.__init__(self, **kwargs) if classSchedule is None: self.classSchedule = Schedule() else: self.classSchedule = classSchedule
def __init__(self, name, cash=3000): Person.__init__(self) self.name = name self.cash = cash self.bet = 0 self.doubled_down = False
def clear_hand(self): Person.clear_hand(self) self.doubled_down = False
from Person.Person import * from Foods.Food import * me=Person('John',90) print "Name: %s\nHealth: %i" % (me.name, me.health) food=Food('kanin',10) poison=Food('lason',-10) me.eat(food.value) print "Health is %s" % (me.health) me.eat(poison.value) print "Health is %s" % (me.health)