Exemplo n.º 1
0
    def test_exercise_comment_model(self):
        """Test user commentting functionality on an exercise."""

        # Create test exercises
        e1 = Exercise(name="Bench Press",
                      description="Chest exercise",
                      category_id=10)
        e1.id = 500
        e2 = Exercise(name="Triceps Pushdown",
                      description="Triceps exercise",
                      category_id=11)
        e2.id = 501

        # Create test user
        u = User.register("testing1", "password", "*****@*****.**", "John",
                          "Doe", None)
        u.id = 777

        db.session.add_all([e1, e2])

        uc1 = ExerciseComment(content="Test1", user_id=u.id, exercise_id=e1.id)
        uc2 = ExerciseComment(content="Test2", user_id=u.id, exercise_id=e2.id)

        db.session.add_all([uc1, uc2])

        db.session.commit()

        ucs = ExerciseComment.query.filter_by(user_id=u.id)

        self.assertEqual(ucs.count(), 2)
        self.assertEqual(ucs[0].exercise_id, e1.id)
        self.assertEqual(ucs[0].user_id, u.id)
        self.assertEqual(ucs[1].exercise_id, e2.id)
        self.assertEqual(ucs[1].user_id, u.id)
Exemplo n.º 2
0
    def test_user_exercise_model(self):
        """Test adding exercises to a user's exercises functionality."""

        # Create test exercises
        e1 = Exercise(name="Bench Press",
                      description="Chest exercise",
                      category_id=10)
        e1.id = 500
        e2 = Exercise(name="Triceps Pushdown",
                      description="Triceps exercise",
                      category_id=11)
        e2.id = 501

        # Create test user
        u = User.register("testing1", "password", "*****@*****.**", "John",
                          "Doe", None)
        u.id = 777

        db.session.add_all([e1, e2])

        ue1 = UserExercise(user_id=u.id, exercise_id=e1.id)
        ue2 = UserExercise(user_id=u.id, exercise_id=e2.id)

        db.session.add_all([ue1, ue2])

        db.session.commit()

        exc = UserExercise.query.filter_by(user_id=u.id)

        self.assertEqual(exc.count(), 2)
        self.assertEqual(exc[0].exercise_id, e1.id)
        self.assertEqual(exc[1].exercise_id, e2.id)
Exemplo n.º 3
0
    def test_exercise_model(self):
        """Test basic exercise model."""

        # Create test exercises
        e1 = Exercise(name="Bench Press",
                      description="Chest exercise",
                      category_id=10)
        e1.id = 500
        e2 = Exercise(name="Triceps Pushdown",
                      description="Triceps exercise",
                      category_id=11)
        e2.id = 501

        db.session.add_all([e1, e2])

        db.session.commit()

        e = Exercise.query.all()

        self.assertEqual(len(e), 2)
        self.assertEqual(e[0].id, e1.id)
        self.assertEqual(e[0].name, "Bench Press")
        self.assertEqual(e[0].description, "Chest exercise")
        self.assertEqual(e[1].id, e2.id)
        self.assertEqual(e[1].name, "Triceps Pushdown")
        self.assertEqual(e[1].description, "Triceps exercise")
Exemplo n.º 4
0
def demo_exercise():
    from models import Exercise
    run = Exercise.query.filter(Exercise._name=='Run').first()
    walk = Exercise.query.filter(Exercise._name=='Walk').first()
    if run is None:
        run = Exercise('Run', '4 mph')
        db.session.add(run)
        db.session.commit()
    if walk is None:
        walk = Exercise('Walk', '2 mph')
        db.session.add(walk)
        db.session.commit()
    return run, walk
Exemplo n.º 5
0
def process_exercise(name, starting_path, clone_dir, blob_prefix, mapper,
                     bucket, user):
    tqdm.write(f"Processing exercise:{name}")
    exercise_path = f"{starting_path}/{name}"
    with tarfile.open(f"{exercise_path}/{name}.tar.gz", "w:gz") as f:
        f.add(f"{exercise_path}/", arcname=name, recursive=True)

    upload_folder(exercise_path, starting_path, mapper.language, bucket)

    has_hint = mapper.hint_exists(exercise_path)
    mappings = mapper.get_files_mappings(blob_prefix, name, has_hint=has_hint)
    metadata = mapper.get_metadata(clone_dir)
    topics, difficulty = next(
        iter([(ex["topics"], ex["difficulty"]) for ex in metadata
              if ex["slug"] == name]), (None, None))
    exercise = Exercise(name=name,
                        language=mapper.language,
                        description=mapper.pluck_readme(exercise_path),
                        topics=topics,
                        difficulty=difficulty,
                        creator=user.email)

    files = Artifact(readme=mappings["readme"],
                     solution=mappings["solution"],
                     starting_point=mappings["starting_point"],
                     test=mappings["test"],
                     hint=mappings["hint"],
                     compressed=mappings["compressed"],
                     exercise=exercise)

    return (exercise, files)
