예제 #1
0
파일: views.py 프로젝트: Mac-Genius/auacm
def unregister_for_competition(cid):
    """ Called when a user wants to unregister for a competition.

    All the user has to do is submit a post to this url with no form data.
    From their logged-in status, we'll go ahead and remove them from the
    competiton.

    Similar to the <code>/register</code> endpoint, an admin can post a list of
    users to unregister from the competition.
    """
    if session.query(Competition).filter(Competition.cid == cid).first() \
            is None:
        return serve_error('Competition does not exist', response_code=404)

    if current_user.admin == 1 and 'users' in request.data:
        try:
            registrants = loads(request.data['users'])
        except ValueError:
            return serve_error('JSON data for \'users\' not properly formatted',
                    response_code=400)
    else:
        registrants = [current_user.username]

    for user in registrants:
        (session.query(CompUser)
                .filter(CompUser.username == user, CompUser.cid == cid)
                .delete())
    session.flush()
    session.commit()

    return serve_response({})
예제 #2
0
파일: views.py 프로젝트: Mac-Genius/auacm
def get_competitions():
    ongoing = list()
    past = list()
    upcoming = list()
    current_time = int(time())

    registered_rows = session.query(CompUser).filter(
            CompUser.username == current_user.username).all()
    registered = set()
    for row in registered_rows:
        registered.add(row.cid)

    for competition in session.query(Competition).all():
        if competition.stop < current_time:
            past.append(competition.to_dict(
                user_registered=competition.cid in registered))
        elif competition.start < current_time:
            ongoing.append(competition.to_dict(
                user_registered=competition.cid in registered))
        else:
            upcoming.append(competition.to_dict(
                user_registered=competition.cid in registered))
    return serve_response({
        'ongoing': ongoing,
        'past': past,
        'upcoming': upcoming
    })
예제 #3
0
  def test_case_1(self):
    ''' 재귀호출 - 메뉴목록 '''
    
    src = aliased(MN_MENU_MST, name="SRC")
    with_rec_menus = session.query(src.menu_id, src.menu_name, src.pmenu_id, src.menu_type, src.sort_order) \
      .filter(src.pmenu_id==None) \
      .cte(recursive=True, name="REC_MENUS")

    cte = aliased(with_rec_menus, name="CTE")

    rec = with_rec_menus.union_all(
      session.query(src.menu_id, src.menu_name, src.pmenu_id, src.menu_type, src.sort_order) \
        .join(cte, cte.c.menu_id == src.pmenu_id)
    )

    t2 = aliased(rec, name="TGT")
    column_menu_sort = func.row_number().over(partition_by="menu_type", order_by=asc("sort_order")).label('rn')
    column_min_order = func.min("sort_order").label("asdf")

    query = session.query(
        t2,
        column_menu_sort,
        column_min_order
      ) \
      .select_from(t2) \
      .group_by("menu_type", "menu_id") \
      .order_by(asc("asdf"))
예제 #4
0
파일: views.py 프로젝트: ejw0013/auacm
def put_competition_teams(cid):
    """ Update the teams for a competition

    If a user is an admin, they can update the competition's users, doing a PUT.
    This will take the JSON data in the 'teams' part of the request form and
    store it to the database. Any teams or users not included in the JSON data
    will not be a part of the competition and will have to re-register; however
    it should not be used for the solely purpose of de-registering participants.
    """
    try:
        teams = loads(request.form['teams'])
    except KeyError as err:
        return serve_error('You must include the parameter \'teams\'.',
                response_code=400)
    except ValueError:
        return serve_error('JSON data for \'teams\' not properly formatted',
                response_code=400)

    # Delete all of the old CompUser rows for this competition
    session.query(CompUser).filter(CompUser.cid == cid).delete()

    for team in teams:
        for user in teams[team]:
            session.add(CompUser(
                cid=cid,
                username=user,
                team=team
            ))

    session.flush()
    session.commit()

    return serve_response({})
예제 #5
0
def getCompetitionData(cid):
    competition = session.query(Competition).filter(Competition.cid==cid).first()
    if competition is None:
        return serve_error('competition not found', response_code=404)
    comp_users = session.query(CompUser).filter(CompUser.cid==cid).all()
    comp_problems = [p.pid for p in session.query(CompProblem).filter(CompProblem.cid==cid).all()]
    comp_problems.sort()
    
    submissions = session.query(Submission)\
            .filter(Submission.submit_time>competition.start,\
                    Submission.submit_time<competition.stop)\
            .order_by(asc(Submission.submit_time))\
            .all()
    
    scoreboard = list()
    
    team_users = dict()
    for user in comp_users:
        if not user.team in team_users:
            team_users[user.team] = list()
        team_users[user.team].append(user.username)
    
    for team in team_users.keys():
        team_problems = dict()
        for problem in comp_problems:
            correct = 0
            incorrect = 0
            pointless = 0
            for s in submissions:
                if not s.pid == problem or not s.username in team_users[team]:
                    continue
                elif correct > 0:
                    pointless += 1
                elif s.result == 'good':
                    correct = s.submit_time - competition.start
                else:
                    incorrect += 1
            problem_time = incorrect*20+correct/60
            submit_count = 0
            if (correct > 0):
                submit_count = 1
            submit_count += incorrect+pointless
            team_problems[problem] = {
                'problemTime' : problem_time,
                'submitCount' : submit_count,
                'status' : 'correct' if correct > 0 else 'unattempted' if submit_count == 0 else 'incorrect'
            }
        team_row = dict()
        team_row['name'] = team
        team_row['users'] = team_users[team]
        team_row['problemData'] = team_problems
        scoreboard.append(team_row)
        
    return serve_response({
        'competition' : create_competition_object(competition),
        'compProblems' : comp_problems,
        'teams' : scoreboard
    })
    
