Beispiel #1
0
 def post(self, userid):
     user = User.query.filter_by(userid=userid).first_or_404()
     goal = Goal(user=user)
     update_obj_with(goal, request.json, Goal.write_fields.iterkeys())
     db.session.add(goal)
     db.session.commit()
     return goal
Beispiel #2
0
    def setUp(self):
        self.school = School(name='Minnesota')
        db.session.add(self.school)
        db.session.commit()

        self.tch = Teacher(first_name='Jess',
                           last_name='Christensen',
                           title='K4-2nd Sped',
                           school_id=self.school.id,
                           username='******',
                           password='******')
        db.session.add(self.tch)
        db.session.commit()

        self.stu = Student(first_name='Fake',
                           last_name='Kid',
                           dob=date(2012, 1, 24),
                           grade=1,
                           teacher_id=self.tch.id,
                           dis_area='OHI')
        db.session.add(self.stu)
        db.session.commit()

        self.iep = IEP(student_id=self.stu.id, teacher_id=self.tch.id)

        db.session.add(self.iep)
        db.session.commit()

        self.goal = Goal(iep_id=self.iep.id,
                         goal="Increase CWPM to 23",
                         standard="Read with fluency")

        db.session.add(self.goal)
        db.session.commit()
Beispiel #3
0
def newgoal():
    goals = Goal.objects(people=g.user.id)
    me = User.objects(id=g.user.id).first()

    friends = Set()
    if goals:
        for goal in goals:
            friends.update(goal.people)
            friends.update(goal.completed)

        if friends:
            friends.remove(me)
    else:
        friends.add(User.objects(username='******').first())

    form = GoalForm()
    if form.validate_on_submit():

        me = User.objects(id=g.user.id).first()

        if form.description.data:
            goal = Goal(name=form.name.data,
                        description=form.description.data,
                        end=form.end.data,
                        people=[me])
        else:
            goal = Goal(name=form.name.data, end=form.end.data, people=[me])
        goal.save()

        feeditem = GoalRequest(
            user=me,
            goal=goal,
            message='Your friend invited you to join their goal')

        people = []
        for email in form.people.data:
            friend = User.objects(username=email).first()
            friend.feed.append(feeditem)
            friend.goalrequest.append(goal)
            friend.save()

        flash('Goal added!')
        return redirect(url_for('goals'))
    else:
        print "Nope"

    return render_template('newgoal.html', users=friends, form=form)
    def _start_match(self):  
        print("Starting match ...")

        team1 = Team(name=self.team1_name, members=self.team1_members, score_handler=_team_scored)
        team2 = Team(name=self.team2_name, members=self.team2_members, score_handler=_team_scored)

        dev = MotionSensor(16, pull_up=True, sample_rate=120, queue_len=1)
        goal_a = Goal(name="Goal A",
                    score_device=dev,
                    score_handler=None)

        dev = MotionSensor(19, pull_up=True, sample_rate=120, queue_len=1)
        goal_b = Goal(name="Goal B",
                    score_device=dev,
                    score_handler=None)

        self.devices = [goal_a.input_device, goal_b.input_device]

        games_played = 0
        while games_played < self.games_per_match:
            if games_played % 2 == 0:
                last_game = self._start_new_game(team1, goal_a, team2, goal_b, ui_queue=self.ui_queue)
            else:
                last_game = self._start_new_game(team1, goal_b, team2, goal_a, ui_queue=self.ui_queue)
            
            if self.cancelled:
                self._clean_up()
                print("Match was cancelled")
                return

            # Game has finished check if the next game in the match should be played
            games_played += 1
            if games_played < self.games_per_match:
                if not self._play_next_game(last_game):
                    self._clean_up()
                    if self.match_end_callback:
                        self.match_end_callback()
                    break
            else:
                # Match is over
                if self.match_end_callback:
                    self.match_end_callback()
                print("Match is over hope you had fun!")
Beispiel #5
0
def add_goal():
    username = session['username']
    if request.form["button"] == u"新規作成":
        goal_text = request.form['goal_text']
        if goal_text != "":
            Goal(username=username, content=goal_text).save()
    elif request.form["button"] == u"削除":
        rmgoal = request.form['rmgoal']
        Goal.objects(username=username, content=rmgoal).delete()
    return redirect('/goal')
Beispiel #6
0
def add(week_id):
    """Add a goal task."""
    f = GoalForm()
    # print(f.data)
    if f.validate_on_submit():
        new_goal = Goal()
        f.populate_obj(new_goal)
        new_goal.week_id = week_id
        db.session.add(new_goal)
        db.session.commit()
    # else:
    #     print('validation failed')
    return redirect(url_for('worksheet.worksheet', week_id=week_id))