Exemplo n.º 6
0
def add_workout():
    if request.method == 'POST':
        user = User.query.filter_by(name=session['username']).first()
        workout = Workout(date=datetime.utcnow(), user_id=user.id)

        exercise_count = int(request.form['exercise_count'])
        for exercise_num in range(1, exercise_count + 1):
            exercise = Exercise(order=1,
                                exercise_id=request.form['exercise' +
                                                         str(exercise_num)],
                                workout=workout)
            weights = request.form.getlist('weight' + str(exercise_num))
            reps = request.form.getlist('reps' + str(exercise_num))

            set_order = 1
            for weight, rep in zip(weights, reps):
                work_set = Set(order=set_order,
                               exercise=exercise,
                               weight=weight,
                               reps=reps)
                set_order += 1

        db.session.add(workout)
        db.session.commit()
        return redirect(url_for('index'))

    exercises = Exercises.query.all()
    return render_template('add_workout.html', exercises=exercises)
Exemplo n.º 7
0
def get_all_exercises():

    response = requests.get('https://curric.rithmschool.com/r13/exercises/')
    soup = BeautifulSoup(response.text)
    links = []

    # Drop Exercise table
    engine = create_engine(ProductionConfig.SQLALCHEMY_DATABASE_URI)
    Exercise.__table__.drop(engine)
    db.create_all()

    # Set up current exercises to test for duplicates
    current_exercises = []
    for exercise in Exercise.query.all():
        current_exercises.append(exercise.title)

    for link in soup.find_all('a'):
        links.append('https://curric.rithmschool.com/r13/exercises/' +
                     link.get('href'))

    for link in links:
        if 'zip' in link:
            continue

        response = requests.get(link)
        soup = BeautifulSoup(response.text)
        if (soup.title is None):
            continue
        if (soup.title.string == 'Rithm Curriculum'):
            continue
        else:
            new_exercise = Exercise(title=soup.title.string, url=link)
            db.session.add(new_exercise)

    db.session.commit()
Exemplo n.º 8
0
def get_exercises():
    """Get exercises from API and place them in db."""
    request = requests.get(
        'https://wger.de/api/v2/exercise?language=2&limit=250')

    result = request.json()

    # Find all exercises currently stored in database
    exercises = Exercise.query.all()

    exercise_ids = []

    for exercise in exercises:
        exercise_ids.append(exercise.id)

    for item in result['results']:
        if item['id'] not in exercise_ids:
            exercise = Exercise(id=item['id'],
                                name=item['name'],
                                description=item['description'],
                                category_id=item['category'])

            db.session.add(exercise)

            db.session.commit()
Exemplo n.º 9
0
def test_delete():
    entry = ExerciseEntry.ExerciseEntry()
    entry.delete(TEST_ENTRY_DATA["user_id"],
                 TEST_ENTRY_DATA["exercise_entry_id"])
    exercise = Exercise.Exercise()
    exercise.delete(TEST_EXERCISE_DATA["user_id"],
                    TEST_EXERCISE_DATA["exercise_id"])
    assert entry.get_one(TEST_ENTRY_DATA["exercise_entry_id"]) is None
Exemplo n.º 10
0
def generate_percentage_exercise():
    percentage_equations_factory = PercentageEquationsFactory()

    exercise = Exercise()

    percentage_equations_factory.appendTo(exercise)

    return render_template('exercise.html', exercise=exercise)
Exemplo n.º 11
0
def test_update_invalid_data_types():
    exercise = Exercise.Exercise()
    copy = dict(TEST_EXERCISE_DATA)
    copy.update({
        "amount": "this is not an int",
        "description": 123,
    })
    res = exercise.update(copy)
    assert res is None
Exemplo n.º 12
0
def generate_division_exercise():
    three_digit_rounded_division_equations_factory = RoundedDivisionEquationsFactory(
    )

    exercise = Exercise()

    three_digit_rounded_division_equations_factory.appendTo(exercise)

    return render_template('exercise.html', exercise=exercise)
Exemplo n.º 13
0
def generate_multiplication_exercise():
    two_digit_multiplication_equations_factory = TwoDigitMultiplicationEquationsFactory(
    )

    exercise = Exercise()

    two_digit_multiplication_equations_factory.appendTo(exercise)

    return render_template('exercise.html', exercise=exercise)