예제 #6
0
def getCompetitionData(cid):
    competition = session.query(Competition).filter(Competition.cid == cid).first()
    if competition is None:
        return serve_error("competition not found", response_code=404)
    comp_users = session.query(CompUser).filter(CompUser.cid == cid).all()
    comp_problems = [p.pid for p in session.query(CompProblem).filter(CompProblem.cid == cid).all()]
    comp_problems.sort()

    submissions = (
        session.query(Submission)
        .filter(Submission.submit_time > competition.start, Submission.submit_time < competition.stop)
        .order_by(asc(Submission.submit_time))
        .all()
    )

    scoreboard = list()

    team_users = dict()
    for user in comp_users:
        if not user.team in team_users:
            team_users[user.team] = list()
        team_users[user.team].append(user.username)

    for team in team_users.keys():
        team_problems = dict()
        for problem in comp_problems:
            correct = 0
            incorrect = 0
            pointless = 0
            for s in submissions:
                if not s.pid == problem or not s.username in team_users[team]:
                    continue
                elif correct > 0:
                    pointless += 1
                elif s.result == "good":
                    correct = s.submit_time - competition.start
                else:
                    incorrect += 1
            problem_time = incorrect * 20 + correct / 60
            submit_count = 0
            if correct > 0:
                submit_count = 1
            submit_count += incorrect + pointless
            team_problems[problem] = {
                "problemTime": problem_time,
                "submitCount": submit_count,
                "status": "correct" if correct > 0 else "unattempted" if submit_count == 0 else "incorrect",
            }
        team_row = dict()
        team_row["name"] = team
        team_row["users"] = team_users[team]
        team_row["problemData"] = team_problems
        scoreboard.append(team_row)

    return serve_response(
        {"competition": create_competition_object(competition), "compProblems": comp_problems, "teams": scoreboard}
    )
def delete_category(category_id):
    try:
        category = session.query(Category).filter_by(id=category_id).one()
    except:
        return error_message(404, "Cannot delete: Category not found.")
    session.query(Course).filter_by(category_id=category_id).delete()
    session.delete(category)
    session.commit()
    return data_message(200, None,
                        "Category and sub-courses was successfully deleted.")
예제 #8
0
    def test_bucketlist_access_control(self):
        """Test access to bucketlists and items only by creator."""
        bucketlist = session.query(BucketList).first()
        bucketlistitem = session.query(BucketListItems).first()
        url = '/bucketlists/{0}/items/{1}/'.format(bucketlist.list_id,
                                                   bucketlistitem.item_id)

        response = self.client.put(url,
                                   data=json.dumps({'list_type': fake.name()}),
                                   headers={'token': self.token})
        self.assertEqual(response.status_code, 404)
예제 #9
0
def get_courses_by_category_id(category_id):
    try:
        category = session.query(Category).filter_by(id=category_id).one()
    except:
        return error_message(404, "Category not found.")
    courses = session.query(Course).filter_by(category_id=category_id).all()
    return data_message(
        200, {
            "Category": category.serialize,
            "Courses": [c.serialize for c in courses]
        }, "Successfully returned all courses by given category.")
    def test_bucketlist_access_control(self):
        """Test access to bucketlists and items only by creator."""
        bucketlist = session.query(BucketList).first()
        bucketlistitem = session.query(BucketListItems).first()
        url = '/bucketlists/{0}/items/{1}/'.format(bucketlist.list_id,
                                                   bucketlistitem.item_id)

        response = self.client.put(url,
                                   data=json.dumps({
                                       'list_type': fake.name()}),
                                   headers={'token': self.token})
        self.assertEqual(response.status_code, 404)
예제 #11
0
파일: views.py 프로젝트: Mac-Genius/auacm
def register_for_competition(cid):
    """ Called when a user wants to register for a competition.

    All the user has to do is submit a post to this url with no form data.
    From their logged-in status, we'll go ahead and add them to the competiton
    as an individual (team name is default their display name). A 400 error will
    be returned if the user is already registered for the competition.

    If the user that is submitting this is an admin, they can optionally
    supply a json array of usernames to register for the competition. Specifying
    this will not register the admin, but it will register all users that are
    listed. A 400 error will be returned if any of the users are already
    registered for the competition.
    """
    if session.query(Competition).filter(Competition.cid == cid).first() \
            is None:
        return serve_error('Competition does not exist', response_code=404)

    if current_user.admin == 1 and 'users' in request.data:
        try:
            registrants = loads(request.data['users'])
        except ValueError:
            return serve_error('JSON data for \'users\' not properly formatted',
                    response_code=400)
    else:
        registrants = [current_user.username]

    for user in registrants:
        if session.query(CompUser).filter(CompUser.cid == cid,
            CompUser.username == user).first() is not None:
            return serve_error('User ' + user + ' already registered for '
                    'competition', response_code=400)

    for username in registrants:
        user = session.query(User).filter(User.username == user).first()
        session.add(CompUser(
            cid=cid,
            username=user.username,
            team=user.display
        ))
        socketio.emit('new_user', {
            'cid': cid,
            'user': {
                'display': user.display,
                'username': user.username
            }
        },
        namespace='/register')
    session.flush()
    session.commit()

    return serve_response({})