Beispiel #7
0
def load_goals():

    goals = {
        'travel': '⛱ Для путешествий',
        'study': '🏫 Для учебы',
        'work': '🏢 Для работы',
        'relocate': '🚜 Для переезда',
        'programming': '💻 Для программирования'
    }

    for key, value in goals.items():
        goal = Goal(goal_slug=key, goal_text=value)
        db.session.add(goal)
    db.session.commit()
Beispiel #8
0
    def create_network(self, data):

        goals = data['goals']
        policies = data['policies']

        id_mapping = {}
        links = []

        network = Network()

        for policy in policies:
            p = Policy(id=policy['id'])
            update_node_from_dict(p, policy)
            id_mapping[policy['id']] = p
            network.policies[p.id] = p

            for conn in policy['connections']:
                i = conn['id']
                a = conn['from_id']
                b = conn['to_id']
                w = conn['weight']
                links.append((i, a, b, w))

        for goal in goals:
            g = Goal(id=goal['id'])
            update_node_from_dict(g, goal)
            id_mapping[goal['id']] = g
            network.goals[g.id] = g

            for conn in goal['connections']:
                i = conn['id']
                a = conn['from_id']
                b = conn['to_id']
                w = conn['weight']
                links.append((i, a, b, w))

        for i, a, b, w in links:
            a = id_mapping[a]
            b = id_mapping[b]
            l = Edge(id=i)
            l.init(a, b, w)
            network.edges[l.id] = l

        network.rank()
        self.network = network
Beispiel #9
0
def edit_goal_page(goal_id):
    goal = Goal.query.get(goal_id)
    iep = IEP.query.get(goal.iep.id)

    teacher = Teacher.query.get(goal.iep.teacher_id)
    if goal.iep.is_locked == True:
        flash('IEP is locked. Goals cannot be edited.', 'bad')
        return redirect(f'/teacher/{teacher.id}')

    student = Student.query.get(goal.iep.student_id)
    standards = get_standards_list(student.teacher.school.state_code)
    grade_level = get_grade_level_standard_sets(
        append_zero_convert_to_string(student.grade), standards)
    subject_list = get_subject_list(grade_level)

    g_form = GoalForm()
    d_form = ClassworkDataForm()

    g_form.subject.choices = subject_list

    if g_form.validate_on_submit() and d_form.validate_on_submit():

        Goal.query.filter_by(id=goal.id).delete()
        ClassworkData.query.filter_by(goal_id=goal.id).delete()
        goal = Goal(iep_id=iep.id,
                    goal=g_form.goal.data,
                    subject=g_form.subject.data)
        db.session.add(goal)
        db.session.commit()

        data = ClassworkData(goal_id=goal.id,
                             baseline=d_form.baseline.data,
                             current=d_form.baseline.data,
                             attainment=d_form.attainment.data)
        db.session.add(data)
        db.session.commit()

        flash(f"Goal updated!", "good")
        return redirect(f'/goal/{goal.id}/standard_set')

    return render_template('/student/edit-goal.html',
                           g_form=g_form,
                           d_form=d_form)
Beispiel #10
0
def add_problem(request, patient_id):
    role = UserProfile.objects.get(user=request.user).role
    authenticated = True if (role == 'physician' or role == 'admin') else False
    if 'problem_name' in request.POST:
        problem = Problem(patient=User.objects.get(id=patient_id),
                          problem_name=request.POST['problem_name'],
                          concept_id=request.POST['concept_id'],
                          authenticated=authenticated)
        problem.save()
    elif 'goal' in request.POST:
        goal = Goal(patient=User.objects.get(id=patient_id),
                    goal=request.POST['goal'])
        goal.save()
    elif 'todo' in request.POST:
        # print 'todo'
        # print request.POST
        todo = ToDo(patient=User.objects.get(id=patient_id),
                    todo=request.POST['todo'])
        todo.save()
    return HttpResponse('added')
Beispiel #11
0
    def save(self, current_user, goal=None):
        if goal:
            goal.updated_by = current_user

            for f in ['is_achieved', 'title']:
                if self.cleaned_data.get(f) is not None:
                    setattr(goal, f, self.cleaned_data[f])

            goal.updated_at = datetime.utcnow()
            goal.updated_by = current_user
        else:
            goal = Goal(title=self.cleaned_data.get("title", ""),
                        created_by=current_user,
                        updated_by=current_user,
                        is_achieved=self.cleaned_data.get(
                            "is_achieved", False))

        goal.save()

        return goal
Beispiel #12
0
def add_goal(message):
    text_splits = message.text.split(maxsplit=1)
    goal_main = text_splits[1]
    if entered_correct(goal_main):
        goal_created, goal_deadline, goal_name = parse_goal(goal_main)
        session = Session()
        goal = Goal(chat_id=message.chat.id,
                    name=goal_name,
                    deadline=goal_deadline,
                    created=goal_created,
                    flag_finished=False)
        session.add(goal)
        session.commit()
        text = "List of your goals: \n"
        for goal in session.query(Goal).filter(
                Goal.chat_id == message.chat.id):
            text += goal.name + '\n'
        session.close()
        bot.send_message(message.chat.id, text)
    else:
        bot.send_message(message.chat.id, "Sorry, your data isn't correct")
