class Profile(): def __init__(self, username, sex): self.username = username self.bio = [] self.sex = sex self.hydration = 0 self.hydration_goal = 0 self.workout = Workout(self.name) current = datetime.date(datetime.now()) split = current.split('-') int_date = split[1] * 100 + split[2] self.date = int_date def edit_bio(self, newbio): self.bio.clear() self.bio.append(newbio) # HYDRATION METER def add_hydration(self, hydration): #add "hydration" to the current amount of water drank if (self.sex == "male"): self.hydration_goal = 3.7 #in liters elif (self.sex == "female"): self.hydration_goal = 2.7 #in liters self.hyrdation += hydration def hydration_goal(self): #checks if the hydration goal is met# Check if hydration goal reached if self.hydration >= self.hydration_goal: return True else: return False def hydration_percentage(self): percent = self.hydration / self.hydration_goal return percent #CALENDAER/ Time component def reset_day(self): current = datetime.date(datetime.now()) split = current.split('-') int_date = split[1] * 100 + split[2] if int_date != self.date: self.workout.reset_daily_goal() self.date = int_date def find_active_streak(self): current_date = datetime.now() Completed = True temp_date = current_date - timedelta(1) c = 0 while (Completed): Completed = self.workout.calendar.cal[temp_date].check_status() c += 1 return c
def __init__(self, username, sex): self.username = username self.bio = [] self.sex = sex self.hydration = 0 self.hydration_goal = 0 self.workout = Workout(self.name) current = datetime.date(datetime.now()) split = current.split('-') int_date = split[1] * 100 + split[2] self.date = int_date
def form_data(): conn = sqlite3.connect('mydb.db') c = conn.cursor() if "id" in request.form: user_id = request.cookies['user'] c1 = Workout(request.form['name'], request.form['description'], request.form['length'], request.form['video'], request.form['type'], user_id, id=request.form['id']) print(c1.id, c1.description) c.execute( """UPDATE workouts SET name = :name, description = :description, length = :length, video_url= :video_url, type = :type WHERE id = :id """, { "name": c1.name, "description": c1.description, "length": c1.length, "video_url": c1.video_url, "type": c1.type, "id": c1.id }) conn.commit() conn.close() return redirect(url_for('index', is_edited=True)) else: user_id = request.cookies['user'] c1 = Workout(request.form['name'], request.form['description'], request.form['length'], request.form['video'], request.form['type'], user_id) c.execute( """INSERT INTO workouts VALUES(:id, :name, :description, :length, :video_url, :type, :user_id)""", { "id": c1.id, "name": c1.name, "description": c1.description, "length": c1.length, "video_url": c1.video_url, "type": c1.type, "user_id": c1.user_id }) conn.commit() conn.close() return redirect(url_for('index', is_sent=True))
def simulate(self): human_list = self.human_list for human_data in human_list: workout = Workout(20, human_data) while workout.pt_count > 0: if round(human_data.bmi) == 23: workout.exercise() print( "{}번 님, {}일만에 Diet를 성공하셨네요!!! 남은 pt는 {}회 입니다.".format( workout.human.id, workout.days, workout.pt_count)) self.success.append(workout.human) break if human_data.fatigue < 90: workout.days += 1 workout.pt_count -= 1 workout.exercise() else: workout.days += 1 workout.rest() # while문이 끝난 경우 if workout.pt_count == 0: print("{}번 님, {}일 동안 열심히 했지만 아직 목표치에 도달하지 못했네요 ㅠㅠ " "조금 더 노력하면 목표치에 도착할 수 있을거에요!!".format( workout.human.id, workout.days)) self.failure.append(workout.human)
def validate_and_save_workout(self, workout): try: validated_workout = Workout(workout) result = self.fitness_repository.store_workout(validated_workout) return '', result except AttributeError as err: return str(err), 400
def build_workout_sample(): workout1 = Workout() workout1.date = '2018-02-19' execution1 = Execution() execution1.exercise = build_exercise_sample() set1, set2, set3 = Set(), Set(), Set() set1.start_time = '2018-02-19T16:10:35Z' set1.repetitions = 10 set1.weight = 40 set2.start_time = '2018-02-19T16:12:35Z' set2.repetitions = 9 set2.weight = 42 set3.start_time = '2018-02-19T16:14:35Z' set3.repetitions = 8 set3.weight = 42 execution1.sets = [set1, set2, set3] workout1.executions = [execution1] return workout1
def edit_workout(id): conn = sqlite3.connect('mydb.db') c = conn.cursor() c.execute("""SELECT * FROM workouts WHERE id=:id""", {"id": id}) row = c.fetchone() c1 = Workout(row[1], row[2], row[3], row[4], row[5], row[6], id=row[0]) conn.close() return render_template('editWorkout.html', workout=c1)
def get_workout(db_conn, a_id): sqlSelect = "SELECT * from Workout WHERE A_ID = '{}'".format(a_id) results = db_conn.execute(sqlSelect) workout_data = results.fetchone() print(workout_data) if workout_data == None: return False else: workout_plan = Workout(workout_data) return workout_plan
def index(): if 'is_sent' in request.args: show_msg = True msg = "Your workout has been added!" elif 'is_deleted' in request.args: show_msg = True msg = "Your workout has been removed!" elif "is_edited" in request.args: show_msg = True msg = "Your workout has been updated!" elif "user_created" in request.args: show_msg = True msg = "Your user has been created!" elif "user_is_deleted" in request.args: show_msg = True msg = "The user has been deleted!" elif 'correct_action' in request.args: show_msg = True msg = "You are now connected!" else: show_msg = False msg = "" conn = sqlite3.connect('mydb.db') c = conn.cursor() connected_user = get_connected_user(c) is_connected, username = get_is_connected_and_name(connected_user) if not is_connected: return render_template('index.html', show_msg=show_msg, msg=msg, is_connected=is_connected, username=username) c.execute("SELECT * FROM workouts WHERE user_id = :connected_user", {"connected_user": connected_user.user_id}) rows = c.fetchall() workouts = [] for row in rows: c = Workout(row[1], row[2], row[3], row[4], row[5], row[6], id=row[0]) workouts.append(c) return render_template('index.html', workouts=workouts, show_msg=show_msg, msg=msg, is_connected=is_connected, username=username)
def test_happy_path(self): valid_workout = Workout({ "distance": "1.23", "start_time": "a_time", "end_time": "another_time" }) self.mock_cursor.execute = MagicMock() self.mock_cursor.close = MagicMock() self.mock_conn.cursor = MagicMock(return_value=self.mock_cursor) self.mock_conn.commit = MagicMock() self.assertEqual(self.repository.store_workout(valid_workout), 202)
def __init__(self, user_id, workout_template): self.workout = Workout() print 'templates' self.template = pickle.loads(templates.find_one()['template_object']) print 'after templates' self.state = NOT_STARTED self.workout_state = None self.prev_user_set = None self.template.intro = 'Chest and Triceps' ut.send_response(self.template.intro, user_id) ut.send_response(START_WORKOUT, user_id)
def startWorkout(request): ''' Renders the page with the current workout and starts training ''' global workout, th try: # stop the thread with previous workout if it is running th.do_run = False except: pass workout = Workout() try: workouts = [workoutName] except: pass # display the workout that was selected before the page reload for wk in Workouts.objects.values_list('workout_name').distinct(): try: if wk[0] != workoutName: workouts.append(wk[0]) except: workouts.append(wk[0]) training_program, models = {}, {} restTimes = [] isTabata = True # form the training program for ex in exercises: training_program[ex.exercise.exercise_name] = ex.numRepeats models[ex.exercise.exercise_name] = ex.exercise.model_path isTabata = ex.isTabata restTimes.append(ex.restTime) # start workout and movement counting in a separate thread th = threading.Thread(target=workout.runTraining, args=(training_program, models, isTabata, restTimes)) th.setDaemon(True) th.start() # tell the thread it should run th.do_run = True try: template = "index.html" return render(request, template, {'workouts': workouts}) except Exception as e: print("error", e)
def delete(self, id=None): #if there is an id, delete it if id: #Remove exercise from workouts for w in Workout.query().fetch( ): #fetch all workout from the database delFlag = -1 for i, exID in enumerate(w.exerciseIDs): if exID == id: delFlag = i self.response.write("match found" + str(i)) if delFlag != -1: w.exerciseIDs.pop(delFlag) w.put() ndb.Key(urlsafe=id).delete() #delete workout
def get(self, id=None): #return workout ids with list of exercise ids in JSON format relationship_dict = [] #dictionary to store relationships in if id: for r in Workout.query().fetch( ): #fetch all workout from the database r_d = "{\"workoutURLID\":\"" + r.workoutURLID + "\"" y = 0 for x in r.exerciseIDs: r_d = r_d + ", \"exerciseURLID" + str( y) + "\":\"" + r.exerciseIDs[y] + "\"" y = y + 1 #self.response.write(r_d) r_d = r_d + "}" relationship_dict.append(r_d) self.response.write(json.dumps( relationship_dict)) ###u' is being generated here by json.dumps()
def index(request): ''' Loads the workout page ''' global workout workout = Workout() global workouts # add all workouts from the database to the drop down list workouts = [] for index, wk in enumerate( Workouts.objects.values_list('workout_name').distinct()): workouts.append(wk[0]) try: template = "index.html" return render(request, template, {'workouts': workouts}) except Exception as e: print("error", e)
def execute(self): # Create workout event e = Workout() loc = input("Enter the location: ") calo = input("Enter calories to be burned: ") if "tags" in self.details: e.setTags(self.details["tags"]) for tag in self.details["tags"]: e.updateDescription(self.details["tags"]) if "time" in self.details: e.updateStartTime(self.details["time"]) e.updateLocation(loc) e.setCalories(calo) # User verification #print(e) # Cannot print out Workout resume = input("Is this what you wanted to add? (y/n): ") while resume != 'y': print("Start time") print("End time") print("Description") print("Location") print("Calories") e_change = input("What would you like to change?: ") newData = input("Set it here: ") # Is there an easier way to process user input? if e_change == "Start time": datetime_obj, _ = cal.parseDT( datetimeString=newData, tzinfo=timezone(DEFAULT_TIMEZONE)) e.updateStartTime(datetime_obj) elif e_change == "End time": datetime_obj, _ = cal.parseDT( datetimeString=newData, tzinfo=timezone(DEFAULT_TIMEZONE)) e.updateEndTime(datetime_obj) elif e_change == "Description": e.updateDescription(newData) elif e_change == "Location": e.updateLocation(newData) elif e_change == "Calories": e.setCalories(newData) else: print("Invalid request to change.") #print(e) resume = input("Retry change? (y/n): ") # Add to calendar self.calendar.addToCalendar(e)
NavigationItem = namedtuple('NavigationItem', 'id title icon') app = Flask(__name__) with open('config.yaml', 'r') as f: config = yaml.full_load(f) locale = config['locale'] if 'locale' in config else 'en' babel = Babel(app, default_locale=locale) with app.app_context(): # this is required to have translations in loading functions _agenda = Agenda() _journaling = Journaling(config['journaling']) _workout = None if 'workout' in config: _workout = Workout(config['workout']) _tasks = None if 'redmine' in config: config['redmine']['date_format'] = config['date_format'] # copy from global _tasks = Tasks(config['redmine']) @app.route('/') def index_page(): content_left = '' content_right = '' navigation = [] content_right += get_user_content_right() content_right += _journaling.render_journal() + render_template('journaling_static.html')
startdate = datetime(2016,2,22,tzinfo=pytz.utc) volume = 1000.0 workout_day_inc = [1, 2, 2, 2] wp = WorkoutProgram("Strength Training", startdate, volume, 12, "Matt") dayIndex = 0 workoutCount = 0 totalWorkouts = 36 # ------------------ Workout Generation --------------------# for week in range(0, wp.workoutprogram_nWeeks): dayIndex = dayIndex + workout_day_inc[0] wPercent = workout.periodization_equation(workoutCount, totalWorkouts) workoutCount = workoutCount + 1 workoutdate = wp.workoutprogram_dt_start + timedelta(days=dayIndex) wkout = Workout("%s - Strength" % (workoutdate.strftime("%A")), workoutdate, wPercent, volume) rndex = wkout.pick_random_exercise("Press") wkout.add_exercise_target_volume(rndex['name'], 5) rndex = wkout.pick_random_exercise("Jerk") wkout.add_exercise_target_volume(rndex['name'], 5) rndex = wkout.pick_random_exercise("Squat") wkout.add_exercise_target_volume(rndex['name'], 5) wkout.add_exercise_target_volume("Deadlift", 5) wkout.add_exercise("Push ups") rndex = wkout.pick_random_exercise("Core") wkout.add_exercise(rndex['name']) wp.add_workout(wkout) wPercent = workout.periodization_equation(workoutCount, totalWorkouts) workoutCount = workoutCount + 1 dayIndex = dayIndex + workout_day_inc[1]
startdate = datetime(2016,2,29,tzinfo=pytz.utc) volume = 550.0 workout_day_inc = [1, 2, 2, 2] wp = WorkoutProgram("Climbing Training", startdate, volume, 12, "Matt") dayIndex = 0 workoutCount = 0 totalWorkouts = 36 # ------------------ Workout Generation --------------------# for week in range(0, wp.workoutprogram_nWeeks): dayIndex = dayIndex + workout_day_inc[0] wPercent = workout.periodization_equation(workoutCount, totalWorkouts) workoutCount = workoutCount + 1 workoutdate = wp.workoutprogram_dt_start + timedelta(days=dayIndex) wkout = Workout("%s - Strength" % (workoutdate.strftime("%A")), workoutdate, wPercent, volume) wkout.add_exercise_target_volume("Climbing", 8) rndex = wkout.pick_random_exercise("Core") wkout.add_exercise(rndex['name']) wp.add_workout(wkout) wPercent = workout.periodization_equation(workoutCount, totalWorkouts) workoutCount = workoutCount + 1 dayIndex = dayIndex + workout_day_inc[1] workoutdate = wp.workoutprogram_dt_start + timedelta(days=dayIndex) wkout = Workout("%s - Strength" % (workoutdate.strftime("%A")), workoutdate, wPercent, volume) wkout.add_exercise_target_volume("Climbing", 8) rndex = wkout.pick_random_exercise("Core") wkout.add_exercise(rndex['name']) wp.add_workout(wkout)
class WorkoutGuider(): """ Class that is used to guide a user through a workout template and simultaneously log their workout """ def __init__(self, user_id, workout_template): self.workout = Workout() print 'templates' self.template = pickle.loads(templates.find_one()['template_object']) print 'after templates' self.state = NOT_STARTED self.workout_state = None self.prev_user_set = None self.template.intro = 'Chest and Triceps' ut.send_response(self.template.intro, user_id) ut.send_response(START_WORKOUT, user_id) def process(self, text, user, user_id): """ Processes user input for a given state state = NOT_STARTED ---> ask user to start state = IN_WORKOUT ---> log current set reported by user Returns bool representing successful parse and whether we should move on to next set """ #=====[ If user has not started workout ]===== if self.state == NOT_STARTED: if 'yes' in text: #=====[ hard coding timers for now ]===== self.template.workout.timer = [45, 60] user.timer = self.template.workout.timer ut.update(user_id, user) self.state = IN_WORKOUT self.workout_state = (0, -1) return (True, True) else: ut.send_response(START_WORKOUT,user_id) return (False, False) #=====[ If in workout, log state ]===== elif self.state == IN_WORKOUT: sub_state, set_state = self.workout_state user_set = ut.extract_exercise(text) if user_set: template_workout = self.template.workout sub_state, set_state = self.workout_state xsets = template_workout.subroutines[sub_state].get_flattened_sets() user_set.exercise = xsets[set_state].exercise #=====[ Log set and give feedback ]===== workout_log.log_set(user_set, self.workout, user, user_id) ut.send_response('Got your last set to be: ' + str(user_set), user_id) self.prev_user_set = user_set return (self.cur_set_feedback(user_set, xsets[set_state], user_id), True) else: ut.send_response('Exercise not recognized, please retry', user_id) return (False, False) def subroutine_intro(self, user_id): sub_state = self.workout_state[0] subroutine = self.template.workout.subroutines[sub_state] response = 'Subroutine is:\n' for exercise in subroutine.exercises: response += exercise + '\n' ut.send_response(response, user_id) def next_set(self, user_id): sub_state, set_state = self.workout_state # Get the subroutine of the current set curr_subroutine = self.template.workout.subroutines[sub_state] set_state += 1 if set_state >= curr_subroutine.num_sets: set_state = 0 sub_state += 1 if sub_state >= len(self.template.workout.subroutines): return None # Update curr_subroutine after updating indexes curr_subroutine = self.template.workout.subroutines[sub_state] sets_per_cycle = len(curr_subroutine.exercises) subroutine_mode = curr_subroutine.mode # Update object workout state self.workout_state = (sub_state, set_state) # set_state == 0 means we are starting a new subroutine if set_state == 0: self.subroutine_intro(user_id) self.workout.add_subroutine() next_subroutine = self.template.workout.subroutines[sub_state] self.workout.new_subroutine(next_subroutine.mode, next_subroutine.exercises) # If we are at the beginning of a cycle in a circuit if subroutine_mode == "circuit" and set_state % sets_per_cycle == 0: response = "Next Cycle of Circuit: \n" sets = self.template.workout.subroutines[sub_state].get_flattened_sets() for i in range(sets_per_cycle): xset = sets[set_state + i] response += xset.exercise + ' ' + str(xset) + "\n" ut.send_response(response, user_id) # TODO: FOR BRANDON # get_feedback - current user set, current template set, next template set (None for diff subroutine) response = "Your next set is: " sets = self.template.workout.subroutines[sub_state].get_flattened_sets() xset = sets[set_state] response += xset.exercise + ' ' + str(xset.reps) + " reps\n" message = True #=====[ Give feedback for up and coming set ]===== if self.prev_user_set: message = self.next_set_feedback(self.prev_user_set, xset, user_id) ut.send_response(response, user_id) print 'message to return is:', message print self.workout_state print set_state if self.workout_state: return (message, False) if set_state != 0 else (message, True) else: return (self.workout_state, False) def cur_set_feedback(self, user_set, cur_set, user_id): """ Analyzes a user's current set and gives feedback """ message = '' #=====[ Check to see if we're giving feedback on a body weight set ]===== if cur_set.weight == None and user_set.weight == None: #=====[ If user did more sets than required ]===== if int(user_set.reps) > int(cur_set.reps): message = GOOD_REPS_NO_WEIGHT else: rep_percentage = float(user_set.reps)/float(cur_set.reps) if int(user_set.reps) < int(cur_set.reps): #=====[ Feedback on not doing enough reps on current set ]===== if rep_percentage: message = DID_TOO_MUCH_WEIGHT + str(int(rep_percentage*100)) + "% of your reps. " elif int(user_set.reps) != int(cur_set.reps) - 1: message = DID_A_BIT_TOO_MUCH_WEIGHT if int(user_set.reps) > int(cur_set.reps): #=====[ Feedback on doing too many reps on current set ]===== if rep_percentage > 1.3: message = DID_NOT_DO_ENOUGH_WEIGHT + str(int((rep_percentage-1)*100)) + "%. " elif int(user_set.reps) != int(cur_set.reps) + 1: message = DID_A_BIT_TOO_LIGHT print 'the message is :', message return message def next_set_feedback(self, user_set, next_set, user_id): """ Analyzes a user's current set and gives feedback for next set """ if next_set.weight: #=====[ Give feedback on weight for next set ]===== if int(user_set.reps) < int(next_set.reps) - 1: return REDUCE_WEIGHT elif int(user_set.reps) > int(next_set.reps) + 1: return INCREASE_WEIGHT else: return KEEP_WEIGHT else: if int(user_set.reps) < int(next_set.reps): return MORE_REPS_NO_WEIGHT