예제 #12
0
파일: views.py 프로젝트: Mac-Genius/auacm
def update_competition_data(cid):
    """ Adds problems to a competition

    Doing a POST request adds that problem to the competition whereas
    a PUT request will remove all problems that were previously associated
    with that competition and add all of the ones in the form body.

    TODO: form validation to make sure that no duplicates are added.
    """
    if current_user.admin == 0:
        # admins only
        return serve_error('Only admins can modify competitions', 401)

    data = request.form

    try:
        competition = session.query(Competition).filter(Competition.cid == cid)\
                .first()

        competition.name = data['name']
        competition.start=int(data['start_time'])
        competition.stop=(int(data['start_time']) + int(data['length']))
        competition.closed = 0 if bool(data['closed']) else 0
        competition.commit_to_session()

        # If the client sends a PUT request, we need to delete all of the old
        # problems associated with this competition
        session.query(CompProblem).filter(CompProblem.cid == cid).delete()

        comp_problems = loads(data['problems'])
    except KeyError as err:
        return serve_error('You must specify name, startTime, length, and'
                ' and problem attributes. ' + err[0] + ' not found.',
                response_code=400)
    except ValueError:
        return serve_error('JSON data for \'problems\' not properly formatted',
                response_code=400)

    for problem in comp_problems:
        session.add(CompProblem(
            label=problem['label'],
            cid=competition.cid,
            pid=problem['pid']
        ))

    session.flush()
    session.commit()
    return serve_response(competition.to_dict())
예제 #13
0
def get_category():
	"""
	Args:
		None
	Return:
		List
	"""
	try:
		categories = session.query(Category).all()
		datas = []
		for category in categories:
			data = {}
			data['category_id'] = category.category_id
			data['category'] = category.category
			datas.append(data)
		logger.info({
				'action': 'controller.py',
				'datas': datas,
				'datas type': type(datas),
				'datas[0]': datas[0],
				'datas[0] type': type(datas[0])
			})
	finally:
		session.close()
	return datas
예제 #14
0
def get_all_latlng_datas(products_id):
	"""
	Args:
		products_id (int): 作品id
	Return:
		List
	"""
	try:
		rrl_datas = session.query(Real_life_location).filter(products_id==products_id).all()
		real_life_location_datas = []
		for rrl_data in rrl_datas:
			data = {}
			data['name'] = rrl_data.name
			data['scene'] = rrl_data.scene
			data['overview'] = rrl_data.overview
			data['image_path'] = rrl_data.image_path
			data['latitude'] = float(rrl_data.latitude)
			data['longitude'] = float(rrl_data.longitude)
			real_life_location_datas.append(data)
		logger.info({
				'action': 'controller.py',
				'real_life_location_datas': real_life_location_datas,
				'real_life_location_datas type': type(real_life_location_datas)
			})
	finally:
		session.close()
	return real_life_location_datas
예제 #15
0
def get_latlng_data(real_life_location_id):
	"""
	Args:
		real_life_location_id (int): 聖地id
	Return:
		List
	"""
	try:
		datas = session.query(Real_life_location).\
		filter(Real_life_location.real_life_location_id==real_life_location_id).all()
		real_life_location_data = {}
		real_life_location_data['name'] = datas[0].name
		real_life_location_data['scene'] = datas[0].scene
		real_life_location_data['overview'] = datas[0].overview
		real_life_location_data['image_path'] = datas[0].image_path
		real_life_location_data['latitude'] = float(datas[0].latitude)
		real_life_location_data['longitude'] = float(datas[0].longitude)
		logger.info({
				'action': 'controller.py',
				'real_life_location_data': real_life_location_data,
				'real_life_location_data type': type(real_life_location_data)
			})
		real_life_location_datas = []
		real_life_location_datas.append(real_life_location_data)
	finally:
		session.close()
	return real_life_location_datas