Beispiel #13
0
def create_goal(iep_id):
    iep = IEP.query.get(iep_id)
    student = Student.query.get(iep.student_id)

    standards = get_standards_list(student.teacher.school.state_code)
    grade_level = get_grade_level_standard_sets(
        append_zero_convert_to_string(student.grade), standards)
    subject_list = get_subject_list(grade_level)

    g_form = GoalForm()
    d_form = ClassworkDataForm()

    g_form.subject.choices = subject_list

    goals = Goal.query.filter_by(iep_id=iep.id).all()

    if g_form.validate_on_submit() and d_form.validate_on_submit():
        goal = Goal(iep_id=iep.id,
                    goal=g_form.goal.data,
                    subject=g_form.subject.data)
        db.session.add(goal)
        db.session.commit()
        data = ClassworkData(goal_id=goal.id,
                             baseline=d_form.baseline.data,
                             current=d_form.baseline.data,
                             attainment=d_form.attainment.data)
        db.session.add(data)
        db.session.commit()
        flash(
            f"Goal created! {goal.goal}. {data.baseline}. {data.attainment}. Select Standard Set",
            "good")
        return redirect(f'/goal/{goal.id}/standard_set')

    return render_template('/student/goal.html',
                           g_form=g_form,
                           d_form=d_form,
                           student=student,
                           iep_id=iep.id,
                           goals=goals)
Beispiel #14
0
def set_new_reading_goal():
    if "user_id" in request.form and "target" in request.form and "year" in request.form:
        user_id = request.form["user_id"],
        target = request.form["target"],
        year = request.form["year"]

        check_achievement(user_id, 'goal')
        # change so current reads from count of HasRead with dates within that year
        # current = db.session.query(func.count(HasRead).label('current')).filter(HasRead.user_id==user_id, HasRead.finish_date.between(year + '-01-01', year + '-12-31')).all()
        # authors = db.session.query(func.count(Book.author).label('count'), Book.author).join(HasRead, HasRead.book_id==Book.book_id).filter(HasRead.user_id==user_id).group_by(Book.author).order_by(desc('count')).limit(3).all()
        existing_goal = db.session.query(Goal).filter(
            Goal.user_id == user_id, Goal.year == year).scalar() is not None

        if not existing_goal:
            db.session.add(
                Goal(target=target, current=0, user_id=user_id, year=year))
            db.session.commit()

        return make_response(
            jsonify({"success:": "Reading goal successfully set"}), 200)
    else:
        return make_response(jsonify({"error:": "Failed to set goal"}), 404)
Beispiel #15
0
iep4 = IEP(student_id=4, teacher_id=1, is_locked=True)
iep5 = IEP(student_id=5, teacher_id=2, is_locked=True)
iep6 = IEP(student_id=6, teacher_id=3, is_locked=True)
iep7 = IEP(student_id=1, teacher_id=1, is_locked=True)

db.session.add(iep1)
db.session.add(iep2)
db.session.add(iep3)
db.session.add(iep4)
db.session.add(iep5)
db.session.add(iep6)
db.session.add(iep7)
db.session.commit()

goal1 = Goal(iep_id=1,
             goal='Pay attention for 10 minutes',
             subject='Time on task')
goal2 = Goal(iep_id=1, goal='Correct display table data', subject='Math')
goal3 = Goal(iep_id=1,
             goal='Categorize words to demonstrate knowledge',
             subject='Reading')
goal4 = Goal(iep_id=7,
             goal='Identify and follow classroom rules',
             subject='Social/Emotional')
goal5 = Goal(iep_id=7, goal='Display knowledge of symmetry.', subject='Math')
goal6 = Goal(iep_id=7, goal='Read multisyllable words', subject='Reading')

# goal4 = Goal(iep_id=2, goal='Read a whole book', standard='Reading')
# goal5 = Goal(iep_id=2, goal='Finish math problems', standard='Math')

# goal6 = Goal(iep_id=3, goal='Finish math problems', standard='Math')
import json
from app import db
from models import Teacher, Goal

"""
"""
with open("teachers.json") as f:
    teachers = json.load(f)

with open("goals.json") as f:
    goals = json.load(f)


for goal, name in goals.items():
    goal_add = Goal(name_slug=goal, name=name[2:], name_symvol=name[0])
    db.session.add(goal_add)


