def test_real_query(): """" Do the test Using """ p = People() assert p is not None assert len(p.query()) == 3
def test_real_query_2(): """" Do the test Using the read Database """ p = People() assert p is not None assert len(p.query()) == 3
def __init__(self): People.__init__(self) BaseWidget.__init__(self,'People window') #Definition of the forms fields self._peopleList = ControlList('People', plusFunction = self.__addPersonBtnAction, minusFunction = self.__rmPersonBtnAction) self._peopleList.horizontalHeaders = ['First name', 'Middle name', 'Last name']
def main(): first = People(18, "Helen") second = People(25, "Rick") third = People(40, "Margie") older = first.getOlder(second) #old = first.getOlder(3) print older, "is the oldest out of", first.name, "and", second.name print third.getOlder(first), "is the oldest out of", first.name, "and", third.name
def __init__(self): People.__init__(self) BaseWidget.__init__(self, "People window") # Definition of the forms fields self._peopleList = ControlList( "People", plusFunction=self.__addPersonBtnAction, minusFunction=self.__rmPersonBtnAction ) self._peopleList.horizontalHeaders = ["First name", "Middle name", "Last name"]
def get_indonesia(): """ only DB_INSTANCE serve /indonesia to preserve quota usage """ if not environ['DB_INSTANCE'] in request.url_root: return '[]' nitems = int(request.form['nitems']) page = int(request.form['page']) offset = 0 if page > 0: offset = (page-1) * nitems # process phase 1 (update database) # now handled by cron per 10 minutes # process phase 2 (response with data from memcache or Datastore) # unfortunately total data from Datastore is bigger than max allowed on memcache (1MB) # so we will split the query, and optimized with the current profile on memcache profiles = deserialize_entities(memcache.get('profile_by_activity_updated:%d:%d' % (nitems, offset))) if profiles is None: profiles = Profile.query().order(-Profile.activity_updated). \ fetch(nitems, offset=offset, projection=[Profile.activity_updated]) if not memcache.add('profile_by_activity_updated:%d:%d' % (nitems, offset), serialize_entities(profiles), 60): error('Memcache set failed: profile_by_activity_updated:%d:%d' % (nitems, offset)) indonesia_users = [] for profile in profiles: # get data from memcache or datastore for specific user p = get_profile(profile.key.id()) # 'updated' is field from Google+ API activities related to specified user last_activity = '(unknown)' activity_updated = profile.activity_updated if activity_updated is not None: last_activity = get_delta(activity_updated) if p.activity_data is not None: activity_data = json.loads(p.activity_data) items = activity_data['items'] #items = activity_data.get('items', []) if len(items) > 0: item_object = items[0]['object'] t_reshare = str(item_object['resharers']['totalItems']) t_plusone = str(item_object['plusoners']['totalItems']) t_comment = str(item_object['replies']['totalItems']) last_activity += '<br/>('+t_reshare+' reshares, '+t_plusone+' <b>+1</b>, '+t_comment+' comments)' # user profile is a return of Google+ API people person = People(p.user_data) if person is not None: user_dict = {'displayName': person.displayName, 'id': person.id, 'name': person.name, 'image': person.get_image(), 'verified': person.verified, 'last_activity': last_activity} indonesia_users.append(user_dict) data_indonesia_users = {'total_data': count_indonesia(), 'paging_data': indonesia_users} return json.dumps(data_indonesia_users)
def __init__(self): People.__init__(self) BaseWidget.__init__(self,'People window') AddMenuFuntionality.__init__(self) self._panel = ControlDockWidget() #Definition of the forms fields self._peopleList = ControlList('People', plusFunction = self.__addPersonBtnAction, minusFunction = self.__rmPersonBtnAction) self._peopleList.horizontalHeaders = ['First name', 'Middle name', 'Last name']
def test_fake_query(mock_function): """" Do the test using fake data. """ mock_function.return_value = [('Superman', ' 1'), ('Avengers', '2')] p = People() assert p is not None pprint(p.query()) print("Hi can be seen with -s flag") assert len(p.query()) == 2 names = [rec[0] for rec in p.query()] assert "Superman" in names assert "Avengers" in names
def initialize_container(self): """ 产生6000个人, 坐标是随机 """ for i in range(int(self.numberOfPeople)): x = Decimal(random.uniform(0, 100)).quantize(Decimal("0.0")) y = Decimal(random.uniform(0, 100)).quantize(Decimal("0.0")) new_people = People(x, y, False) self.SUSCEPTIBLE.append(new_people) for i in range(2): # 产生2个零号病人 x = Decimal(random.uniform(0, 100)).quantize(Decimal("0.0")) y = Decimal(random.uniform(0, 100)).quantize(Decimal("0.0")) new_people = People(x, y, True) self.INFECTED.append(new_people)
def __init__(self): People.__init__(self) BaseWidget.__init__(self, 'People window') AddMenuFuntionality.__init__(self) self._panel = ControlDockWidget() #Definition of the forms fields self._peopleList = ControlList( 'People', add_function=self.__addPersonBtnAction, remove_function=self.__rmPersonBtnAction) self._peopleList.horizontalHeaders = [ 'First name', 'Middle name', 'Last name' ]
def _setup_people(self): peoples = {} # peoples_matrix: [[id, wealth, age, metabolism, life_expectancy, vision, axis_x, axis_y],] peoples_matrix = self._generate_peoples() for i in range(peoples_matrix.shape[0]): peoples[i] = People(self, *peoples_matrix[i]) return peoples
def listMongodb(): conection = Connection("test", "People") modelPeopleList = [ People("hugo1", "roca1", "24", "*****@*****.**", "1"), People("hugo2", "roca2", "24", "*****@*****.**", "2"), People("hugo3", "roca3", "24", "*****@*****.**", "3"), People("hugo4", "roca4", "24", "*****@*****.**", "4"), People("hugo5", "roca5", "24", "*****@*****.**", "5") ] collection = conection.getConnection(); for people in modelPeopleList: #print(people.toDbCollection()) collection.insert(people.json())
def test_fake_query2(mock_function): """" Do the test using fake data. Slightly different call than the previous version. But with the same result """ #mock_function.return_value = [('Superman', ' 1'), ('Avengers', '2')] p = People() assert p is not None pprint(p.query()) print("Hi can be seen with -s flag") assert len(p.query()) == 2 names = [rec[0] for rec in p.query()] assert "Superman" in names assert "Avengers" in names assert "tim" not in names
def test_init(): """ Make sure we can access this Object :return: """ p = People() assert p is not None
def createPeople(self, homeNode, workNode, number): people = [] if isinstance(number, int): for i in range(0, number): people.append(People(i, homeNode, workNode, "S")) return people else: print("Wrong format of number " + str(number) + "of people in Node " + homeNode + " working in " + workNode) print( "Skipping creating people, check this out and clean data accordingly..." )
def __init__(self, databaseName, sizesFilename, peopleFilename, sizeCatalogFilename): self.databaseName = databaseName # (!) change this line to make it work # connect with database self.db = MySQLdb.connect(host="localhost", user="******", passwd="root", db=self.databaseName) self.io = IO() sizesDataLines = self.io.ReadFile(sizesFilename) peopleDataLines = self.io.ReadFile(peopleFilename) sizeCatalogDataLines = self.io.ReadFile(sizeCatalogFilename) self.sizes = Sizes(sizesDataLines) self.people = People(peopleDataLines) self.sizeCatalog = SizeCatalog(sizeCatalogDataLines)
def update_profile(): user_profile = key.get() if user_profile is None: user_profile = Profile(key=key, user_data=user_json, user_lastupdate=datetime.now()) else: user_profile.user_data = user_json user_profile.user_lastupdate = datetime.now() activity_updated = user_profile.activity_updated if activity_updated is not None: if datetime.now() - activity_updated > timedelta( days=delay_for_users_after_days): # delay next schedule of in-active user to next 1 day user_profile.user_lastupdate = datetime.now( ) + timedelta(days=1) # read content from Google+ API People person = People(user_json) user_profile.user_is_verified = person.verified user_profile.put()
''' @File : 5_fight.py @Time : 2020/04/14 20:22:04 @Author : xdbcb8 @Version : 1.0 @Contact : [email protected] ''' # here put the import lib from Dog import Dog from People import People from random import randint dog = [Dog(), Dog(), Dog()] people = [People(), People()] def choose_attact(a, b): # 判断游戏是否还可以进行下去 flag1 = True flag2 = True for f in a: if f.get_blood() > 0 and f.get_attack() > 0: flag1 = False for s in b: if s.get_blood() > 0 and f.get_attack() > 0: flag2 = False if flag1: print(a[0].get_sort(), "defeat")
def batchSearch(request): form = UploadFileForm(request.POST, request.FILES) print request.FILES['linkedFile'] #fname = dirname(abspath(request.FILES['linkedFile'])) workbook = None # print "Form is Valid" filehandle = request.FILES['linkedFile'] ''' Below we have used PyExcel for excel sheet operations, follow online documents for more details into the SDK. ''' workbook = filehandle.get_sheet() workbook.name_columns_by_row(1) records = workbook.to_records() message = '' sParams = {} linkObj = Authenticate('*****@*****.**','chandraisgr8') failReads = 0 successReads = 0 sParamsList = [] locationsList = [] for r in records: if r['Full Name']=='' or r['Full Name']=='?': if r['Email']: print "" else: if r['No.'] == '': l = str(r['Name']).split("/") for i in l: locationsList.append(i) # LIST SAVED TO SESSION" res = CSPerson.objects.order_by('person.firstName') allpeople = [] for r in res: res1 = r['person'] allpeople.append(People(res1['firstName'],res1['lastName'],'')) # print allpeople.__str__() for r in records: if r is None: failReads = failReads + 1 continue sParams = {} goodRecord = False ''' Peculiar possibilities based on the doc provided. ''' if r['Name']=='Total': break if r['Name']=='Arizona': continue if r['Full Name']!='' or r['Full Name']!='?': thename = r['Full Name'] thename = re.sub(r'\(.+?\)\s*', '', thename ) print "Cleaned Full Name : "+thename if thename.strip()=='': continue # name = r['Full Name'].split(' ') name = thename.strip().split(' ') goodRecord = True if name: nlist = list(name) ''' Still no check for the cases for middle names. ''' if len(nlist)>=2: sParams['firstName'] = name[0].strip() #Removing Trailing Spaces sParams['lastName'] = name[1].strip() else: # sParams['firstName'] = '' # sParams['lastName'] = '' sParams['firstName']=name[0] sParams['lastName']='' else: goodRecord = True sParams['firstName']='' sParams['lastName']='' print "Checking for "+sParams['firstName']+", "+sParams['lastName'] ''' Check for record already available. ''' inrecords = False # Need to Optimize code here to use something like Hash (make it faster) ''' Below code checks if the entry was already there in database. If it was there then it skips to the next record. ''' for p in allpeople: # print "Inside People Records .." if ((p.firstName.lower()==sParams['firstName'].lower()) and (p.lastName.lower()==sParams['lastName'].lower())): print p.firstName+" "+p.lastName+" already in records" print "RECORD ALREADY PRESENT" inrecords = True break if inrecords==True: print "CONTINUE TO NEXT RECORD" continue print "CONTINUE DID NOT EXECUTE" if locationsList: sParams['locations'] = locationsList # request.session['locations']=locationsList # print "LOCATION LIST SAVED TO SESSION" if r['Email']: # print "" sParams['email'] = r['Email'] else: print "No Email" sParams['email'] = ' ' goodRecord = True if goodRecord is True: print "CALLING PERFORM CS SEARCH" resp = Authenticate.performCSSearch(linkObj, sParams, 'localhost', 27017, 'test3') # resp = 'Success' # print "sparams : " # print sParams # resp = 'Success' if resp.startswith('Success'): print "Successfully found" successReads = successReads + 1 else : print "Unfortunately Not Found" failReads = failReads + 1 # if goodRecord is True: sParamsList.append(sParams) print "SEARCH OPERATION COMPLETED AND DATABASE UPDATED." for s in sParamsList: print s # resp = Authenticate.performCSSearch(linkObj, s, 'localhost', 27017, 'test3') # resp = Authenticate.performSearch(linkObj, s, 'localhost', 27017, 'test3') # resp = 'Success' message = 'The records from the uploaded file have been processed. ' message = message + 'Success : ' + str(successReads)+' Failed : ' + str(failReads) msg = {'type':'I','message':message} context = { 'msg':msg } if successReads!=0: return render(request, 'testApp/searchGrad.html', context) else: msg = {'type':'I','message':message} context = { 'msg':msg } # return render(request,'testApp/message.html', context) return render(request, 'testApp/searchGrad.html', context)
from People import People from pprint import pprint as pp p = People(123, 'alex', 10000000) p.get_id() pp(People.__dict__) print(p.__dict__) print(p._People__star)
break_seconds = input("Enter break seconds (3600): ") break_seconds = int( break_seconds) if break_seconds != '' and break_seconds.isdecimal( ) and int(break_seconds) > 0 else 3600 year = input("Enter year (2019): ") year = int(year) if year != '' and year.isdecimal( ) and int(year) >= 2017 and int(year) < 2030 else 2019 print("Loading data...") trainer1 = "trainer#1" # logger.log('start load demand',2) demand = People() demand.loadFromXLS(workbook='demand_' + str(year) + '.xlsm', worksheet='demand') # print('demand') if printflag else None # printDict(demand.people,"\t") if printflag else None # logger.log('start load history',2) history = People() history.loadFromXLS('demand_' + str(year) + '.xlsm', worksheet='histor') # print('history') if printflag else None # printDict(history.people,"\t") if printflag else None # logger.log('start load rules',2) rules = Rules() rules.loadFromCSV('rules2_' + str(year) + '.csv') # print('rules') if printflag else None
from People import People pp = People() pp.checkMe()
def getInfo(dictionary, movies): ErrorFile = open('Data\errors.txt', 'a') scannedMovies = [] num_in_line = 0 movie_count = len(movies) for movie in movies: num_in_line = num_in_line + 1 try: # Creating lists containing information to be written to a file movie_info = [] similar_info = [] genre_info = [] location_info = [] plays_in_info = [] cast_info = [] crew_info = [] works_on_info = [] writers_info = [] creates_info = [] music_info = [] artist_info = [] heard_in_info = [] award_record_info = [] start_time = time.time() title = setTitle(movie) print('\n\n') looking_at = 'Scanning through ' + title print(looking_at.center(100, '=')) print('\n\n') rating = setRating(movie) tconst = setTconst(movie) thisMovie = Movie(title, rating, tconst) dictionary[tconst] = title persons = People(tconst).getPeople() cast = [] writers = [] crew = [] director = None for p in range(len(persons)): try: if (persons[p].getDepartment() == 'Directed'): director = persons[p] dname = director.getName() dFRY = director.getFRY() dBdate = director.getBirthday() elif (persons[p].getDepartment() == 'Cast'): cast.append(persons[p]) elif (persons[p].getDepartment() == 'Writing Credits'): writers.append(persons[p]) else: crew.append(persons[p]) except: pass if director == None: dname = 'NULL' dFRY = 'NULL' dBdate = 'NULL' movie_info.append([ title, thisMovie.getRD_date(), thisMovie.getTime_len(), thisMovie.getContentRating(), rating, thisMovie.getBO_GrossUSA(), thisMovie.getBO_GrossWorld(), thisMovie.getBudget(), thisMovie.getON_Earnings(), thisMovie.getON_Date(), dname, dFRY, dBdate ]) sims = thisMovie.getSimilarMovieTitles() for s in sims: similar_info.append([title, s]) genres = thisMovie.getGenres() for g in genres: genre_info.append([title, g]) locations = thisMovie.getLocations() for local in locations: location_info.append([ title, local.getCountry(), local.getCity(), local.getState() ]) for p in cast: plays_in_info.append([p.getName(), title]) cast_info.append([p.getName(), p.getGender(), p.getBirthday()]) for c in crew: crew_info.append( [c.getName(), c.getDepartment(), c.getBirthday()]) works_on_info.append([c.getName(), title]) for w in writers: writers_info.append([w.getName(), w.getBirthday()]) creates_info.append([w.getName(), title]) awards = thisMovie.getAwards() for a in awards: award_record_info.append( [title, a.getAward(), a.getYear(), a.getCategory()]) music = thisMovie.getMusic() if music != None: song_list = music.songs() for song in song_list: music_info.append([song.getTitle(), song.getlength()]) artist_info.append([song.getTitle(), song.getAuthor()]) heard_in_info.append([title, song.getTitle()]) writeToFiles(movie_info, similar_info, genre_info, location_info, plays_in_info, cast_info, crew_info, works_on_info, writers_info, creates_info, music_info, artist_info, heard_in_info, award_record_info) # Movie was successfuly scanned for information scannedMovies.append(movie) end_time = time.time() print('\nEnded search in ' + str(end_time - start_time) + ' seconds on movie ' + title + ' , movie number ' + str(num_in_line) + ' out of ' + str(movie_count) + '\n\n') except Exception as err: print('\n\nFailed to scan movie ' + setTitle(movie) + '\n\n') toWrite = '\nFailed to scan movie ' + setTitle(movie) toWrite = toWrite + '\n\tError due to ' + str(err) ErrorFile.write(toWrite) ErrorFile.close() return scannedMovies
min_dist = min(distances) # tell elevator it has been chosen self.elevators[min_dist[1]].pickup_on_floor( people.cur_floor, people.direction) # arrange this people to the list self.people_from_floors[people.cur_floor][people.direction].put( people) # change elevator future state self.elevators[min_dist[1]].future_state = people.direction def status(self): for elevator in self.elevators: elevator.print_status() if __name__ == '__main__': elevator_num = raw_input('How many elevators: ') floor_num = raw_input('How many floors: ') ecs = ElevatorControlSystem(int(elevator_num), int(floor_num)) ecs.status() while True: behavior = raw_input('Enter behavior: ') if len(behavior) == 0: ecs.step() elif behavior[0] == 'p': parts = behavior.split(',') people = People(int(parts[1]), int(parts[2]), int(parts[3])) ecs.pickup(people) ecs.status()
def main(): print "test begining" peoOne=People("zym","16","男") peoOne.displayCount()
randomCheck = random.randint(0, 2) if randomCheck is 0: bus.status = "atStart" elif randomCheck is 1: bus.status = "inRoute" elif randomCheck is 2: bus.status = "atEnd" temp_for_bus.append(bus) for bus in temp_for_bus: print("Bus route NO." + str(bus.route) + " Max load is " + str(bus.max_load) + " people.") # generating people to ride the buses temp_for_people = [] for i in range(1, 500): person = People("person" + str(i), random.randint(1, 100)) temp_for_people.append(person) # putting people on buses randomly for i in range(0, len(temp_for_people)): temp_for_bus[random.randint(0, 12)].people_on.append(temp_for_people[i]) # setting departure and arrival towns for each bus for i in range(0, len(temp_for_bus)): temp_for_bus[i].departure_town = temp_for_town[random.randint(0, 13)] randomcheck = random.randint(0, 1) if randomcheck == 0: temp_for_bus[i].arrival_town = temp_for_bus[ i].departure_town.first_road_to elif randomcheck == 1: temp_for_bus[i].arrival_town = temp_for_bus[