예제 #16
0
    def save_new_user(data):
        user = session.query(User).filter_by(username=data['username']).first()
        if not user:
            new_user = User(
                username=data['username'],
                password=data['password'],
                registered_on=datetime.datetime.utcnow()
            )

            UserService.save_changes(new_user)

            response_object = {
                'status': 'success',
                'message': 'Successfully registered.'
            }

            return response_object, 201

        else:
            response_object = {
                'status': 'fail',
                'message': 'User already exists. Please Log in.',
            }

            return response_object, 409
    def test_unauthorized_methods(self):
        """Test unsuccessful bucketlist retrieval and
           creation for unauthorized users.
        """
        # Test that a user has to have a token to access bucketlists
        response = self.client.get(url_for('bucketlists'))
        self.assertEqual(response.status_code, 401)

        response = self.client.post(url_for('bucketlists'))
        self.assertEqual(response.status_code, 401)

        # Test that a user can only access/edit bucketlists that they create.
        bucketlist = session.query(BucketList).first()
        url2 = '/bucketlists/{}/'.format(bucketlist.list_id)
        response = self.client.get(url2,
                                   headers={'token': self.token})
        self.assertIn('Bucketlist {} not found'.format(bucketlist.list_id),
                      response.data)

        response2 = self.client.put(url2, data=json.dumps(
            {'list_name': fake.name()}), headers={'token': self.token})
        self.assertIn('Bucketlist {} has not been found'
                      .format(bucketlist.list_id), response2.data)

        response3 = self.client.delete(url2, headers={'token': self.token})
        self.assertIn('Bucketlist {} has not been found'
                      .format(bucketlist.list_id), response3.data)
예제 #18
0
def main():
    # grab the last timestamp file, get the timestamp
    # ask RRSMS_URL for some fresh data
    username='******'
    pwd='pickabetterpassword'
    client_id='1'
    resp = requests.get("{}/get_update".format(RRSMS_URL), timeout=60, params={"client_id":client_id}, auth=HTTPBasicAuth(username, pwd))
    # unpickle the data 
    data = resp.json()
    timefile_n = ".timestamps/client{}timestamp".format(client_id)
    new_file = not os.path.isfile(timefile_n)
    mode = 'w+' if new_file else 'r+'
    timefile = open(timefile_n, mode)
    max_time = 0
    if new_file:
        last_time = 0
    else:
        last_time = float(timefile.read())
    for update in data:
        (rrid, field, newval, timestamp) =  (update[0], update[1], update[2], update[3])
        if timestamp > max_time:
            max_time = timestamp
        if timestamp < last_time: 
            continue
        patient = session.query(Patient).filter(Patient.id == rrid).first()
        update_patient(patient, field, newval)
        
    session.commit()
    timefile.seek(0)
    timefile.write(str(max_time))
    timefile.truncate()
    timefile.close()
    
    requests.get("{}/update_ack".format(RRSMS_URL), timeout=60, params={"client_id":client_id, "timestamp":str(max_time)},
                 auth=HTTPBasicAuth(username, pwd))
예제 #19
0
파일: views.py 프로젝트: joverbey/WebCode
def create_submission():
    try:
        project = (session.query(Project).filter(
            Project.project_id == int(request.form['project_id'])
            and Project.username == current_user.username).first())

        project.body = request.form['body']
        submission = Submission(username=current_user.username,
                                submit_time=int(time.time()),
                                type=project.type,
                                project_id=int(request.form['project_id']),
                                run=int(request.form['run']))
    except KeyError:
        return serve_error('Form data missing.')

    submission.commit_to_session()
    project.commit_to_session()

    Event.log(current_user.username, 'execute', submission.job)

    directory = directory_for_submission(submission.job)
    os.mkdir(directory)
    file_name = 'submit' + FILE_EXTENSIONS_FROM_TYPE[submission.type]
    source_file = open(os.path.join(directory, file_name), 'w')
    source_file.write(project.body)
    source_file.close()

    runner = Runner(submission, file_name)
    runner.run_queued()

    return serve_response({'job': submission.job})
예제 #20
0
    def load(x, y, create=False):
        loaded_chunk = session.query(models.Chunk).filter_by(x=x, y=y).first()

        if loaded_chunk is None:
            if create:
                chunk = Chunk(x, y)
                chunk.build_blocks()
                chunk.save()
            else:
                return None
        else:
            chunk = Chunk.load_from_db_obj(loaded_chunk)

        if not os.path.isfile(chunk.img_file):
            chunk.build_img()

        bg_img = load_image(chunk.img_file)
        chunk.sprite = Sprite(bg_img,
                              0,
                              0,
                              batch=chunk.draw_batch,
                              group=chunk.background)

        chunk.set_walls()
        chunk.add_npcs(5)

        return chunk
예제 #21
0
파일: views.py 프로젝트: joverbey/WebCode
def get_submissions():
    submissions = session.query(Submission).filter(
        Submission.username == current_user.username).all()
    subs = list()
    for s in submissions:
        subs.append(s.to_dict())
    return serve_response({'submissions': subs})
예제 #22
0
파일: views.py 프로젝트: ejw0013/auacm
def get_submits():
    """
    Return one or more submissions. Can be filtered by user or id, and limited
    to a specific number. Parameters are given in the query string of the
    request. Note that if ID is supplied, the other two parameters will be
    ignored.

    :param username: The user to collect submits for (leaving blank will return
                     submissions from all users).
    :param limit:    The number of submits to pull, max 100
    """

    # Default and max limit is 100
    limit = min(int(request.args.get('limit') or 100), 100)

    submits = (session.query(models.Submission)
               .order_by(models.Submission.submit_time.desc()))

    # Filter by user if provided
    if request.args.get('username'):
        submits = submits.filter(
                models.Submission.username == request.args.get('username'))

    result = submits.limit(limit).all()

    if not result:
        return serve_error('No submissions found', 401)

    return serve_response([s.to_dict() for s in result])