for teacher in teachers:
    name = teacher["name"]
    about = teacher["about"]
    rating = float(teacher["rating"])
    picture = teacher["picture"]
    price = int(teacher["price"])
    free = json.dumps(teacher["free"])
    teacher_add = Teacher(name=name, about=about, rating=rating, picture=picture, price=price, free=free)
    for goal in teacher["goals"]:
        goal_teacher = db.session.query(Goal).filter(Goal.name_slug == goal)
        teacher_add.goals.extend(goal_teacher)
    db.session.add(teacher_add)
Beispiel #17
0
 def post(self):
     form = json.loads(self.request.get('form'))
     prompt = form['prompt']
     pid = form['pid']
     Goal(prompt=prompt, pid=pid).put()
Beispiel #18
0
from models import Teacher, Goal, db, teachers_goals_association

# TODO без этого костыля не работает данный модуль заполнения таблиц со следующей ошибкой, можно сделать лучше?
# No application found. Either work inside a view function or push an application context.
# See http://flask-sqlalchemy.pocoo.org/contexts/.
from app import app
app.app_context().push()

# Удаляем данные из таблиц, чтобы исключить дубли
db.session.query(Goal).delete(synchronize_session=False)
db.session.query(Teacher).delete(synchronize_session=False)
db.session.query(teachers_goals_association).delete(synchronize_session=False)
db.session.commit()

for code, goal in goals.items():
    db.session.add(Goal(code=code, goal=goal))
db.session.commit()

## TODO При использвании many to many отношений с таблицей Goals не понял как применять этот вариант "быстрого" заполнения
# teachers_to_save = []
# for t in teachers:
#     teacher = Teacher(id=t['id'], name=t['name'], about=t['about'], rating=t['rating'], picture=t['picture'],
#                       price=t['price'],
#                       goals=json.dumps(t['goals']),
#                       free=json.dumps(t['free']))
#     teachers_to_save.append(teacher)
# db.session.bulk_save_objects(teachers_to_save)
# db.session.commit()

for t in teachers:
    teacher = Teacher(id=t['id'],
Beispiel #19
0
from data import goals, teachers
from app import db
from models import Teacher, Goal

for i in goals:
    goal = Goal(id=i['id'],
                name=i['goal'],
                description=i['description'],
                icon=i['icon'])
    db.session.add(goal)
db.session.commit()

for i in teachers:
    teacher = Teacher(id=i['id'],
                      name=i['name'],
                      about=i['about'],
                      rating=i['rating'],
                      picture=i['picture'],
                      price=i['price'],
                      free=i['free'])
    for j in i['goals']:
        teacher.goals.append(
            db.session.query(Goal).filter(Goal.name == j).first())
    db.session.add(teacher)

db.session.commit()
Beispiel #20
0
def insert_test_data():
    with open('test_data.json', 'r', encoding='utf8') as _file:
        data = json.load(_file)
    all_objects = []

    week_days = [
        WeekDay(id=_id, day_name=day_name)
        for _id, day_name in [(1, 'Понедельник'), (2, 'Вторник'), (
            3,
            'Среда'), (4,
                       'Четверг'), (5,
                                    'Пятница'), (6,
                                                 'Суббота'), (7,
                                                              'Воскресенье')]
    ]
    all_objects.extend(week_days)

    times = [
        Time(id=id_time[0], time=id_time[1])
        for id_time in [(1, tim(8)), (2, tim(10)), (3, tim(12)), (
            4, tim(14)), (5, tim(16)), (6, tim(18)), (7, tim(20)), (8,
                                                                    tim(22))]
    ]
    all_objects.extend(times)

    goals = \
        [Goal(id=int(goal_id), value=goal_data[0], emoji=goal_data[1]) for goal_id, goal_data in data['goals'].items()]
    all_objects.extend(goals)

    teachers = []
    lessons = []
    lesson_id = 1
    for teacher_dict in data['teachers']:
        teacher_ = Teacher(
            id=int(teacher_dict['id']) + 1,
            name=teacher_dict['name'],
            about=teacher_dict['about'],
            rating=teacher_dict['rating'],
            picture=teacher_dict['picture'],
            price=teacher_dict['price'],
            goals=list(
                filter(
                    lambda x: x.id in [int(i) for i in teacher_dict['goals']],
                    goals)))
        teachers.append(teacher_)
        for day_id, time_status in teacher_dict['free'].items():
            for _time, status in time_status.items():
                _time = tim(int(_time.split(':')[0]))
                _time_id = list(filter(lambda x: x.time == _time, times))[0].id
                lesson = Lesson(id=lesson_id,
                                teacher_id=teacher_.id,
                                day_name_id=int(day_id),
                                time_id=_time_id,
                                status=status)
                lessons.append(lesson)
                lesson_id += 1

    all_objects.extend(teachers)
    all_objects.extend(lessons)

    db.session.add_all(all_objects)
    db.session.commit()