def create_table(): result = r.get_registry()['MY_SQL'].query( ( "select * from information_schema.tables where " "TABLE_SCHEMA='scoring_system' and table_name='robots';" ) ) if result != 0: return query = ( """CREATE TABLE IF NOT EXISTS robots( division VARCHAR(16), id VARCHAR(10) UNIQUE, volume INT, school VARCHAR(100), name VARCHAR(100), is_unique BOOLEAN, used_versa_valve BOOLEAN, level INT, is_disqualified BOOLEAN, passed_inspection BOOLEAN, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;""" ) r.get_registry()['MY_SQL'].query(query) r.get_registry()['MY_SQL'].query( ('ALTER TABLE robots ADD INDEX (name), ADD ' 'UNIQUE INDEX (name)') )
def create_table(): result = r.get_registry()['MY_SQL'].query( ( "select * from information_schema.tables where " "TABLE_SCHEMA='scoring_system' and table_name='runs';" ) ) if result != 0: return query = ( """CREATE TABLE IF NOT EXISTS runs( id INT AUTO_INCREMENT, level INT, failed_trial BOOLEAN, actual_time FLOAT(10,2), non_air BOOLEAN, furniture BOOLEAN, arbitrary_start BOOLEAN, return_trip BOOLEAN, candle_location_mode BOOLEAN, stopped_within_circle BOOLEAN, signaled_detection BOOLEAN, num_rooms_searched INT, kicked_dog BOOLEAN, touched_candle INT, cont_wall_contact INT, ramp_hallway BOOLEAN, alt_target BOOLEAN, all_candles BOOLEAN, used_versa_valve BOOLEAN, score FLOAT(10,2), robot_id VARCHAR(10), PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;""") r.get_registry()['MY_SQL'].query(query)
def create_table(): result = r.get_registry()['MY_SQL'].query( ("select * from information_schema.tables where " "TABLE_SCHEMA='trin_report' and table_name='emergency';")) if result != 0: return query = ("""CREATE TABLE IF NOT EXISTS emergency( id INT AUTO_INCREMENT, created DATETIME, name VARCHAR(350), phone VARCHAR(350), id_num VARCHAR(350), email VARCHAR(350), dorm VARCHAR(350), longitude VARCHAR(350), latitude VARCHAR(350), location_last_updated DATETIME, handled_status BOOLEAN, handled_time DATETIME, explanation VARCHAR(350), callme BOOLEAN, done BOOLEAN, archived BOOLEAN, archived_time DATETIME, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;""") r.get_registry()['MY_SQL'].query(query)
def advance_level(robot_id): # validate robot id robot = r.get_registry()['ROBOTS'].get_robot(robot_id) if not robot: return render_template("not_found.html") # get existing runs of robot runs = r.get_registry()['RUNS'].get_runs(robot_id) # check if robot is eligible to be advanced to next level eligible = LevelProgressHandler.get_eligibility_for_next_run( runs, robot['level'] ) # if eligible and has not be disqualified, advance robot to next level if eligible.get('can_level_up') and not eligible['disqualified']: # advance to next level by updating 'level' column in db r.get_registry()['ROBOTS'].advance_level( robot_id, robot['level'] ) # redirect to add run page return redirect( url_for('main.robot_add_run', robot_id=robot_id) ) return "Robot not eligible to advance to next level.\n"
def robot_detail(robot_id, inputs=None): robot = r.get_registry()['ROBOTS'].get_robot(robot_id) if not robot: return render_template("not_found.html") runs = r.get_registry()['RUNS'].get_runs(robot_id) run_levels = [run['id'] for run in runs] # check if disqualifited and eligibility to advnace to next level eligibility = LevelProgressHandler.get_eligibility_for_next_run( runs, robot['level'] ) # get current best scores best_scores, attempted_levels, total_score, num_successful = ( ScoreCalculator.get_best_scores(runs) ) return render_template( "robot.html", attempted_levels=attempted_levels, total_score=total_score, robot_id=robot_id, robot=robot, disqualified=eligibility['disqualified'], eligible=eligibility['can_level_up'], best_scores=best_scores, robot_runs=runs, applied_factors=[applied_factors(id, robot_id) for id in run_levels], inputs=inputs )
def create_table(): result = r.get_registry()['MY_SQL'].query( ("select * from information_schema.tables where " "TABLE_SCHEMA='scoring_system' and table_name='runs';")) if result != 0: return query = ("""CREATE TABLE IF NOT EXISTS runs( id INT AUTO_INCREMENT, level INT, failed_trial BOOLEAN, actual_time FLOAT(10,2), non_air BOOLEAN, furniture BOOLEAN, arbitrary_start BOOLEAN, return_trip BOOLEAN, candle_location_mode BOOLEAN, stopped_within_circle BOOLEAN, signaled_detection BOOLEAN, num_rooms_searched INT, kicked_dog BOOLEAN, touched_candle INT, cont_wall_contact INT, ramp_hallway BOOLEAN, alt_target BOOLEAN, all_candles BOOLEAN, used_versa_valve BOOLEAN, score FLOAT(10,2), robot_id VARCHAR(10), PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;""") r.get_registry()['MY_SQL'].query(query)
def create_table(): result = r.get_registry()['MY_SQL'].query( ("select * from information_schema.tables where " "TABLE_SCHEMA='scoring_system' and table_name='robots';")) if result != 0: return query = ("""CREATE TABLE IF NOT EXISTS robots( division VARCHAR(16), id VARCHAR(10) UNIQUE, volume INT, school VARCHAR(100), name VARCHAR(100), is_unique BOOLEAN, used_versa_valve BOOLEAN, level INT, is_disqualified BOOLEAN, passed_inspection BOOLEAN, from_na BOOLEAN, from_ct BOOLEAN, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;""") r.get_registry()['MY_SQL'].query(query) r.get_registry()['MY_SQL'].query( ('ALTER TABLE robots ADD INDEX (name), ADD ' 'UNIQUE INDEX (name)'))
def robot_detail(robot_id, inputs=None): robot = r.get_registry()['ROBOTS'].get_robot(robot_id) if not robot: return render_template("not_found.html") runs = r.get_registry()['RUNS'].get_runs(robot_id) run_levels = [run['id'] for run in runs] # check if disqualifited and eligibility to advnace to next level eligibility = LevelProgressHandler.get_eligibility_for_next_run( runs, robot['level']) # get current best scores best_scores, attempted_levels, total_score, num_successful = ( ScoreCalculator.get_best_scores(runs)) return render_template( "robot.html", attempted_levels=attempted_levels, total_score=total_score, robot_id=robot_id, robot=robot, disqualified=eligibility['disqualified'], eligible=eligibility['can_level_up'], best_scores=best_scores, robot_runs=runs, applied_factors=[applied_factors(id, robot_id) for id in run_levels], inputs=inputs)
def set_day(run_id, day): query = """UPDATE runs SET day = %(day)s where id = %(id)s;""" data = {'day': day, 'id': run_id} r.get_registry()['MY_SQL'].insert(query, data)
def export_to_csv(): divisions = ['junior', 'walking', 'high_school', 'senior'] all_robots = {} for division in divisions: all_robots[division] = r.get_registry()['ROBOTS'].get_all_robots_division(division) si = StringIO.StringIO() cw = csv.writer(si) cw.writerow(['Rank', 'Division', 'Name', '# of Successful Runs', 'Current Level', 'LS1', 'LS2', 'LS3', 'TFS', 'From CT', 'From NA', 'Is unique']) for div in all_robots: for robot in all_robots[div]: runs = r.get_registry()['RUNS'].get_runs(robot['id']) # get current best scores best_scores, attempted_levels, total_score, num_successful = ( ScoreCalculator.get_best_scores(runs) ) robot.update(best_scores) robot['TFS'] = total_score robot['num_successful'] = num_successful # calculate lowes scores for each level and TFS, returns tuple robot['completed'] = attempted_levels # sort based on name then total score sorted_robots = sorted( list(all_robots[div]), key=lambda k: k['name'] ) sorted_robots = sorted( list(sorted_robots), key=lambda k: k['TFS'] ) for index, sorted_r in enumerate(sorted_robots, start=1): cw.writerow([ index, sorted_r['division'], sorted_r['name'], sorted_r['num_successful'], sorted_r['level'], sorted_r['LS1'], sorted_r['LS2'], sorted_r['LS3'], sorted_r['TFS'], sorted_r['from_ct'], sorted_r['from_na'], sorted_r['is_unique'] ]) cw.writerow('\n') output = make_response(si.getvalue()) si.close() output.headers["Content-Disposition"] = "attachment; filename=scoreboard.csv" output.headers["Content-type"] = "text/csv" return output
def run(): load_registry() r.get_registry()['MY_SQL'].query( 'DROP TABLE runs;' ) r.get_registry()['MY_SQL'].query( 'DROP TABLE robots;' )
def applied_factors(run_id, robot_id): query = ("""SELECT * FROM runs where id = %(run_id)s;""") data = { 'run_id': run_id } run_data = r.get_registry()['MY_SQL'].get(query, data) query = ("""SELECT division FROM robots where id = %(robot_id)s;""") data = { 'robot_id': robot_id } robot_div = r.get_registry()['MY_SQL'].get(query, data).get('division') run_level = run_data['level'] applied_oms = "" applied_rf = "" applied_pp = "" if run_data.get('failed_trial') == 1: if run_level == 1 and robot_div in ['junior', 'walking']: if (run_data.get('num_rooms_searched', 0) > 0): applied_oms += 'Task.search:-30x%d rooms\n' % (run_data.get('num_rooms_searched', 0)) applied_oms += 'Task.detect:-30\n' if run_data.get('signaled_detection', 0) == 1 else '' applied_oms += 'Task.position:-30\n' if run_data.get('stopped_within_circle', 0) == 1 else '' else: if run_data.get('touched_candle', 0) > 0: applied_pp += 'PP.candle=%d\n' % (run_data.get('touched_candle', 0) * 50) if run_data.get('cont_wall_contact', 0) > 0: applied_pp += 'PP.slide=%dcm/2\n' % (run_data.get('cont_wall_contact', 0)) applied_pp += 'PP.dog=50\n' if run_data.get('kicked_dog', 0) == 1 else '' if run_level == 1: applied_oms += 'OM.candle=0.75\n' if run_data.get('candle_location_mode', 0) == 1 else '' if run_level in [1,2]: applied_oms += 'OM.start=0.8\n' if run_data.get('arbitrary_start', 0) == 1 else '' applied_oms += 'OM.return=0.8\n' if run_data.get('return_trip', 0) == 1 else '' applied_oms += 'OM.extinguisher=0.75\n' if run_data.get('non_air', 0) == 1 else '' applied_oms += 'OM.furniture=0.75\n' if run_data.get('furniture', 0) == 1 else '' if run_data.get('num_rooms_searched') == 1: applied_rf += 'Room Factor:1\n' elif run_data.get('num_rooms_searched') == 2: applied_rf += 'Room Factor:0.85\n' elif run_data.get('num_rooms_searched') == 3: applied_rf += 'Room Factor:0.5\n' elif run_data.get('num_rooms_searched') == 4: applied_rf += 'Room Factor:0.35\n' elif run_level == 3: applied_oms += 'OM.Alt_Target=0.6\n' if run_data.get('alt_target', 0) == 1 else '' applied_oms += 'OM.Ramp_Hallway=0.9\n' if run_data.get('ramp_hallway', 0) == 1 else '' applied_oms += 'OM.All_Candles=0.6\n' if run_data.get('all_candles', 0) == 1 else '' return {'applied_oms': applied_oms, 'applied_rf': applied_rf, 'applied_pp': applied_pp}
def get_applied_factors(run_id, robot_id): query = ("""SELECT * FROM runs where id = %(run_id)s;""") data = { 'run_id': run_id } run_data = r.get_registry()['MY_SQL'].get(query, data) query = ("""SELECT division FROM robots where id = %(robot_id)s;""") data = { 'robot_id': robot_id } robot_div = r.get_registry()['MY_SQL'].get(query, data).get('division') run_level = run_data['level'] applied_oms = "" applied_rf = "" applied_pp = "" if run_data.get('failed_trial') == 1: if run_level == 1 and robot_div in ['junior', 'walking']: if (run_data.get('num_rooms_searched', 0) > 0): applied_oms += 'Task.search:-30x%d rooms\n' % (run_data.get('num_rooms_searched', 0)) applied_oms += 'Task.detect:-30\n' if run_data.get('signaled_detection', 0) == 1 else '' applied_oms += 'Task.position:-30\n' if run_data.get('stopped_within_circle', 0) == 1 else '' else: if run_data.get('touched_candle', 0) > 0: applied_pp += 'PP.candle=%d\n' % (run_data.get('touched_candle', 0) * 50) if run_data.get('cont_wall_contact', 0) > 0: applied_pp += 'PP.slide=%dcm/2\n' % (run_data.get('cont_wall_contact', 0)) applied_pp += 'PP.dog=50\n' if run_data.get('kicked_dog', 0) == 1 else '' if run_level == 1: applied_oms += 'OM.candle=0.75\n' if run_data.get('candle_location_mode', 0) == 1 else '' if run_level in [1,2]: applied_oms += 'OM.start=0.8\n' if run_data.get('arbitrary_start', 0) == 1 else '' applied_oms += 'OM.return=0.8\n' if run_data.get('return_trip', 0) == 1 else '' applied_oms += 'OM.extinguisher=0.75\n' if run_data.get('non_air', 0) == 1 else '' applied_oms += 'OM.furniture=0.75\n' if run_data.get('furniture', 0) == 1 else '' if run_data.get('num_rooms_searched') == 1: applied_rf += 'Room Factor:1\n' elif run_data.get('num_rooms_searched') == 2: applied_rf += 'Room Factor:0.85\n' elif run_data.get('num_rooms_searched') == 3: applied_rf += 'Room Factor:0.5\n' elif run_data.get('num_rooms_searched') == 4: applied_rf += 'Room Factor:0.35\n' elif run_level == 3: applied_oms += 'OM.Alt_Target=0.6\n' if run_data.get('alt_target', 0) == 1 else '' applied_oms += 'OM.Ramp_Hallway=0.9\n' if run_data.get('ramp_hallway', 0) == 1 else '' applied_oms += 'OM.All_Candles=0.6\n' if run_data.get('all_candles', 0) == 1 else '' return {'applied_oms': applied_oms, 'applied_rf': applied_rf, 'applied_pp': applied_pp}
def set_day(run_id, day): query = """UPDATE runs SET day = %(day)s where id = %(id)s;""" data = { 'day': day, 'id': run_id } r.get_registry()['MY_SQL'].insert(query, data)
def get(cls, id): redis_key = cls.get_redis_key(id) cached_data = r.get_registry()['REDIS'].hgetall(redis_key) if cached_data: return Question(cached_data) query = "SELECT * FROM questions WHERE id=%s" result = r.get_registry()['MY_SQL'].get(query, [id]) if result: cls.cache_result(result) return Question(result) return None
def create_table(): result = r.get_registry()['MY_SQL'].query( ("select * from information_schema.tables where " "TABLE_SCHEMA='trin_report' and table_name='user';")) if result != 0: return query = ("""CREATE TABLE IF NOT EXISTS user( user_id VARCHAR(32), auth_token VARCHAR(64), public_key_pem VARCHAR(450), PRIMARY KEY (user_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;""") r.get_registry()['MY_SQL'].query(query)
def get_report_record(report_id): # get report record report = r.get_registry()['REPORT'].get_report(report_id) # validate report id if not report: return jsonify({'error': "Invalid report ID"}), 400 # get images meta data images = r.get_registry()['IMAGE'].get_images(report_id) # create response js = {} js['report'] = report return jsonify(js), 200
def register_user(): # get user data from request data = request.form user_id = data.get('user_id') auth_token = data.get('auth_token') # add record to database r.get_registry()['USER'].register_user( user_id, auth_token ) # create response js = {} return jsonify(js), 200
def robot_add_run(robot_id): robot = r.get_registry()['ROBOTS'].get_robot(robot_id) if not robot: return render_template("not_found.html") all_runs = r.get_registry()['RUNS'].get_runs(robot_id) if request.method == 'GET': # get all previous runs return render_template( "run.html", robot=robot, division=get_division_label(robot['division']), input=request.args, all_runs=all_runs ) # For post request # Database query for showing past runs if the POST fails all_runs = r.get_registry()['RUNS'].get_runs(robot_id) # if invalidate input data params_d = bind_params(request.form, robot_id, robot['level']) err = validate_params(params_d, robot['level'], robot['division'], robot['name']) if err: err['ERR'] = True params_and_errors = {} params_and_errors.update(params_d) # leave data already entered unchanged params_and_errors.update(err) # include errors return render_template( "run.html", robot=robot, division=get_division_label(robot['division']), input=params_and_errors, all_runs=all_runs ) # calculate score score = get_score(robot, params_d) # convert dict values to tuple to prepare to insert to DB params_t = convert_to_tuple(params_d, robot_id, score) # insert into databse r.get_registry()['RUNS'].record_run(*params_t) return redirect(url_for('main.robot_detail', robot_id=robot_id))
def run(): # grant all privileges on *.* to trivia_challenge@localhost identified by '9a7123w4982ew3490x23pl34bz' with grant option; # NOQA load_registry() r.get_registry()['MY_SQL'].query('CREATE DATABASE challenge;') r.get_registry()['MY_SQL'].query("""CREATE TABLE questions( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), prompt VARCHAR(255), passing_score INT, correct_names LONGTEXT, finalized INT DEFAULT 1, active INT DEFAULT 1, total INT DEFAULT 0 )""")
def run(): load_registry() division_map = { 'high school': 'high_school', 'junior': 'junior', 'senior': 'senior', 'walking': 'walking' } unique_map = {'unique': True, 'custom kit': False, 'i am not sure': False} versa_valve_map = {'yes': True, 'no': False} fields_index = { 'division': 0, 'name': 1, 'unique': 3, 'versa_valve': 6, 'school': 2 } with open('robot_list_2017.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile) i = 0 id_counter = {'high_school': 1, 'senior': 1, 'walking': 1, 'junior': 1} for row in spamreader: # skip first three lines if i <= 2: i += 1 continue i += 1 d = {} if row[fields_index['unique']].strip().lower() == ( 'i am not sure, please contact me to discuss'): continue for field, index in fields_index.iteritems(): if field == 'division': d[field] = division_map[row[index].strip().lower()] elif field == 'unique': d[field] = unique_map[row[index].strip().lower()] else: d[field] = row[index] d['id'] = get_id(id_counter, d) r.get_registry()['ROBOTS'].record_robot(division=d['division'], id=d['id'], volume=0, school=d['school'], name=d['name'], is_unique=d['unique'], used_versa_valve=False, level=1, is_disqualified=False, passed_inspection=False)
def advance_level(robot_id): robot = r.get_registry()['ROBOTS'].get_robot(robot_id) if not robot: return render_template("not_found.html") runs = r.get_registry()['RUNS'].get_runs(robot_id) eligible = LevelProgressHandler.get_eligibility_for_next_run(runs, robot['level']) if eligible.get('can_level_up') and not eligible['disqualified']: r.get_registry()['ROBOTS'].advance_level(robot_id, robot['level']) return redirect(url_for('main.robot_add_run', robot_id=robot_id)) return "Robot not eligible to advance to next level.\n"
def emergency_request(): # get timestamp timestamp = datetime.datetime.now() # get data from form data = request.form name = data.get('username') phone = data.get('userphone') id_num = data.get('userid') email = data.get('useremail') dorm = data.get('userdorm') lat = data.get('latitude') lng = data.get('longitude') exp = data.get('explanation') # default boolean values handled_status = False archived = False done = False # add record to database e_id = r.get_registry()['EMERGENCY'].record_emergency( timestamp, name, phone, id_num, email, dorm, lat, lng, handled_status, exp, archived, done) # create response js = {} js['emergency_id'] = e_id return jsonify(js), 200
def advance_level(robot_id): robot = r.get_registry()['ROBOTS'].get_robot(robot_id) if not robot: return render_template("not_found.html") runs = r.get_registry()['RUNS'].get_runs(robot_id) eligible = LevelProgressHandler.get_eligibility_for_next_run( runs, robot['level']) if eligible.get('can_level_up') and not eligible['disqualified']: r.get_registry()['ROBOTS'].advance_level(robot_id, robot['level']) return redirect(url_for('main.robot_add_run', robot_id=robot_id)) return "Robot not eligible to advance to next level.\n"
def advance_level(robot_id, current_level): query = """UPDATE robots SET level = %(level)s where id = %(robot_id)s;""" data = { 'level': current_level + 1, 'robot_id': robot_id } return r.get_registry()['MY_SQL'].insert(query, data)
def sign_in(): # if already logged in if Signin.is_loggedin(): return redirect(url_for('main.landing')) # get input from form email = request.json.get('email').lower() password = request.json.get('password') # validate input error = Signin.validate_signin(email, password) # error response if error: return jsonify({ 'email': email, 'password': password, 'email_error': error.get('email_error'), 'password_error': error.get('password_error') }), 400 # login user, logout current user if any Signin.logout() user = r.get_registry()['ADMIN'].get_admin_by_email(email) Signin.login(email) # create response js = { 'redirect': '/home', 'logged_in': True } return jsonify(js), 200
def run(): # grant all privileges on *.* to trivia_challenge@localhost identified by '9a7123w4982ew3490x23pl34bz' with grant option; # NOQA load_registry() r.get_registry()['MY_SQL'].query('CREATE DATABASE challenge;') r.get_registry()['MY_SQL'].query( """CREATE TABLE questions( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), prompt VARCHAR(255), passing_score INT, correct_names LONGTEXT, finalized INT DEFAULT 1, active INT DEFAULT 1, total INT DEFAULT 0 )""" )
def get_report_records(): # get all non-archived records records = r.get_registry()['REPORT'].get_non_archived_reports() # create response js = {} js['reports'] = list(records) return jsonify(js), 200
def get_runs_robot_level(robot_id, level): query = """SELECT * FROM runs where (robot_id = %(robot_id)s) AND (level = level);""" data = { 'robot_id': robot_id, 'level': level } return r.get_registry()['MY_SQL'].get_all(query, data)
def scoreboard_lisp(level): if not level.isdigit(): return render_template("not_found.html") if int(level) not in [1, 2, 3]: return render_template("not_found.html") robots = r.get_registry()['ROBOTS'].get_all_robots() if not robots: return render_template("not_found.html") # add additional parameters to be displayed on scoreboard robots = ScoreBoard.add_scoreboard_params(robots) # filter robots filtered_robots = ScoreBoard.filter_robots_level(robots, int(level)) # key used for sorting score_name = "LS" + level # sort based on name then this level's lowest score sorted_robots = sorted(list(filtered_robots), key=lambda k: k['name']) sorted_robots = sorted(list(sorted_robots), key=lambda k: k[score_name]) return render_template( "scoreboard_lisp.html", robots=sorted_robots, level=level, score_name=score_name )
def scoreboard_lisp(level): if not level.isdigit(): return render_template("not_found.html") if int(level) not in [1, 2, 3]: return render_template("not_found.html") robots = r.get_registry()['ROBOTS'].get_all_robots() if not robots: return render_template("not_found.html") # add additional parameters to be displayed on scoreboard robots = ScoreBoard.add_scoreboard_params(robots) # filter robots filtered_robots = ScoreBoard.filter_robots_level(robots, int(level)) # key used for sorting score_name = "LS" + level # sort based on name then this level's lowest score sorted_robots = sorted(list(filtered_robots), key=lambda k: k['name']) sorted_robots = sorted(list(sorted_robots), key=lambda k: k[score_name]) return render_template("scoreboard_lisp.html", robots=sorted_robots, level=level, score_name=score_name)
def get_question(question_id): if not question_id: return None question = r.get_registry()['QUESTIONS'].get(question_id) if not question: return None return question.flatten()
def scoreboard_brd(division): robots = r.get_registry()['ROBOTS'].get_all_robots_division( division ) if not robots: return render_template("not_found.html") # add additional parameters to be displayed on scoreboard robots = ScoreBoard.add_scoreboard_params(robots) # sort based on name then total score sorted_robots = sorted( list(robots), key=lambda k: k['name'] ) sorted_robots = sorted( list(sorted_robots), key=lambda k: k['TFS'] ) return render_template( "scoreboard_brd_gpmp.html", robots=sorted_robots, scoreboard_name=get_division_label(division) )
def mark_as_done(): # get data from form data = request.form emergency_id = data.get('emergency_id') # get emergency record emergency = r.get_registry()['EMERGENCY'].get_emergency(emergency_id) # validate emergency id if not emergency: print "Invalid emergency ID: " + emergency_id return jsonify({'error': "Invalid emergency ID"}), 400 # update 'done' column in db done = True r.get_registry()['EMERGENCY'].mark_as_done(emergency_id, done) # create response js = {} return jsonify(js), 200
def home(): robots = r.get_registry()['ROBOTS'].get_all_robots() for rb in robots: rb['endpoint'] = url_for('main.robot_detail', robot_id=rb['id']) return render_template( "home.html", robots=robots )
def publish_user_public_key(): # get data from request data = request.form auth_token = data.get('auth_token') public_key = data.get('public_key') # add public key to database r.get_registry()['USER'].publish_public_key( auth_token, public_key ) # get admin, we assume there is only one admin admin = r.get_registry()['ADMIN'].get_admins()[0] # get public key of admin public_key_pem = admin.get('public_key_pem') # create response js = {'public_key': public_key_pem} return jsonify(js), 200
def record_robot(division, id, volume, school, name, is_unique, used_versa_valve, level, is_disqualified, passed_inspection): query = """INSERT INTO robots( division, id, volume, school, name, is_unique, used_versa_valve, level, is_disqualified, passed_inspection ) VALUES ( %(division)s, %(id)s, %(volume)s, %(school)s, %(name)s, %(is_unique)s, %(used_versa_valve)s, %(level)s, %(is_disqualified)s, %(passed_inspection)s );""" data = { 'division': division, 'id': id, 'volume': volume, 'school': school, 'name': name, 'is_unique': is_unique, 'used_versa_valve': used_versa_valve, 'level': level, 'is_disqualified': is_disqualified, 'passed_inspection': passed_inspection } r.get_registry()['MY_SQL'].insert(query, data)
def emergency_explanation(): # get data from form timestamp = datetime.datetime.now() data = request.form emergency_id = data.get('emergency_id') explanation = data.get('explanation') # get emergency record emergency = r.get_registry()['EMERGENCY'].get_emergency(emergency_id) # validate emergency id if not emergency: print "Invalid emergency ID: " + emergency_id return jsonify({'error': "Invalid emergency ID"}), 400 # save explanation in db r.get_registry()['EMERGENCY'].update_explanation(emergency_id, explanation) # create response js = {} return jsonify(js), 200
def emergency_records(): # get all non-archived records records = r.get_registry()['EMERGENCY'].get_non_archived_records() # create response js = {} js['emergencies'] = list(records) return jsonify(js), 200
def create_table(): result = r.get_registry()['MY_SQL'].query( ("select * from information_schema.tables where " "TABLE_SCHEMA='trin_report' and " "table_name='message_admin';")) if result != 0: return query = ("""CREATE TABLE IF NOT EXISTS message_admin( id INT AUTO_INCREMENT, report_id VARCHAR(450), content VARCHAR(350), from_admin BOOLEAN, timestamp DATETIME, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;""") r.get_registry()['MY_SQL'].query(query)
def export_to_csv(): divisions = ['junior', 'walking', 'high_school', 'senior'] all_robots = {} for division in divisions: all_robots[division] = r.get_registry()['ROBOTS'].get_all_robots_division(division); si = StringIO.StringIO() cw = csv.writer(si) cw.writerow(['Rank', 'Division', 'Name', '# of Successful Runs', 'Current Level', 'LS1', 'LS2', 'LS3', 'TFS', 'Volume', 'From NA', 'From CT', 'Unique']) for div in all_robots: for robot in all_robots[div]: runs = r.get_registry()['RUNS'].get_runs(robot['id']) # get current best scores best_scores, attempted_levels, total_score, num_successful = ( ScoreCalculator.get_best_scores(runs) ) robot.update(best_scores) robot['TFS'] = total_score robot['num_successful'] = num_successful # calculate lowes scores for each level and TFS, returns tuple robot['completed'] = attempted_levels # sort based on name then total score sorted_robots = sorted(list(all_robots[div]), key=lambda k: k['name']) sorted_robots = sorted(list(sorted_robots), key=lambda k: k['TFS']) for index, sorted_r in enumerate(sorted_robots, start=1): cw.writerow([index, sorted_r['division'], sorted_r['name'], sorted_r['num_successful'], sorted_r['level'], sorted_r['LS1'], sorted_r['LS2'], sorted_r['LS3'], sorted_r['TFS'], sorted_r['volume'], sorted_r['from_na'], sorted_r['from_ct'], sorted_r['is_unique']]) cw.writerow('\n') output = make_response(si.getvalue()) si.close() output.headers["Content-Disposition"] = "attachment; filename=scoreboard.csv" output.headers["Content-type"] = "text/csv" return output
def approve_and_store_volume(robot_id, volume): query = """UPDATE robots SET volume = %(volume)s, passed_inspection = %(passed_inspection)s where id = %(robot_id)s;""" data = { 'volume': volume, 'robot_id': robot_id, 'passed_inspection': True } return r.get_registry()['MY_SQL'].insert(query, data)
def load_registry(): """ Initialize and load the global registry """ r = registry.get_registry() if r.is_locked(): return init_mysql(r) init_redis(r) init_clients(r) init_db_objects(r) r.lock()
def add_scoreboard_params(robots): # adds necessary parameters to be displayed on the scoreboard for robot in robots: runs = r.get_registry()['RUNS'].get_runs(robot['id']) best_scores, attempted_levels, total_score, num_successful = ( ScoreCalculator.get_best_scores(runs) ) robot.update(best_scores) robot['TFS'] = total_score robot['completed'] = attempted_levels robot['num_successful'] = num_successful return robots
def robot_detail(robot_id, inputs=None): robot = r.get_registry()['ROBOTS'].get_robot(robot_id) if not robot: return render_template("not_found.html") runs = r.get_registry()['RUNS'].get_runs(robot_id) run_levels = [run['id'] for run in runs] # check if disqualifited and eligibility to advnace to next level eligibility = LevelProgressHandler.get_eligibility_for_next_run( runs, robot['level'] ) # get current best scores best_scores, attempted_levels, total_score, num_successful = ( ScoreCalculator.get_best_scores(runs) ) # check how many runs robot did on sunday (sunday = 1) # TODO: this logic needs to be rewritten after the competition sunday = 1 filtered = filter_runs_day(runs, sunday) already_run_three = False if len(filtered) >= 3: already_run_three = True return render_template( "robot.html", attempted_levels=attempted_levels, total_score=total_score, robot_id=robot_id, robot=robot, disqualified=eligibility['disqualified'], eligible=eligibility['can_level_up'], best_scores=best_scores, robot_runs=runs, applied_factors=[applied_factors(id, robot_id) for id in run_levels], inputs=inputs, already_run_three=already_run_three )
def scoreboard_gpmp(): robots = r.get_registry()['ROBOTS'].get_all_robots() # add additional parameters to be displayed on scoreboard robots = ScoreBoard.add_scoreboard_params(robots) # sort based on name then total score sorted_robots = sorted(list(robots), key=lambda k: k['name']) sorted_robots = sorted(list(sorted_robots), key=lambda k: k['TFS']) for robot in sorted_robots: robot['completed'] = list(robot['completed']) return jsonify({ 'robots': sorted_robots })
def scoreboard_gpmp(): robots = r.get_registry()['ROBOTS'].get_all_robots() if not robots: return render_template("not_found.html") # add additional parameters to be displayed on scoreboard robots = ScoreBoard.add_scoreboard_params(robots) # sort based on name then total score sorted_robots = sorted(list(robots), key=lambda k: k['name']) sorted_robots = sorted(list(sorted_robots), key=lambda k: k['TFS']) return render_template( "scoreboard_brd_gpmp.html", robots=sorted_robots, scoreboard_name="Grand Performance" )
def store(cls, name, prompt, passing_score, correct_names): query = """INSERT INTO questions(name, prompt, passing_score, correct_names) VALUES ( %(name)s, %(prompt)s, %(passing_score)s, %(correct_names)s );""" row_id = r.get_registry()['MY_SQL'].insert( query, { 'name': name, 'prompt': prompt, 'passing_score': passing_score, 'correct_names': ujson.dumps(correct_names) } ) return row_id
def run(): db = MySQLdb.connect( host=settings.mysql_host, port=settings.mysql_port, user=settings.mysql_user, passwd=settings.mysql_password) db.query('CREATE DATABASE IF NOT EXISTS scoring_system;') load_registry() r.get_registry()['MY_SQL'].query( 'ALTER DATABASE scoring_system CHARACTER SET ' 'utf8 COLLATE utf8_general_ci;' ) r.get_registry()['ROBOTS'].create_table() r.get_registry()['RUNS'].create_table()
def get_score(robot, data): return r.get_registry()['RUNS'].calculate_run_score( robot['division'], robot['level'], data['run_disqualified'], (to_float(data['seconds_to_put_out_candle_1']) + to_float(data['seconds_to_put_out_candle_2'])) / 2.0, data['non_air'], data['furniture'], data['arbitrary_start'], data['return_trip'], data['no_candle_circle'], data['stopped_within_30'], data['candle_detected'], to_int(data['number_of_rooms_searched']), data['kicked_dog'], to_int(data['touched_candle']), to_int(data['wall_contact_cms']), data['ramp_used'], data['baby_relocated'], data['all_candles'])
def prize_winners(): robots = r.get_registry()['ROBOTS'].get_all_robots() # calculate additional score parameters robots = ScoreBoard.add_scoreboard_params(robots) # gpmp_winner[place] dict gpmp_winners = ScoreBoard.get_gpmp_winners(robots) # lisp_winners[level][category][place] dict lisp_winners = ScoreBoard.get_lisp_winners(robots) # brd_winners[division][category][place] dict brd_winners = ScoreBoard.get_brd_winners(robots) return render_template( "prizes.html", gpmp_winners=gpmp_winners, lisp_winners=lisp_winners, brd_winners=brd_winners )
def run(): load_registry() robots = [ { "division": "junior", "id": "test-1", "volume": 365, "school": "Test", "name": "Jazz", "is_unique": True, "used_versa_valve": False, "level": 1, "is_disqualified": False, "passed_inspection": False, }, { "division": "high_school", "id": "test-2", "volume": 345, "school": "Test", "name": "Hanley", "is_unique": True, "used_versa_valve": False, "level": 1, "is_disqualified": False, "passed_inspection": False, }, { "division": "senior", "id": "test-3", "volume": 345, "school": "Test", "name": "Spazz", "is_unique": True, "used_versa_valve": False, "level": 1, "is_disqualified": False, "passed_inspection": False, }, ] for data in robots: r.get_registry()["ROBOTS"].record_robot( division=data["division"], id=data["id"], volume=data["volume"], school=data["school"], name=data["name"], is_unique=data["is_unique"], used_versa_valve=data["used_versa_valve"], level=data["level"], is_disqualified=data["is_disqualified"], passed_inspection=data["passed_inspection"], ) # Values of param for record_run is robot_div, level, # failed_trial, actual_time, reached_time_limit, # non_air, furniture, arbitrary_start, return_trip, # candle_location_mode, stopped_within_circle, # signled_detection, num_rooms_detected, kicked_dog, # touched_candle, cont_wall_contact, ramp_hallway, # alt_target, all_candles, used_versa_valve, score, robot_id # Just using dictionary for clarification jazz_runs = [ { "level": 1, "failed_trial": False, "actual_time": 155.742, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 1, "failed_trial": False, "actual_time": 132.614, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": True, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 4, "kicked_dog": True, "touched_candle": False, "cont_wall_contact": 16, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 1, "failed_trial": True, "actual_time": 340, # Some random number over 3 "reached_time_limit": True, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 1, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 2, "failed_trial": False, "actual_time": 150.304, "reached_time_limit": False, "non_air": False, "furniture": True, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 4, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 3, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 3, "failed_trial": True, "actual_time": 190, "reached_time_limit": True, "non_air": False, "furniture": True, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 3, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, ] hanley_runs = [ { "level": 1, "failed_trial": False, "actual_time": 285.742, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 1, "failed_trial": False, "actual_time": 39.234, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": True, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 3, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 8, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 2, "failed_trial": False, "actual_time": 150.304, "reached_time_limit": False, "non_air": False, "furniture": True, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 4, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 3, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 3, "failed_trial": True, "actual_time": 450, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 0, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 3, "failed_trial": False, "actual_time": 58.222, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": True, "used_versa_valve": False, }, ] spazz_runs = [ { "level": 1, "failed_trial": True, "actual_time": 285.742, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 3, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 1, "failed_trial": False, "actual_time": 85.641, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 1, "failed_trial": True, "actual_time": 285.742, "reached_time_limit": False, "non_air": False, "furniture": False, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 2, "failed_trial": False, "actual_time": 187.638, "reached_time_limit": False, "non_air": True, "furniture": True, "arbitrary_start": True, "return_trip": True, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 4, "kicked_dog": True, "touched_candle": True, "cont_wall_contact": 0, "ramp_hallway": False, "alt_target": False, "all_candles": False, "used_versa_valve": False, }, { "level": 3, "failed_trial": False, "actual_time": 117, "reached_time_limit": False, "non_air": False, "furniture": True, "arbitrary_start": False, "return_trip": False, "candle_location_mode": False, "stopped_within_circle": False, "signaled_detection": False, "num_rooms_detected": 2, "kicked_dog": False, "touched_candle": False, "cont_wall_contact": 0, "ramp_hallway": True, "alt_target": True, "all_candles": True, "used_versa_valve": False, }, ] for run in jazz_runs: jazz_robot = robots[0] robot_div = jazz_robot["division"] robot_id = jazz_robot["id"] score_components = ( robot_div, run["level"], run["failed_trial"], run["actual_time"], run["non_air"], run["furniture"], run["arbitrary_start"], run["return_trip"], run["candle_location_mode"], run["stopped_within_circle"], run["signaled_detection"], run["num_rooms_detected"], run["kicked_dog"], run["touched_candle"], run["cont_wall_contact"], run["ramp_hallway"], run["alt_target"], run["all_candles"], ) r.get_registry()["RUNS"].record_run( run["level"], run["failed_trial"], run["actual_time"], run["non_air"], run["furniture"], run["arbitrary_start"], run["return_trip"], run["candle_location_mode"], run["stopped_within_circle"], run["signaled_detection"], run["num_rooms_detected"], run["kicked_dog"], run["touched_candle"], run["cont_wall_contact"], run["ramp_hallway"], run["alt_target"], run["all_candles"], run["used_versa_valve"], Runs.calculate_run_score(*score_components), robot_id, ) for run in hanley_runs: hanley_robot = robots[1] robot_div = hanley_robot["division"] robot_id = hanley_robot["id"] score_components = ( robot_div, run["level"], run["failed_trial"], run["actual_time"], run["non_air"], run["furniture"], run["arbitrary_start"], run["return_trip"], run["candle_location_mode"], run["stopped_within_circle"], run["signaled_detection"], run["num_rooms_detected"], run["kicked_dog"], run["touched_candle"], run["cont_wall_contact"], run["ramp_hallway"], run["alt_target"], run["all_candles"], ) print "score components:" print (score_components) r.get_registry()["RUNS"].record_run( run["level"], run["failed_trial"], run["actual_time"], run["non_air"], run["furniture"], run["arbitrary_start"], run["return_trip"], run["candle_location_mode"], run["stopped_within_circle"], run["signaled_detection"], run["num_rooms_detected"], run["kicked_dog"], run["touched_candle"], run["cont_wall_contact"], run["ramp_hallway"], run["alt_target"], run["all_candles"], run["used_versa_valve"], Runs.calculate_run_score(*score_components), robot_id, ) for run in spazz_runs: spazz_robot = robots[2] robot_div = spazz_robot["division"] robot_id = spazz_robot["id"] score_components = ( robot_div, run["level"], run["failed_trial"], run["actual_time"], run["non_air"], run["furniture"], run["arbitrary_start"], run["return_trip"], run["candle_location_mode"], run["stopped_within_circle"], run["signaled_detection"], run["num_rooms_detected"], run["kicked_dog"], run["touched_candle"], run["cont_wall_contact"], run["ramp_hallway"], run["alt_target"], run["all_candles"], ) r.get_registry()["RUNS"].record_run( run["level"], run["failed_trial"], run["actual_time"], run["non_air"], run["furniture"], run["arbitrary_start"], run["return_trip"], run["candle_location_mode"], run["stopped_within_circle"], run["signaled_detection"], run["num_rooms_detected"], run["kicked_dog"], run["touched_candle"], run["cont_wall_contact"], run["ramp_hallway"], run["alt_target"], run["all_candles"], run["used_versa_valve"], Runs.calculate_run_score(*score_components), robot_id, )
def add_run(robot_id, params_d): robot = r.get_registry()['ROBOTS'].get_robot(robot_id) score = get_score(robot, params_d) params_t = convert_to_tuple(params_d, robot_id, score) r.get_registry()['RUNS'].record_run(*params_t)
def cache_result(cls, question): r.get_registry()['REDIS'].hmset( cls.get_redis_key(question['id']), question )
def run(): load_registry() division_map = { 'fire fighting high school division': 'high_school', 'fire fighting junior division': 'junior', 'fire fighting senior division': 'senior', 'fire fighting walking division': 'walking' } unique_map = { 'unique': True, 'customized': False, 'i am not sure': False } versa_valve_map = { 'yes': True, 'no': False } fields_index = { 'division': 3, 'name': 4, 'unique': 5, 'versa_valve': 6, 'school': 7 } with open('robot_list.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile) i = 0 id_counter = { 'high_school': 1, 'senior': 1, 'walking': 1, 'junior': 1 } for row in spamreader: if i == 0: i += 1 continue i += 1 d = {} if row[fields_index['unique']].strip().lower() == ( 'i am not sure, please contact me to discuss'): continue for field, index in fields_index.iteritems(): if field == 'division': d[field] = division_map[row[index].strip().lower()] elif field == 'unique': d[field] = unique_map[row[index].strip().lower()] elif field == 'versa_valve': d[field] = versa_valve_map[row[index].strip().lower()] else: d[field] = row[index] d['id'] = get_id(id_counter, d) r.get_registry()['ROBOTS'].record_robot( division=d['division'], id=d['id'], volume=0, school=d['school'], name=d['name'], is_unique=d['unique'], used_versa_valve=d['versa_valve'], level=1, is_disqualified=False, passed_inspection=False )