예제 #23
0
파일: views.py 프로젝트: joverbey/WebCode
def create_submission():
    try:
        project = (session.query(Project).filter(
                    Project.project_id == int(request.form['project_id']) and
                    Project.username == current_user.username).first())

        project.body = request.form['body']
        submission = Submission(
            username=current_user.username,
            submit_time=int(time.time()),
            type=project.type,
            project_id=int(request.form['project_id']),
            run=int(request.form['run'])
        )
    except KeyError:
        return serve_error('Form data missing.')

    submission.commit_to_session()
    project.commit_to_session()

    Event.log(current_user.username, 'execute', submission.job)

    directory = directory_for_submission(submission.job)
    os.mkdir(directory)
    file_name = 'submit' + FILE_EXTENSIONS_FROM_TYPE[submission.type]
    source_file = open(os.path.join(directory, file_name), 'w')
    source_file.write(project.body)
    source_file.close()

    runner = Runner(submission, file_name)
    runner.run_queued()

    return serve_response({
        'job': submission.job
    })
예제 #24
0
def get_course_by_id(category_id, course_id):
    try:
        course = session.query(Course).filter_by(
            id=course_id, category_id=category_id).one()
    except:
        return error_message(404, "Course not found.")
    return data_message(200, {"Course": course.serialize},
                        "Successfully returned the selected course.")
예제 #25
0
파일: views.py 프로젝트: joverbey/WebCode
def log_event(conn, data, username):
    user = session.query(User).filter(User.username == username).first()
    if user is not None:  # Ensure that the user exists to prevent crashes
        user.font_size = int(data['fontSize'])
        user.theme = data['theme']
        user.commit_to_session()
    else:
        print('Attempting to log event where username is None')
예제 #26
0
파일: views.py 프로젝트: ejw0013/auacm
def get_submit_for_id(job_id):
    """Return the submission with this id"""
    submit = (session.query(models.Submission)
              .filter(models.Submission.job == job_id).first())
    if not submit:
        return serve_error('Submission with id ' + str(job_id) +
                           ' not found', 401)
    return serve_response(submit.to_dict())
예제 #27
0
파일: models.py 프로젝트: AuburnACM/auacm
 def get_problem(self):
     '''Find the problem that this submit is associated with.'''
     if self._problem is None:
         self._problem = (
             session.query(Problem)
                 .filter(Problem.pid == self.pid)
                 .first())
     return self._problem
예제 #28
0
def verify_token(token):
    user_id = User.verify_auth_token(token)
    if user_id:
        user = session.query(User).filter_by(id=user_id).one()
    else:
        return False
    g.user = user
    return True
예제 #29
0
def delete_course(category_id, course_id):
    try:
        course = session.query(Course).filter_by(
            id=course_id, category_id=category_id).one()
    except:
        return error_message(404, "Cannot delete: Course not found.")
    session.delete(course)
    session.commit()
    return data_message(200, None, "Course was successfully deleted.")
예제 #30
0
파일: views.py 프로젝트: joverbey/WebCode
def get_users():
    users = session.query(User).all()
    ret = list()
    for user in users:
        ret.append({
            'username': user.username,
            'displayName': user.display
        })
    return serve_response(ret)
예제 #31
0
파일: views.py 프로젝트: joverbey/WebCode
def get_submission(job):
    submission = session.query(Submission).filter(
        Submission.username == current_user.username
        and Submission.job == job).first()
    directory = directory_for_submission(job)
    file_name = 'submit' + FILE_EXTENSIONS_FROM_TYPE[submission.type]
    source_file = open(os.path.join(directory, file_name))
    body = source_file.read()
    return serve_response({'body': body})
예제 #32
0
파일: views.py 프로젝트: joverbey/WebCode
def get_submission(job):
    submission = session.query(Submission).filter(Submission.username == current_user.username and
                                                  Submission.job == job).first()
    directory = directory_for_submission(job)
    file_name = 'submit' + FILE_EXTENSIONS_FROM_TYPE[submission.type]
    source_file = open(os.path.join(directory, file_name))
    body = source_file.read()
    return serve_response({
        'body': body
    })
예제 #33
0
  def resolve_przwin_list_page(root, info, pagination=None):
    page = int(pagination.get("page"))
    rows_per_page = int(pagination.get("rows_per_page"))

    rn_start = ( page ) * rows_per_page
    rn_end = rn_start + rows_per_page

    Model = LottoPrzwinType._meta.model

    t1 = session.query(Model) \
      .add_column(func.row_number().over(order_by=desc(Model.drwt_no)).label('rn')) \
      .cte(recursive=False, name="SRC_OBJ")

    query = session.query(Model) \
      .select_entity_from(t1) \
      .filter(t1.c.rn > rn_start) \
      .filter(t1.c.rn <= rn_end)
    
    return query.all()
