def _execute_command(self, command): """ Execute the given command. Any message starting with double dashes (--) will be considered a command. Args: command (str): The command to be parsed Returns: bool: True if the command was '--guess', else False. """ if command == '--guess': if self.n_questions_left == MAX_QUESTIONS: print( info_message( "You need to ask at least one question before making a guess." )) return False else: return True if command in self.commands: self.commands[command]() else: print(info_message("Invalid command '{}'".format(command))) return False
def __init__(self): """ Used to host a Turing Test. """ super(Tester, self).__init__() # Connect to the bot self.bot = connect_to_cleverbot() print(info_message("Successfully connected to cleverbot")) # Set up the routes. self.route(ROUTE_INBOX, method='POST', callback=self.receive_and_send_message) self.route(ROUTE_CONNECT_INFO, method='POST', callback=self.has_connected) self.route(ROUTE_NEW_ROUND, method='POST', callback=self.start_new_round) self.route(ROUTE_CHECK_GUESS, method='POST', callback=self.check_guess) self.route(ROUTE_ENDED_GAME, method='POST', callback=self.game_ended) # Initalized later self.tester_type = None # Estimate writing speed # If false, a random writing speed will be chosen # The writing speed is in chars/sec print(get_chat_line_separator()) if 'y' in input("Estimate writing speed (y/N): "): self.writing_speed = min(estimate_writing_speed(), 0.35) else: self.writing_speed = 0.15 + random() * 0.2 print(info_message("Writing speed estimated to {:.3f} characters/sec".format(self.writing_speed)))
def connect_to_tester(): """ Connect to the tester Returns: HTTPConnection: A connection to the tester """ while True: try: # Get the host host = input( "Please provide the IP of the host (input nothing for localhost): " ).strip() if not host: host = "localhost" # Connect print(info_message("Connecting to tester...")) connection = HTTPConnection(host, PORT) # Inform the tester about the connection connection.request('POST', ROUTE_CONNECT_INFO, socket.gethostbyname(socket.gethostname())) print(info_message(connection.getresponse().read().decode())) break except socket.gaierror: print(info_message("Invalid host '{}'".format(host))) return connection
def connect_to_tester(): """ Connect to the tester Returns: HTTPConnection: A connection to the tester """ while True: try: # Get the host host = input("Please provide the IP of the host (input nothing for localhost): ").strip() if not host: host = "localhost" # Connect print(info_message("Connecting to tester...")) connection = HTTPConnection(host, PORT) # Inform the tester about the connection connection.request('POST', ROUTE_CONNECT_INFO, socket.gethostbyname(socket.gethostname())) print(info_message(connection.getresponse().read().decode())) break except socket.gaierror: print(info_message("Invalid host '{}'".format(host))) return connection
def start_new_round(self): """ Start a new round. For the round to be started, you need to select whether you our the bot is answering. Returns: str: Confirmation message. """ # Get the tester type print(get_chat_line_separator()) print(info_message("New round started by the user.")) tester_type = input("Will the bot or you be answering the questions ({}/{}): ".format(TESTER_BOT, TESTER_HUMAN)) while tester_type not in [TESTER_HUMAN, TESTER_BOT]: tester_type = input("'{}' is not a valid tester type, select either {} or {}: ".format(tester_type, TESTER_BOT, TESTER_HUMAN)) if tester_type == TESTER_BOT: print(info_message("The bot will be answering the questions. Sit back and relax!")) if tester_type == TESTER_HUMAN: print(info_message("You will be answering the questions. Good luck.")) print(info_message("Waiting for first message...")) self.tester_type = tester_type # Reset the bot self.bot.reset() return "New round ready"
def _make_guess(self): """ Guess whether the tester is a bot or a human. """ guess_tester_type = input( "What do you think the tester is ({}/{}): ".format( TESTER_BOT, TESTER_HUMAN)) while guess_tester_type not in [TESTER_HUMAN, TESTER_BOT]: guess_tester_type = input( "{} is not a valid tester type, select either {} or {}: ". format(guess_tester_type, TESTER_BOT, TESTER_HUMAN)) print( info_message("You guessed {}. Waiting for response...".format( guess_tester_type))) self.connection.request('POST', ROUTE_CHECK_GUESS, guess_tester_type) result = self._receive_message() time.sleep(1) if result == GUESS_CORRECT: print(info_message("Your guess was correct!")) self._update_points() else: print(info_message("Your guess was wrong...")) self._display_score()
def _start_new_round(self): """ Start a new round. """ self.n_questions_left = MAX_QUESTIONS self.n_rounds += 1 print(info_message("Starting new round. Waiting for confirmation from tester...")) self.connection.request('POST', ROUTE_NEW_ROUND, "") print(info_message(self._receive_message()))
def _start_new_round(self): """ Start a new round. """ self.n_questions_left = MAX_QUESTIONS self.n_rounds += 1 print( info_message( "Starting new round. Waiting for confirmation from tester...")) self.connection.request('POST', ROUTE_NEW_ROUND, "") print(info_message(self._receive_message()))
def generate_csv_report(connections): """Generate a csv report with details of each alumni if they used cars before and after""" alumnis = {} cursor = connections['smarttraffic'].cursor( cursor_factory=psycopg2.extras.DictCursor) """Count the distances that users had to travel prior Ucarpooling""" querystring = """ select itinerary."ucarpoolingProfile_id", route."aggCost" from uccarpool_useritinerary as itinerary inner join uccarpool_itineraryroute as route on route.itinerary_id=itinerary.id """ cursor.execute(querystring) rows = cursor.fetchall() for row in rows: cost = row['aggCost'][-1] if row['aggCost'] else 0 alumnis[row['ucarpoolingProfile_id']] = {'before': cost} """Count the users that has vehicles after Ucarpooling""" querystring = """ select itinerary."ucarpoolingProfile_id" , carpool.id, route."aggCost" from uccarpool_useritinerary as itinerary inner join uccarpool_itineraryroute as route on route.itinerary_id=itinerary.id left join uccarpool_carpool as carpool on itinerary."ucarpoolingProfile_id"=carpool.driver_id """ cursor.execute(querystring) rows = cursor.fetchall() for row in rows: cost = row['aggCost'][-1] if row['aggCost'] else 0 alumnis[ row['ucarpoolingProfile_id']]['after'] = cost if row['id'] else 0 """Write in the csv data""" with open(settings.CSV_REPORT_DISTANCE_FILE_PATH, 'w', newline='', encoding=settings.ASSIGNED_FILES_ENCODING) as csv_output_file: """Writing the headers of the output_data file""" output_csv_fieldnames = ['before', 'after'] output_csv_writer = csv.DictWriter( csv_output_file, fieldnames=output_csv_fieldnames, delimiter=settings.ASSIGNED_FILES_DELIMITER) output_csv_writer.writeheader() """Iterate for each alumni""" for alumni in alumnis: output_csv_writer.writerow(alumnis[alumni]) helper.info_message(f'Generated the cvs report file')
def run(self): """ Run the test. """ self.connection = connect_to_tester() # Start new game while True: self._start_new_game() self._display_help() # Start new round while True: self._start_new_round() print(get_chat_line_separator()) while self.n_questions_left > 0: # Read message message = input(chat_tag(DISPLAY_NAME_YOU)) # Check if the message is a command if message[:2] == "--": command_was_guess = self._execute_command(message) if command_was_guess: break print(get_chat_line_separator()) # Else, send the message to the tester else: self._send_chat_message(message) print( chat_tag(DISPLAY_NAME_OTHER) + self._receive_message()) print(get_chat_line_separator()) self.n_questions_left -= 1 if self.n_questions_left == 0: print( info_message( "No questions left. Yoy now need to make a guess.") ) self._make_guess() print(get_chat_line_separator()) if 'y' not in input("Start new round (y/N): "): break print( info_message( "Game ended. Your final score is: {:.2f} out of 100.0". format(self._compute_score()))) self.connection.request('POST', ROUTE_ENDED_GAME, "") self._receive_message() if 'y' not in input("Start new game (y/N): "): break
def check_guess(self): """ Check the guess made by the subject. Returns: str: Whether or not the result was correct. """ guess_tester_type = request.body.read().decode() print(get_chat_line_separator()) print(info_message("The human guess that you're a {}".format(guess_tester_type))) print(info_message("Waiting for a new round to start...")) if guess_tester_type == self.tester_type: return GUESS_CORRECT return GUESS_WRONG
def generate_csv_report(connections): """Generate a csv report with details of each alumni if they used cars before and after""" alumnis = {} cursor = connections['smarttraffic'].cursor(cursor_factory=psycopg2.extras.DictCursor) """Count the users that had vehicles prior Ucarpooling""" querystring = """ select profile.id, itinerary."isDriver" from ucusers_ucarpoolingprofile as profile inner join uccarpool_useritinerary as itinerary on itinerary."ucarpoolingProfile_id"=profile.id """ cursor.execute(querystring) rows = cursor.fetchall() for row in rows: alumnis[row['id']] = {'before': row['isDriver']} """Count the users that has vehicles after Ucarpooling""" querystring = """ select profile.id, carpool.driver_id from ucusers_ucarpoolingprofile as profile left join uccarpool_carpool as carpool on profile.id=carpool.driver_id """ cursor.execute(querystring) rows = cursor.fetchall() for row in rows: alumnis[row['id']]['after'] = True if row['driver_id'] else False """Write in the csv data""" with open(settings.CSV_REPORT_CARS_FILE_PATH, 'w', newline='', encoding=settings.ASSIGNED_FILES_ENCODING) as csv_output_file: """Writing the headers of the output_data file""" output_csv_fieldnames = ['before', 'after'] output_csv_writer = csv.DictWriter(csv_output_file, fieldnames=output_csv_fieldnames, delimiter=settings.ASSIGNED_FILES_DELIMITER) output_csv_writer.writeheader() """Iterate for each alumni""" for alumni in alumnis: output_csv_writer.writerow(alumnis[alumni]) helper.info_message(f'Generated the cvs report file')
def _quit(self): """ End the game. """ print(info_message("Game ended")) sys.exit(0)
def _quit(self): """ End the game. """ print(info_message("Game ended")) sys.exit(0)
def _display_score(self): """ Display the current points for the game. """ print( info_message("Current score: {:.2f}".format( self._compute_score())))
def check_guess(self): """ Check the guess made by the subject. Returns: str: Whether or not the result was correct. """ guess_tester_type = request.body.read().decode() print(get_chat_line_separator()) print( info_message( "The human guess that you're a {}".format(guess_tester_type))) print(info_message("Waiting for a new round to start...")) if guess_tester_type == self.tester_type: return GUESS_CORRECT return GUESS_WRONG
def game_ended(self): """ Inform the tester that the previous game was ended. """ print(get_chat_line_separator()) print(info_message("Current game ended. Waiting for new game to start...")) return "Ok"
def _display_questions_left(self): """ Display the number of questions left in the current round. """ print( info_message("Number of questions left in this round: " + str(self.n_questions_left)))
def start_server(): """ Start the Turing Test Server. """ tester = Tester() host = None while True: try: print(get_chat_line_separator()) host = input("IP to host on (nothing for localhost): ").strip() if not host: host = "localhost" print(info_message("Starting Turning Test Server on {}".format(host))) print(info_message("Waiting for connection from subject...")) tester.run(host=host, port=PORT, quiet=True) except socket.gaierror: print(info_message("Invalid host '{}'".format(host)))
def game_ended(self): """ Inform the tester that the previous game was ended. """ print(get_chat_line_separator()) print( info_message( "Current game ended. Waiting for new game to start...")) return "Ok"
def run(self): """ Run the test. """ self.connection = connect_to_tester() # Start new game while True: self._start_new_game() self._display_help() # Start new round while True: self._start_new_round() print(get_chat_line_separator()) while self.n_questions_left > 0: # Read message message = input(chat_tag(DISPLAY_NAME_YOU)) # Check if the message is a command if message[:2] == "--": command_was_guess = self._execute_command(message) if command_was_guess: break print(get_chat_line_separator()) # Else, send the message to the tester else: self._send_chat_message(message) print(chat_tag(DISPLAY_NAME_OTHER) + self._receive_message()) print(get_chat_line_separator()) self.n_questions_left -= 1 if self.n_questions_left == 0: print(info_message("No questions left. Yoy now need to make a guess.")) self._make_guess() print(get_chat_line_separator()) if 'y' not in input("Start new round (y/N): "): break print(info_message("Game ended. Your final score is: {:.2f} out of 100.0".format(self._compute_score()))) self.connection.request('POST', ROUTE_ENDED_GAME, "") self._receive_message() if 'y' not in input("Start new game (y/N): "): break
def _make_guess(self): """ Guess whether the tester is a bot or a human. """ guess_tester_type = input("What do you think the tester is ({}/{}): ".format(TESTER_BOT, TESTER_HUMAN)) while guess_tester_type not in [TESTER_HUMAN, TESTER_BOT]: guess_tester_type = input("{} is not a valid tester type, select either {} or {}: ".format(guess_tester_type, TESTER_BOT, TESTER_HUMAN)) print(info_message("You guessed {}. Waiting for response...".format(guess_tester_type))) self.connection.request('POST', ROUTE_CHECK_GUESS, guess_tester_type) result = self._receive_message() time.sleep(1) if result == GUESS_CORRECT: print(info_message("Your guess was correct!")) self._update_points() else: print(info_message("Your guess was wrong...")) self._display_score()
def has_connected(self): """ Get notified that the user has connected. Returns: str: Confirmation. """ host = request.body.read().decode() print(get_chat_line_separator()) print(info_message("Host {} just connected".format(host))) return "Successfully connected"
def has_connected(self): """ Get notified that the user has connected. Returns: str: Confirmation. """ host = request.body.read().decode() print(get_chat_line_separator()) print(info_message("Host {} just connected".format(host))) return "Successfully connected"
def __init__(self): """ Used to host a Turing Test. """ super(Tester, self).__init__() # Connect to the bot self.bot = connect_to_cleverbot() print(info_message("Successfully connected to cleverbot")) self.conv = self.bot.new_conversation() # Set up the routes. self.route(ROUTE_INBOX, method='POST', callback=self.receive_and_send_message) self.route(ROUTE_CONNECT_INFO, method='POST', callback=self.has_connected) self.route(ROUTE_NEW_ROUND, method='POST', callback=self.start_new_round) self.route(ROUTE_CHECK_GUESS, method='POST', callback=self.check_guess) self.route(ROUTE_ENDED_GAME, method='POST', callback=self.game_ended) # Initalized later self.tester_type = None # Estimate writing speed # If false, a random writing speed will be chosen # The writing speed is in chars/sec print(get_chat_line_separator()) if 'y' in input("Estimate writing speed (y/N): "): self.writing_speed = min(estimate_writing_speed(), 0.35) else: self.writing_speed = 0.15 + random() * 0.2 print( info_message( "Writing speed estimated to {:.3f} characters/sec".format( self.writing_speed)))
def generate_report(connections): """Generate report for amount of vehicles less with carpooling""" cursor = connections['smarttraffic'].cursor( cursor_factory=psycopg2.extras.DictCursor) querystring = """ select * from public.uccarpool_carpool_poolers as poolers inner join uccarpool_useritinerary as itinerary on poolers.ucarpoolingprofile_id=itinerary."ucarpoolingProfile_id" inner join uccarpool_itineraryroute as route on route.itinerary_id=itinerary.id """ cursor.execute(querystring) rows = cursor.fetchall() total_distance_saved = 0 for row in rows: aggCost = row['aggCost'] total_distance_saved += aggCost[-1] total_distance_saved = round(total_distance_saved / 1000, 3) helper.info_message(f'{total_distance_saved} kilometers saved') helper.info_message(f'{total_distance_saved * 0.1} liters in fuel saved') helper.info_message(f'{total_distance_saved * 0.1 * 6000} guaranies saved')
def _execute_command(self, command): """ Execute the given command. Any message starting with double dashes (--) will be considered a command. Args: command (str): The command to be parsed Returns: bool: True if the command was '--guess', else False. """ if command == '--guess': if self.n_questions_left == MAX_QUESTIONS: print(info_message("You need to ask at least one question before making a guess.")) return False else: return True if command in self.commands: self.commands[command]() else: print(info_message("Invalid command '{}'".format(command))) return False
def start_new_round(self): """ Start a new round. For the round to be started, you need to select whether you our the bot is answering. Returns: str: Confirmation message. """ # Get the tester type print(get_chat_line_separator()) print(info_message("New round started by the user.")) tester_type = input( "Will the bot or you be answering the questions ({}/{}): ".format( TESTER_BOT, TESTER_HUMAN)) while tester_type not in [TESTER_HUMAN, TESTER_BOT]: tester_type = input( "'{}' is not a valid tester type, select either {} or {}: ". format(tester_type, TESTER_BOT, TESTER_HUMAN)) if tester_type == TESTER_BOT: print( info_message( "The bot will be answering the questions. Sit back and relax!" )) if tester_type == TESTER_HUMAN: print( info_message( "You will be answering the questions. Good luck.")) print(info_message("Waiting for first message...")) self.tester_type = tester_type # Reset the bot self.conv.reset() return "New round ready"
def start_server(): """ Start the Turing Test Server. """ tester = Tester() host = None while True: try: print(get_chat_line_separator()) host = input("IP to host on (nothing for localhost): ").strip() if not host: host = "localhost" port = input("Port to host on (nothing for {}): ".format(PORT)) if not port: port = PORT print( info_message("Starting Turing Test Server on {}:{}".format( host, port))) print(info_message("Waiting for connection from subject...")) tester.run(host=host, port=port, quiet=True) except socket.gaierror: print(info_message("Invalid host '{}'".format(host)))
def generate_report(connections): """Generate report for amount of vehicles less with carpooling""" cursor = connections['smarttraffic'].cursor( cursor_factory=psycopg2.extras.DictCursor) querystring = """ select carpool_id, count(ucarpoolingprofile_id) from public.uccarpool_carpool_poolers as poolers group by carpool_id """ cursor.execute(querystring) rows = cursor.fetchall() total_poolers = 0 total_carpools = 0 for row in rows: total_poolers += row['count'] total_carpools += 1 helper.info_message(f'{total_carpools} total carpools') helper.info_message( f'{total_poolers / total_carpools} average poolers per carpool')
def estimate_writing_speed(): """ Estimate the writing speed of the human tester. Returns: float: The estimated writing speed in characters/sec """ n = 3 print(info_message("Starting estimation of writing speed")) print("Please write {} arbitrary sentences. End each sentence with enter.".format(n)) speeds = [] for i in range(n): t_start = time() text = input("Sentence {}: ".format(i+1)) speeds.append((time()-t_start)/len(text)) return sum(speeds)/n
def estimate_writing_speed(): """ Estimate the writing speed of the human tester. Returns: float: The estimated writing speed in characters/sec """ n = 3 print(info_message("Starting estimation of writing speed")) print("Please write {} arbitrary sentences. End each sentence with enter.". format(n)) speeds = [] for i in range(n): t_start = time() text = input("Sentence {}: ".format(i + 1)) speeds.append((time() - t_start) / len(text)) return sum(speeds) / n
def generate_report(connections): """Generate report for amount of vehicles less with carpooling""" cursor = connections['smarttraffic'].cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute('select count(*) from public.uccarpool_itineraryroute') row = cursor.fetchone() amount_vehicles_before = row['count'] cursor.execute('select count(*) FROM public.uccarpool_carpool as carpool') row = cursor.fetchone() amount_vehicles_after = row['count'] helper.info_message(f'There were {amount_vehicles_before} vehicles before') helper.info_message(f'There are {amount_vehicles_after} vehicles after') helper.info_message(f'There was a reduction of {round((1-float(amount_vehicles_after/amount_vehicles_before)) * 100, 2)}%')
def upload_users_itinerary(): """ Uploads all the generated users profile to api/ucarpooling/users/ """ alumni_auth = Table(settings.DATABASE_TABLE_AUTH) try: con = sqlite3.connect(settings.DATABASE) con.row_factory = sqlite3.Row cursorObj = con.cursor() """Building the query for retrieving all the users and their assigned profiles""" querystring = Query \ .from_(Table(settings.DATABASE_TABLE_ALUMNI)) \ .join(Table(settings.DATABASE_TABLE_ITINERARY)) \ .on_field('uuid') \ .join(Table(settings.DATABASE_TABLE_CARS)) \ .on_field('uuid') \ .select('*')\ .limit(settings.LIMIT_USERS) # print(querystring.get_sql()) """Executing the query""" rows = cursorObj.execute(querystring.get_sql()).fetchall() with Chronometer() as time_uploading: """Iteraring for each row in the database for alumni""" for alumni in rows: """Building the body in a json-like format for the boy of the POST request""" origen = f'{alumni[settings.FIELDNAME_LATITUDE.lower()]},{alumni[settings.FIELDNAME_LONGITUDE.lower()]}' toa = f'{date.today()}T{alumni[settings.FIELDNAME_TOA.lower()]}Z' body = { "isDriver": True if alumni[settings.FIELDNAME_TRANSPORT.lower()] == 'Car' else False, "origin": origen, "destination": "-25.324491,-57.635437", # Uca latitude and longitude "timeOfArrival": toa } """Getting the token of the alumni for the POST header""" querystring = Query\ .from_(alumni_auth)\ .select(alumni_auth.token)\ .where(alumni_auth.uuid == alumni[settings.FIELDNAME_UUID.lower()]) cursorObj.execute(querystring.get_sql()) alumni_token = (cursorObj.fetchone())['token'] """POST request for the itinerary""" response = requests.post( url=settings.USER_ITINERARY_URL, json=body, headers={ "Authorization": f'Token {alumni_token}' # Token og the Ucarpooling app } ) if response.status_code == 201: helper.success_message(f'Uploaded successfully itinerary for alumni {alumni[settings.FIELDNAME_UUID.lower()]}') body_response = response.json() store_useritinerary_id(con, cursorObj, body_response['id'], alumni[settings.FIELDNAME_UUID.lower()]) else: helper.error_message(f'Error uploading itinerary for alumni {alumni[settings.FIELDNAME_UUID.lower()]} ' f'---- status code: {response.status_code}: {response.reason}') """Uploading ended""" helper.info_message('=================UPLOADING ENDED=====================') helper.detail_message('Uploading runtime: {:.3f} seconds'.format(float(time_uploading))) except Error: print(Error) finally: """Closing the database connection""" con.close()
def _display_questions_left(self): """ Display the number of questions left in the current round. """ print(info_message("Number of questions left in this round: " + str(self.n_questions_left)))
def _display_score(self): """ Display the current points for the game. """ print(info_message("Current score: {:.2f}".format(self._compute_score())))
def upload_users(): """ Uploads all the generated users profile to api/ucarpooling/users/ """ try: con = sqlite3.connect(settings.DATABASE) con.row_factory = sqlite3.Row cursorObj = con.cursor() """Building the query for retrieving all the users and their assigned profiles""" querystring = Query \ .from_(Table(settings.DATABASE_TABLE_ALUMNI)) \ .join(Table(settings.DATABASE_TABLE_ELOQUENCE)) \ .on_field('uuid') \ .join(Table(settings.DATABASE_TABLE_SMOKER)) \ .on_field('uuid') \ .join(Table(settings.DATABASE_TABLE_MUSIC)) \ .on_field('uuid') \ .select('*')\ .limit(settings.LIMIT_USERS) """Executing the query""" rows = cursorObj.execute(querystring.get_sql()).fetchall() """Iteraring for each row in the database for alumni""" with Chronometer() as time_uploading: for alumni in rows: """Building the body in a json-like format for the boy of the POST request""" body = { "email": f"{alumni[settings.FIELDNAME_UUID.lower()]}@mail.com", "password": "******", "first_name": str(alumni[settings.FIELDNAME_UUID.lower()]), "last_name": str(alumni[settings.FIELDNAME_UUID.lower()]), "ucarpoolingprofile": { "sex": alumni[settings.FIELDNAME_SEX.lower()], "smoker": True if alumni[settings.FIELDNAME_SMOKER.lower()] == 'Si' else False, "musicTaste": alumni[settings.FIELDNAME_MUSIC_TASTE.lower()].split(", "), "eloquenceLevel": get_eloquence_level(alumni[settings.FIELDNAME_ELOQUENCE.lower()]) } } "POST the alumni data to the API" response = requests.post( url=settings.USER_URL, json=body, headers={ "Authorization": f'Token {settings.UCARPOOLING_APP_TOKEN}' # Token of the Ucarpooling app } ) if response.status_code == 201: helper.success_message(f'Uploaded successfully alumni {alumni[settings.FIELDNAME_UUID.lower()]}') get_token(con, cursorObj, alumni) else: helper.error_message(f'Error uploading alumni {alumni[settings.FIELDNAME_UUID.lower()]} ' f'---- status code: {response.status_code}: {response.reason}') """Uploading ended""" helper.info_message('=================UPLOADING ENDED=====================') helper.detail_message('Uploading runtime: {:.3f} seconds'.format(float(time_uploading))) except Error: print(Error) finally: """Closing the database connection""" con.close()
def simulator(): """ Simulates the use of the Ucarpooling app """ """Variables for statistics in the simulation""" max_time = 0 total_time = 0 total_errors = 0 """Get the set of people that will request a carpooling partner""" rows = get_requesters() helper.info_message( f'==============STARTING SIMULATION=====================') """Iteraring for each row in the database for alumni""" with Chronometer() as time_simulation: total_row_count = len(rows) row_counter = 0 helper.info_message(f'{total_row_count} records to check matching') for alumni in rows: print('=========================================') row_counter += 1 helper.info_message(f'Progress: {row_counter}/{total_row_count}') alumni_token = alumni['token'] alumni_id = alumni[settings.FIELDNAME_UUID.lower()] alumni_ucarpooling_id = alumni['ucarpoolingprofile_id'] alumni_useritinerary_id = alumni['useritinerary_id'] "GET the matches for the alumni" with Chronometer() as time_matching: response = requests.get( url=get_matcher_url(alumni_useritinerary_id), headers={"Authorization": f'Token {alumni_token}'}) """Time statistics for the matcher of the back-end""" match_time = float(time_matching) helper.detail_message('Match for {} took {:.3f} seconds'.format( alumni_id, match_time)) total_time += match_time max_time = match_time if max_time < match_time else max_time if response.status_code == 200: body_response = response.json() partners = get_carpooling_partner(body_response) if partners: create_carpool(alumni_ucarpooling_id, partners, alumni_useritinerary_id) else: helper.warning_message( f'{alumni_id} had matches but did not travel with poolers' ) else: """The server did not respond a good result""" total_errors += 1 if response.status_code == 420: helper.warning_message( f'{alumni_id} is already in a carpool') elif response.status_code == 204: helper.no_matches_message( f'{alumni_id} did not have any matches') create_carpool(alumni_ucarpooling_id, [], alumni_useritinerary_id) else: helper.error_message( f'Error getting matches for alumni {alumni_id} ' f'---- status code: {response.status_code}: {response.reason}' ) """The simulation ended""" helper.info_message( '=================SIMULATION ENDED=====================') helper.detail_message(f'There was a total of {total_errors} errors') helper.detail_message(f'Max total match time: {max_time} seconds') helper.detail_message('Simulation runtime: {:.3f} seconds'.format( float(time_simulation)))