Exemplo n.º 14
0
def generate_exercise():
    subtraction_equations_factory = SubtractionEquationsFactory()
    multiplication_equations_factory = MultiplicationEquationsFactory()

    exercise = Exercise()

    subtraction_equations_factory.appendTo(exercise)
    multiplication_equations_factory.appendTo(exercise)

    return render_template('exercise.html', exercise=exercise)
Exemplo n.º 15
0
    def setUp(self):
        """
        Define test variables and initialize app
        Has to be in this awkward camelCase to overload method in TestCase
        """
        self.app = create_app()
        self.client = self.app.test_client

        self.database_path = os.environ['HEROKU_POSTGRESQL_AQUA_URL']
        setup_db(self.app, self.database_path)

        # binds the app to the current context
        with self.app.app_context():

            # populate tables with test values
            e1 = Exercise(
                name='kb swing',
                equipment='kettlebell',
                target='reps',
                link='dummy link'
            )
            e2 = Exercise(
                name='kb goblet squat',
                equipment='kettlebell',
                target='reps',
                link='another dummy link here'
            )
            e1.insert()
            e2.insert()
            w = Workout(
                name='test workout',
                focus='legs',
                repeat=False
            )
            w.insert()
            m = WorkoutExercise(
                workout_id=1,
                exercise_id=1,
                sets=3,
                reps=8,
                weight=4
            )
            m.insert()
Exemplo n.º 16
0
 def create(self, validated_data):
     e = Exercise(name=validated_data['name'],
                  order=validated_data['order'],
                  repsStart=validated_data['repsStart'],
                  repsEnd=validated_data['repsEnd'],
                  setsStart=validated_data['setsStart'],
                  setsEnd=validated_data['setsEnd'],
                  workout_id=validated_data['workout_id'],
                  owner=validated_data['owner'])
     e.save()
     return e
Exemplo n.º 17
0
def test_create():
    entry = ExerciseEntry.ExerciseEntry()
    exercise = Exercise.Exercise()
    exercise_id = exercise.create(TEST_EXERCISE_DATA["user_id"],
                                  TEST_EXERCISE_DATA)["exercise_id"]
    TEST_ENTRY_DATA["exercise_id"] = exercise_id
    TEST_EXERCISE_DATA["exercise_id"] = exercise_id
    res = entry.create(TEST_ENTRY_DATA["user_id"],
                       TEST_ENTRY_DATA["exercise_id"], TEST_ENTRY_DATA)
    TEST_ENTRY_DATA.update({"exercise_entry_id": res["exercise_entry_id"]})
    assert res is not None
Exemplo n.º 18
0
def agregarExercise(idPersona, exerciseTime, date):
    try:
        query=Exercise(
                idPersona=idPersona,
                exerciseTime=exerciseTime,
                date=date
            )
        db.session.add(query)
        db.session.commit()
        return "exercise added. exercise id={}".format(query.id)
    except Exception as e:
        return(str(e))
Exemplo n.º 19
0
def test_update():
    exercise = Exercise.Exercise()
    copy = dict(TEST_EXERCISE_DATA)
    copy.update({
        "amount": 255,
        "sets": 5,
        "reps": 5,
        "units": "lbs",
        "description": "Update"
    })
    res = exercise.update(copy)
    assert res is not None
Exemplo n.º 20
0
def add_exercise():
    body = request.get_json()

    # creating list
    exercise_list = []

    if isinstance(body, list):
        for exercise_body in body:
            if 'name' not in exercise_body:
                return 'please specify name', 400
            if 'name_en' not in exercise_body:
                return 'please specify name_en', 400
            if 'type' not in exercise_body:
                return 'please specify type', 400
            exercise = Exercise(name=exercise_body['name'],
                                name_en=exercise_body['name_en'],
                                type=exercise_body['type'])
            exercise_list.append(exercise)

        db.session.add_all(exercise_list)
        db.session.commit()
        return jsonify(
            exercises=[exercise.serialize()
                       for exercise in exercise_list]), 200
    else:
        if 'name' not in body:
            return 'please specify name', 400
        if 'name_en' not in body:
            return 'please specify name_en', 400
        if 'type' not in body:
            return 'please specify type', 400

        exercise = Exercise(name=body['name'],
                            name_en=body['name_en'],
                            type=body['type'])
        db.session.add(exercise)
        db.session.commit()
        return jsonify(exercise.serialize()), 200