예제 #34
0
파일: views.py 프로젝트: joverbey/WebCode
def edit_project(project_id):
    project = session.query(Project).filter(Project.project_id == project_id).first()
    if 'title' in request.form:
        project.title = request.form['title']
    if 'type' in request.form:
        project.type = request.form['type']
    if 'delete' in request.form:
        project.hide = int(request.form['delete'])

    project.commit_to_session()
    return serve_response(project.to_dict())
예제 #35
0
파일: views.py 프로젝트: joverbey/WebCode
def get_projects():
    projects = session.query(Project).filter(Project.username == current_user.username).all()
    ret = dict()
    for project in projects:
        if project.hide > 0:
            continue
        ret[repr(project.project_id)] = project.to_dict()
    return serve_response({
        'selected': repr(projects[0].project_id) if len(projects) > 0 else -1,
        'projects': ret
    })
예제 #36
0
def get_all_data(products_id):
	"""
	Args:
		products_id (int): 作品id
	Return:
		dict
	"""
	try:
		products_datas = session.query(Products).filter(Products.products_id==products_id).all()
		main_data = {}
		for products_data in products_datas:
			main_data['p_id'] = products_data.products_id
			main_data['p_title'] = products_data.title
			main_data['p_director'] = products_data.director
			main_data['p_overview'] = products_data.overview
			main_data['p_image_path'] = products_data.image_path
		# logger.info({
		# 		'action': 'controller.py',
		# 		'main_data': main_data
		# 	})
		rrl_datas = session.query(Real_life_location).filter(Real_life_location.products_id==products_id).all()
		real_life_location_datas = []
		for rrl_data in rrl_datas:
			data = {}
			data['r_name'] = rrl_data.name
			data['r_scene'] = rrl_data.scene
			data['r_overview'] = rrl_data.overview
			data['r_image_path'] = rrl_data.image_path
			data['r_latitude'] = rrl_data.latitude
			data['r_longitude'] = rrl_data.longitude
			data['r_id'] = rrl_data.real_life_location_id
			real_life_location_datas.append(data)
		# logger.info({
		# 		'action': 'controller.py',
		# 		'real_life_location_datas': real_life_location_datas
		# 	})
		main_data['real_life_location_data'] = real_life_location_datas
	finally:
		session.close()

	return main_data
예제 #37
0
파일: views.py 프로젝트: joverbey/WebCode
def edit_project(project_id):
    project = session.query(Project).filter(
        Project.project_id == project_id).first()
    if 'title' in request.form:
        project.title = request.form['title']
    if 'type' in request.form:
        project.type = request.form['type']
    if 'delete' in request.form:
        project.hide = int(request.form['delete'])

    project.commit_to_session()
    return serve_response(project.to_dict())
예제 #38
0
def gconnect():
    code = request.data
    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        return error_message(401, "Failed to upgrade the authorization code.")

    # Check if the access token is valid
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    # If there was an error in the access token info, abort
    if result.get('error') is not None:
        return error_message(500, result.get('error'))

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        return error_message(401,
                             "Token's user ID doesn't match give user ID.")

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        return error_message(401, "Token's client ID does not match app's.")

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    name = data["name"]
    picture = data["picture"]
    email = data["email"]

    user = session.query(User).filter_by(email=email).first()
    if not user:
        user = User(username=name, picture=picture, email=email)
        session.add(user)
        session.commit()

    # Make token
    token = user.generate_auth_token(600)

    return data_message(200, {'token': token.decode('ascii')},
                        "Successfully generated token."), 200
예제 #39
0
def getCompetitions():
    ongoing = list()
    past = list()
    upcoming = list()
    current_time = int(time())
    for competition in session.query(Competition).all():
        if competition.stop < current_time:
            past.append(create_competition_object(competition))
        elif competition.start < current_time:
            ongoing.append(create_competition_object(competition))
        else:
            upcoming.append(create_competition_object(competition))
    return serve_response({"ongoing": ongoing, "past": past, "upcoming": upcoming})
예제 #40
0
def create_blog_object(post):
    user = session.query(User).filter(User.username==post.username).first()
    return {
        'title' : post.title,
        'subtitle' : post.subtitle,
        'postTime' : post.post_time * 1000,
        'body' : post.body,
        'id' : post.id,
        'author' : {
            'username' : user.username,
            'display' : user.display
        }
    }
예제 #41
0
파일: views.py 프로젝트: ejw0013/auacm
def submit():
    """
    Retrieves the submission information from the request, creates a submission,
    then begins the submissions execution. The response is simply a submission
    identifier of the new submission.

    :return: serves a 200 request code and an empty object if it is a good
            request, 403 if the filetype is unsupproted, 400 if the required
            fields are missing.
    """

    uploaded_file = request.files['file']
    if not uploaded_file:
        return serve_error('file must be uploaded', response_code=400)
    if not judge.allowed_filetype(uploaded_file.filename):
        return serve_error('filename not allowed', response_code=403)
    if not request.form['pid']:
        return serve_error('the field \'pid\' must be specified',
            response_code=400)

    # Obtain the time limit for the problem
    time_limit = session.query(ProblemData).\
            options(load_only("pid", "time_limit")).\
            filter(ProblemData.pid==request.form['pid']).\
            first().time_limit


    ext = uploaded_file.filename.split('.')[-1].lower()
    if 'python' in request.form:
        ext = request.form['python']

    attempt = models.Submission(
        username=current_user.username,
        pid=request.form['pid'],
        submit_time=int(time.time()),
        auto_id=0,
        file_type=ext,
        result='start')

    attempt.commit_to_session()

    directory = directory_for_submission(attempt)
    os.mkdir(directory)
    uploaded_file.save(os.path.join(directory, uploaded_file.filename))

    judge.Judge(attempt, uploaded_file, time_limit).run_threaded()

    return serve_response({
        'submissionId': attempt.job
    })
