예제 #1
0
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 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
예제 #3
0
    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)
예제 #4
0
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)
예제 #5
0
    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)
예제 #6
0
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
예제 #7
0
    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
예제 #8
0
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)
예제 #10
0
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)
예제 #11
0
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
예제 #12
0
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)
예제 #13
0
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')