Exemplo n.º 21
0
def add_exercise():
    data = request.get_json()

    new_exercise = Exercise(uid=data['user_id'],
                            name=data['name'],
                            category=data['category'],
                            primary_muscle=data['primary_muscle'],
                            secondary_muscle=data['secondary_muscle'],
                            equipment=data['equipment'])

    db.session.add(new_exercise)
    db.session.commit()

    return jsonify({'message': 'Exercise added successfully!', 'status': 200})
Exemplo n.º 22
0
def add_exercise(request, workout):
    if not request.user.is_authenticated():
        return redirect(index)
    elif request.method == 'POST':
        form = ExerciseForm(request.POST)
        name = request.POST['name']
        if form.is_valid():
            e = Exercise(name=name,
                         owner=request.user,
                         workout=Workout.objects.get(id=workout))
            e.save()
            return redirect(index)
        else:
            print(form.errors)
    else:
        form = ExerciseForm()
    return render(request, 'add_exercise.html', {'form': form})
def call_api(func_name):
    try:
        if func_name not in ENDPOINTS:
            message = "No such endpoint " + "'" + func_name + "'"
            return make_response({"message": message}, 404)
        model = Exercise.Exercise()
        # GET requests have no request bodies, so we must get data from the header
        if func_name == "get":
            user_id = request.headers.get("user_id")
            token = request.headers.get("token")
            return CONTROLLER.execute_model_logic(token, user_id, model, "get",
                                                  dict(user_id=user_id))
        request_body = request.get_json()
        print(request_body)
        params = CONTROLLER.deconstruct_request_body(request_body, model,
                                                     func_name)
        params.update({"model": model, "function_name": func_name})
        return CONTROLLER.execute_model_logic(**params)
    except Exception as e:
        return make_response({"message": "Internal Error: " + str(e)}, 500)
Exemplo n.º 24
0
    def post(self):
        # create a new exercise
        data = request.get_json()
        if not data:
            ret = {
                'message': 'Provide data.',
            }
            return jsonify(ret), 422
        exercise = Exercise(name=data['name'], activity=data['activity'])
        db.session.add(exercise)
        db.session.commit()
        db.session.refresh(exercise)
        ret = {
            'message': 'Exercise created successfully.',
            'id': exercise.id,
            'name': data['name']
        }
        return jsonify(ret), 200

        pass
Exemplo n.º 25
0
def create_exercise():

    """ Page for creating a new exercise """

    if not g.user:
        flash("You must be logged in to view this page")
        return redirect("/unauthorized")
    
    else:
        form = ExerciseForm()

        if form.validate_on_submit():

            new_exercise = Exercise(
                name = form.name.data,
                category = form.category.data,
                muscles = form.muscles_used.data,   
                equipment = form.equipment.data,
                description = form.description.data
            )
                
            category = form.category.data
            equipment = form.equipment.data
            muscles = form.muscles_used.data

            category.exercises.append(new_exercise)

            for equip in equipment:
                equip.exercises.append(new_exercise)
            
            for muscle in muscles:
                muscle.exercises.append(new_exercise)    
            
            db.session.commit()
            return redirect(url_for("show_all_exercises"))
    
    return render_template("exercise/new.html", form=form)
Exemplo n.º 26
0
    def create_exercise():
        try:
            all_data = request.get_json()
            name = all_data['name']
            equipment = all_data['equipment']
            target = all_data['target']
            link = all_data['link']

            for value in [name, equipment, target, link]:
                if value is None:
                    abort(400)

            exercise = Exercise(name=name,
                                equipment=equipment,
                                target=target,
                                link=link)

            # could check whether we expect this to fail
            # based on inputs, and abort(500) otherwise
            exercise.insert()
        except Exception:
            abort(400)

        return jsonify({'success': True, 'id': exercise.id})