예제 #42
0
파일: views.py 프로젝트: joverbey/WebCode
def on_save(conn, data, username):
    """Save the project"""
    project = (session.query(Project)
               .filter(Project.project_id == data['project_id'] and
                       Project.username == data['username']).first())
    project.body = data['body']
    project.cursor_x = data['cursor_x']
    project.cursor_y = data['cursor_y']
    project.last_edited = int(time.time())
    project.commit_to_session()
    SocketHandler.send(conn, 'saved', {
        'project_id': str(project.project_id),
        'save_time': project.last_edited
    })
예제 #43
0
    def resolve_schd_status_nm(root, info):
        T1 = aliased(MT_CODE_TYPE_MST, name="T1")
        T2 = aliased(MT_CODE_MST, name="T2")

        query = session.query(T2.code_nm).select_from(T1).join(
            T2, T1.code_type_id == T2.code_type_id).filter(
                T1.code_type_id == "schd_status", T1.use_yn == "Y",
                T2.code_id == str(root.schd_status), T2.use_yn == "Y").first()

        code_name = None
        if query is not None:
            code_name = query[0]

        return code_name
예제 #44
0
파일: views.py 프로젝트: joverbey/WebCode
def on_save(conn, data, username):
    """Save the project"""
    project = (session.query(Project).filter(
        Project.project_id == data['project_id']
        and Project.username == data['username']).first())
    project.body = data['body']
    project.cursor_x = data['cursor_x']
    project.cursor_y = data['cursor_y']
    project.last_edited = int(time.time())
    project.commit_to_session()
    SocketHandler.send(conn, 'saved', {
        'project_id': str(project.project_id),
        'save_time': project.last_edited
    })
예제 #45
0
파일: views.py 프로젝트: joverbey/WebCode
def get_projects():
    projects = session.query(Project).filter(
        Project.username == current_user.username).all()
    ret = dict()
    for project in projects:
        if project.hide > 0:
            continue
        ret[repr(project.project_id)] = project.to_dict()
    return serve_response({
        'selected':
        repr(projects[0].project_id) if len(projects) > 0 else -1,
        'projects':
        ret
    })
def edit_category(category_id):
    try:
        category = session.query(Category).filter_by(id=category_id).one()
    except:
        return error_message(404, "Cannot update: Category not found.")
    name = request.form.get('name')
    if name:
        category.name = name
        session.add(category)
        session.commit()
    else:
        return error_message(400, "Course name is required.")
    return data_message(200, {"Category": category.serialize},
                        "Successfully updated the category.")
예제 #47
0
def get_problems():
    problems = list()
    solved = session.query(Submission).\
            filter(Submission.username==current_user.username).\
            filter(Submission.result=="good").\
            all()
    solved_set = set()
    for solve in solved:
        solved_set.add(solve.pid)
    
    for problem in session.query(Base.classes.problems).all():
        problems.append({
            'pid': problem.pid,
            'name': problem.name,
            'appeared': problem.appeared,
            'difficulty': problem.difficulty,
            'compRelease': problem.comp_release,
            'added': problem.added,
            'timeLimit': problem.time_limit,
            'solved': problem.pid in solved_set,
            'url': url_for_problem(problem)
        })
    return serve_response(problems)
예제 #48
0
  def test_case_2(self):
    ''' 재귀호출 - 2 '''

    hierarchy = session.query(
      MN_MENU_MST.menu_id,
      MN_MENU_MST.menu_name,
      MN_MENU_MST.menu_type,
      MN_MENU_MST.sort_order,
      literal(1).label('level')
      ) \
      .filter(MN_MENU_MST.pmenu_id==None) \
      .filter(MN_MENU_MST.use_yn=="Y") \
      .cte(recursive=True, name="REC_MENUS")
    
    child = aliased(MN_MENU_MST, name="c")
    parent = aliased(hierarchy, name="p")

    hierarchy = hierarchy.union_all(
      session.query(
        child.menu_id,
        child.menu_name,
        child.menu_type,
        child.sort_order,
        (parent.c.level + 1).label("level")
      ) \
      .filter(child.pmenu_id == parent.c.menu_id)
    )

    query = session.query(
        child,
        func.min(hierarchy.c.sort_order).over(partition_by=hierarchy.c.menu_type).label("sort_type")
      ) \
      .select_entity_from(hierarchy)

    for q in query.all():
      print(q)
예제 #49
0
def add_user():
    name = raw_input("Name: ")
    email = raw_input("Email: ")
    if session.query(User).filter_by(email=email).first():
        print "User with that email already exists"
        return

    password = ""
    password_2 = ""
    while not (password and password_2) or password != password_2:
        password = getpass("Password: "******"Re-enter password: ")
    user = User(name=name, email=email,
        password=generate_password_hash(password))
    session.add(user)
    session.commit()
예제 #50
0
def load_user(request):
    """Check authorization header and authenticate user for request.

    Authenticate user with provided token where the login_required
    decorator is used
    """
    token = request.headers.get('token')
    if token:
        s = Serializer(os.environ.get('SECRET_KEY'))
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None
        user = session.query(User).get(data['confirm'])
        return user
    return None
예제 #51
0
def load_user(request):
    """Check authorization header and authenticate user for request.

    Authenticate user with provided token where the login_required
    decorator is used
    """
    token = request.headers.get('token')
    if token:
        s = Serializer(os.environ.get('SECRET_KEY'))
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None
        user = session.query(User).get(data['confirm'])
        return user
    return None
예제 #52
0
    def post(self):
        """Log in a user."""
        parser.add_argument('username')
        parser.add_argument('password')
        args = parser.parse_args()
        username = args['username']
        password_hash = args['password']

        userlogged = session.query(User).filter_by(username=username).first()
        if password_hash:
            if not userlogged:
                return {'message': "User doesn't exist"}, 404
            if userlogged.verify_password(password_hash):
                token = userlogged.generate_confirmation_token()
                flash("user successfully logged in")
                return {'token': token}, 201
            # if password not verified
            return {'message': 'Incorrect password.'}, 400
        return {'message': 'Password missing'}, 400
예제 #53
0
    def post(self):
        """Allow a user to register."""
        parser.add_argument('username')
        parser.add_argument('password')

        args = parser.parse_args()
        username = args['username']
        password = args['password']
        exists = session.query(User).filter_by(username=username).first()
        if username and password:
            if exists and exists.username == username:
                return {'message': 'User already exists!'}, 400
            user = User(username=username)
            user.hash_password(password)
            session.add(user)
            session.commit()
            return {'message': 'User {} has been successfully registered'
                               .format(username)}, 201
        return {'message': 'Missing fields!'}, 400
예제 #54
0
파일: views.py 프로젝트: Mac-Genius/auacm
def get_competition_teams(cid):
    """ Get all of the teams in a competition.

    Returns all of the teams, their users, and those users' display names.
    """
    comp_users = session.query(CompUser, User).join(User,
            User.username == CompUser.username).filter(CompUser.cid == cid)\
            .all()

    teams = dict()
    for user in comp_users:
        if user.CompUser.team not in teams:
            teams[user.CompUser.team] = list()
        teams[user.CompUser.team].append({
            'username': user.User.username,
            'display': user.User.display
        })

    return serve_response(teams)
예제 #55
0
파일: models.py 프로젝트: AuburnACM/auacm
    def update_status(self, status):
        '''Updates status in the database.

        :param status: the status of the submission
        :return: None
        '''
        self.result = status
        dblock.acquire()

        # Add to problem_solved if solved for first time
        if status == 'good' and not (session.query(ProblemSolved)
                .filter(ProblemSolved.pid == self.pid)
                .filter(ProblemSolved.username == self.username).all()):
            session.add(ProblemSolved(username=self.username, pid=self.pid,
                                      submit_time=self.submit_time))

        session.flush()
        session.commit()
        dblock.release()
예제 #56
0
파일: views.py 프로젝트: Mac-Genius/auacm
def submit():
    """
    Retrieves the submission information from the request, creates a submission, then begins the submissions execution.
    The response simply returns an empty object for data. (In the future, this will return the handle to a web socket).

    :return: serves a 200 request code and an empty object if it is a good request, 403 if the filetype is unsupproted,
            400 if the required fields are missing.
    """

    uploaded_file = request.files['file']
    if not uploaded_file:
        return serve_error('file must be uploaded', response_code=400)
    if not judge.allowed_filetype(uploaded_file.filename):
        return serve_error('filename not allowed', response_code=403)
    if not request.form['pid']:
        return serve_error('the field \'pid\' must be specified', response_code=400)

    # Obtain the time limit for the problem
    time_limit = session.query(ProblemData).\
            options(load_only("pid", "time_limit")).\
            filter(ProblemData.pid==request.form['pid']).\
            first().time_limit;

    attempt = models.Submission(
        username=current_user.username,
        pid=request.form['pid'],
        submit_time=int(time.time()),
        auto_id=0,
        file_type=uploaded_file.filename.split('.')[-1].lower(),
        result='start')
    attempt.commit_to_session()
    thread = Thread(
        target=judge.evaluate, args=(attempt, uploaded_file, time_limit))
    thread.daemon = False
    thread.start()
    return serve_response({
        'submissionId': attempt.job
    })
예제 #57
0
파일: util.py 프로젝트: LucyCReynolds/auacm
def load_user(user_id):
    '''Log a user into the app.'''
    return session.query(User).filter(User.username==user_id).first()