Exemplo n.º 27
0
    def __init__(self):
        if locale.getdefaultlocale()[0] == "en_US":
            language = "en"
            self.get_en_translation()
        else:
            language = "es"
            self.get_es_translation()

        Gtk.Window.__init__(self, title="IPM P1")
        self.set_default_size(700, 500)

        self.wk_grid = Gtk.Grid()
        self.wk_grid.set_column_homogeneous(True)
        self.wk_grid.set_row_spacing(20)
        self.wk_grid.set_column_spacing(20)

        self.scrolled_window = Gtk.ScrolledWindow()
        self.scrolled_window.set_border_width(10)
        self.add(self.scrolled_window)
        self.scrolled_window.add(self.wk_grid)

        # get collections from database
        self.workouts = define_connection('search_workouts', 'workouts')
        self.render_workouts()

        self.exercises = define_connection('search_exercises', 'exercises')
        self.render_exercises()

        self.all_exercises = []
        # make objects from all exercises in database
        for exercise_db in self.exercises:
            try:
                exercise = Exercise(exercise_db['_id'],
                                    exercise_db['description'],
                                    exercise_db['image'], exercise_db['name'],
                                    exercise_db['video'])
                self.all_exercises.append(exercise)
            except:
                pass

        self.all_workouts = []
        # make objects from all workouts in database
        exercises_not_in_db = []

        for index, workout_db in enumerate(self.workouts):
            workout = Workout(workout_db['_id'], workout_db['name'],
                              workout_db['description'], workout_db['image'])
            # attach proper exercises to the workout
            exercises_of_workout = []
            no = 1
            for workout_ex in workout_db['exercises']:
                found_exercise_in_db = False
                for exercise in self.all_exercises:
                    if found_exercise_in_db is False and workout_ex[
                            0] == exercise.name:
                        id_ = random.randint(1, 10000000)
                        found_exercise_in_db = True
                        ex_of_workout = ExerciseToWorkout(
                            id_, workout.id, exercise.id, workout_ex[1], no)
                        no = no + 1
                        exercises_of_workout.append(ex_of_workout)

                # if the exercise given with workout is not in the exercises colllection in database
                if found_exercise_in_db is False and len(
                        sys.argv) > 1 and sys.argv[1] == "1":
                    id_ = random.randint(1, 10000000)
                    exercise = Exercise(id_, "None", "None", workout_ex[0],
                                        "None")
                    exercises_not_in_db.append("{}".format(
                        str(json.dumps(exercise.__dict__))))
                    self.all_exercises.append(exercise)
                    ex_of_workout = ExerciseToWorkout(workout.id, exercise.id,
                                                      workout_ex[1], no)
                    no = no + 1
                    exercises_of_workout.append(ex_of_workout)

            # add list of exercises to the routine for faster displaying
            workout.set_exercises(exercises_of_workout)
            self.all_workouts.append(workout)

        if len(sys.argv) > 1 and sys.argv[1] == "1":
            result = define_connection("insert_ex",
                                       "{}".format(exercises_not_in_db))
            exercises_json = []
            for ex in exercises_of_workout:
                ex_json = json.dumps(ex.__dict__)
                exercises_json.append(ex_json)
            define_connection("insert_ex_to_wk", "{}".format(exercises_json))
        self.make_workouts_grid()
 def __init__(self):
     self.__db = DbAccess.DbAccess()
     self.__exercise = Exercise.Exercise(self.__db)
Exemplo n.º 29
0
def import_data():
    if Path('db/app.db').exists():
        click.confirm('app.db already exist, want to remove it?', abort=True)
        Path('db/app.db').unlink()

    upgrade()
    user = create_user()

    with open("data/steps.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            steps = Steps(steps=line['steps'])
            steps.date = datetime.fromisoformat(line['datetime'])
            steps.user = user
            db.session.add(steps)
        db.session.commit()

    with open("data/weights.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            weight = Weight(weight=line['weight'])
            weight.date = datetime.fromisoformat(line['datetime'])
            weight.user = user
            db.session.add(weight)
        db.session.commit()

    with open("data/exercises.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            exercise = Exercise(name=line['name'], kcal_per_rep=line['kcal'])
            db.session.add(exercise)
        db.session.commit()

    with open("data/ingredients.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            ingredient = Ingredient(name=line['name'],
                                    kcal_per_100_gram=line['kcal'])
            db.session.add(ingredient)
        db.session.commit()

    with open("data/food_log.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            food_log = FoodLog()
            food_log.user = user
            food_log.ingredient_id = line['ingredient_id']
            food_log.grams = line['grams']
            food_log.timestamp = datetime.fromisoformat(line['datetime'])
            db.session.add(food_log)
        db.session.commit()

    with open("data/exercise_log.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            exercise_log = ExerciseLog()
            exercise_log.user = user
            exercise_log.exercise_id = line['exercise_id']
            exercise_log.amount = line['amount']
            food_log.timestamp = datetime.fromisoformat(line['datetime'])
            db.session.add(exercise_log)
        db.session.commit()
Exemplo n.º 30
0
from factories import MultiplicationEquationsFactory, SubtractionEquationsFactory
from models import Exercise

subtraction_equations_factory = SubtractionEquationsFactory()
exercise = Exercise()
subtraction_equations_factory.appendTo(exercise)

def is_desired_question(question):
  return question.answer > 10

with (open('dataset.csv', mode='wb')) as file:
  for question in exercise.questions:
    line = '{0},{1},{2},{3}\n'.format(
      question.expression.first_term,
      question.expression.second_term,
      question.answer,
      is_desired_question(question)
    )
    file.write(line.encode())