def createTeam(): if session.get("id") is None: return redirect("/user/login") name = session.get("name") if request.method == "GET": return render_template('student_templates/createTeam.html', name=name) else: name = request.form.get("name") userId = session.get("id") course = CourseAndStudent.query.filter( CourseAndStudent.studentId == userId).first() with db.auto_commit(): team = Team() team.courseId = course.CourseId team.TeamName = name team.isFinish = 0 db.session.add(team) team = Team.query.filter( Team.courseId == course.CourseId).order_by( Team.TeamNumber.desc()).first() member = Member() member.studentId = userId member.teamId = team.TeamNumber member.votenum = 0 db.session.add(member) return redirect('/student/display')
def create_team(team_name: str, owner: str): """Create new team.""" new_team = Team(name=team_name, owner=owner, team_members=[], draft_position=0) new_team.save() return new_team
def get_team(): with db.auto_commit(): team = Team() team.TeamName = 'g1' team.TeamNumber = 0 # 数据库的insert操作 db.session.add(team) return 'hello team'
def get(self): args = self.get_teams_parser.parse_args() team_name = args.get('name', None) if team_name: teams = TeamModel.search_teams_by_name(name=team_name) else: teams = TeamModel.get_all_teams() team_data = [t.serialize() for t in teams] return {'teams': team_data}
def create_team(): jsonData = request.get_json() with db.auto_commit(): team = Team() team.team_name = jsonData['team_name'] team.team_logo = jsonData['team_logo'] team.team_type = jsonData['team_type'] team.team_captain = jsonData['team_captain'] team.team_slogan = jsonData['team_slogan'] team.team_comment = jsonData['team_comment'] team.school_id = jsonData['school_id'] team.category_id = jsonData['category_id'] db.session.add(team) return Success(msg='新增成功')
def get_team_image(): teams = rackhd_config.Teams repo = rackhd_config.repos team_name = request.form['TeamName'] or 'Maglev Team' startDate = request.form['StartDate'] or '2015-10-01' endDate = request.form['EndDate'] or datetime.now() image_name = request.form['image_name'] if type(startDate) == type(""): startDate = datetime.strptime(startDate, "%Y-%m-%d") if type(endDate) == type(""): endDate = datetime.strptime(endDate, "%Y-%m-%d") team_members = teams[team_name] #print("startDate %s, endDate: %s" % (startDate,endDate) ) t = Team(team_name, team_members) operator = { 'image1': t.draw_team_pr_count_monthly(startDate, endDate), 'image2': t.draw_team_comments_count_monthly(startDate, endDate), 'image3': t.draw_team_avg_duration_monthly(startDate, endDate), 'image4': t.draw_pr_count_member(startDate, endDate), 'image5': t.draw_comments_count_member(startDate, endDate), 'image6': t.draw_avg_duration_member(startDate, endDate) } image_output = operator[image_name] image = base64.b64encode(image_output).decode('UTF-8') return make_response(image)
def update_lines(cls, game_lines): if len(game_lines) == 0: return for new_game in game_lines: game_found = False current_week = Week.get_current_week(new_game['Date']) games = current_week.games previous_game_entry = None for existing_game in games: if existing_game.team_1.to_string( ) == new_game['Favorite'] or existing_game.team_1.to_string( ) == new_game['Underdog']: if existing_game.team_2.to_string() == new_game[ 'Favorite'] or existing_game.team_2.to_string( ) == new_game['Underdog']: game_found = True favorite = existing_game.team_1.to_string( ) == new_game['Favorite'] previous_game_entry = existing_game break if not game_found: print(new_game['Favorite']) print(new_game['Underdog']) game = Game(date=new_game['Date'], team_1_id=Team.find_team(new_game['Favorite']).id, team_2_id=Team.find_team(new_game['Underdog']).id, week_id=current_week.id) db.session.add(game) db.session.flush() spread = Spread(game_id=game.id, points=new_game['Line'], favorite=True) db.session.add(spread) else: old_spread = previous_game_entry.spreads.first() if old_spread.points != float( new_game['Line']) or not favorite: spread = Spread(game_id=previous_game_entry.id, points=new_game['Line'], favorite=favorite) db.session.add(spread) current_week.last_updated = datetime.datetime.now() db.session.add(current_week) db.session.commit()
def get_all_sports_teams(exclude=set()): other_teams = Team.select().where(~(Team.id << exclude)) team_data = {} for sport_type in Sport.SportType: team_data[sport_type.value] = [] for team in other_teams: team_data[team.sport_type.value].append(team) return team_data
def delete_team_api(id_): team = Team.get_by_id(id_) if not team: raise NotFound() contest = team.contest if contest.status == 0: raise Forbidden('Contest is not available') if contest.registration_status == 0: raise Forbidden('Contest is not open registration') if g.user.permission != -1 and g.user.username != team.create_username: raise Forbidden() team_relationship = TeamRelationship.search(team_id=team.id) if team_relationship['count'] != 1: raise Forbidden('There are other members in the team') TeamRelationship.delete_team_relationship(team_relationship['data'][0].id) Team.delete_team(id_) return DeleteSuccess('Delete team success')
def modify_team_api(id_): team = Team.get_by_id(id_) if not team: raise NotFound() contest = team.contest if contest.status == 0: raise Forbidden('Contest is not available') if contest.registration_status == 0: raise Forbidden('Contest is not open registration') if g.user.permission != -1 and g.user.username != team.create_username: raise Forbidden() form = TeamInfoForm().validate_for_api().data_ if g.user.permission != -1 and form['status'] not in [0, 1]: raise Forbidden() Team.modify(id_, **form) return Success('Modify team success')
def search_team_api(): form = SearchTeamForm().validate_for_api().data_ res = Team.search(**form) return jsonify({ 'code': 0, 'data': { 'res': res } })
def post(self): # create league_name = self.get_body_argument("league_name") manager_team_name = self.get_body_argument("manager_team_name") league = League(name=league_name) team = Team(name=manager_team_name, league=league) league.manager = team self.session.add_all([league, team]) self.session.commit()
def post(self, invitation_unid): args = self.update_parser.parse_args() status = args['status'].lower() invitation = TeamInvite.get_by_unid(invitation_unid) if invitation is None: return {'status': 'false', 'message': 'No invitation found'}, 404 if status == 'accept': user_team = UserTeam(invitation.invite_user_unid, invitation.invite_team_unid, 1) invitation.delete(soft=False) Team.add_participant(invitation.invite_team_unid) return {'status': 'true', 'message': 'Invite accepted'}, 201 elif status in ('decline', 'revoke'): invitation.delete(soft=False) return {'status': 'true', 'message': 'Invitation processed'}, 201 else: return {'status': 'true', 'message': 'Invalid status'}, 400
def get_team_api(id_): team = Team.get_by_id(id_) if not team: raise NotFound() return jsonify({ 'code': 0, 'data': { 'team': team } })
def post_team(req): """ """ # Get data from request req.get_data() league_id = req.json.get('league_id') user_id = req.json.get('user_id') name = req.json.get('name') # Create instance of GoalScored and add to database new_team = Team(user_id=user_id, league_id=league_id, name=name) db.session.add(new_team) # Commit data to database - if exception is caught, return the error message try: db.session.commit() except IntegrityError as e: db.session.rollback() return jsonify(status='fail', error=str(e.orig)) # Return success message return jsonify(status='success', data={'Team': new_team.to_dict()})
def get_favorites(self): """ Get favorites for a user item. :return: list of favorite Team objects for the User. """ from app.models.favorite import Favorite join_predicate = ((Team.espn_id == Favorite.team) & (Team.sport_type == Favorite.sport_type)) favorites = Team.select().join( Favorite, on=join_predicate).where(Favorite.user_id == self.id) return favorites
def create_team_api(): form = TeamInfoForm().validate_for_api().data_ contest = Contest.get_by_id(form['contest_id']) if contest.status == 0: raise Forbidden('Contest is not available') if contest.registration_status == 0: raise Forbidden('Contest is not open registration') for i in TeamRelationship.search(username=g.user.username)['data']: if i.team.contest.id == form['contest_id']: raise Forbidden('You already have a team') team = Team.create_team(form['name'], form['contest_id'], g.user.username, form['password']) TeamRelationship.create_team_relationship(g.user.username, team.id) return CreateSuccess('Create team success')
def create_team_relationship_api(): form = TeamRelationshipForm().validate_for_api().data_ team = Team.get_by_id(form['team_id']) if not team: raise NotFound() contest = team.contest if contest.status == 0: raise Forbidden('Contest is not available') if contest.registration_status == 0: raise Forbidden('Contest is not open registration') for i in TeamRelationship.search(username=g.user.username)['data']: if i.team_id == form['team_id']: raise Forbidden('You already have a team') if TeamRelationship.search(team_id=form['team_id'])['count'] >= team.contest.limit: raise Forbidden('The team is full') if not team.check_password(form['password']): raise Forbidden('Password wrong') TeamRelationship.create_team_relationship(g.user.username, form['team_id']) return CreateSuccess('Create team relationship success')
def post(self): args = self.create_team_parser.parse_args() name = args['team_name'] max_members = args['max_participants'] captain = args['team_captain'] num_members = args['number_participants'] route = args['route_id'] needs_accessibility = args.get('requires_accessibility', 0) public = args.get('public_team', 0) public = 0 if public == "0" or public == 0 or public == None else 1 captain_user = User.fetch_user_by_unid(captain) if captain_user is None: return {'status': 'false', 'message': 'Team captain given does not exist'}, 400 team = TeamModel.create_team(name, captain, max_members, num_members, public) user_team = UserTeam.add_user_to_team(captain, team.unid, 2) return {'status': 'true', 'team_id': team.unid, 'user_team': user_team.unid}, 201
class Organization(object): """rackhd and no_rackhd organization """ def __init__(self): self.rackhd = Team("rackhd", []) self.no_rackhd = Team("no_rackhd", []) self.db = SQLiteDB() self.set_rackhd() self.set_no_rackhd() def set_rackhd(self): """select all users from USERS table and set rackhd members """ if self.db == None: self.db = SQLiteDB() try: sql = "select distinct userName from USERS" result = self.db.getResult(sql) if result[0][0] != None: team_members = [x[0] for x in result] self.rackhd.set_team_members(team_members) else: print("USERS table is empty") except Exception as e: print("Error: %s" % e) def set_no_rackhd(self): """select from DB and set the no_rackhd members """ if self.db == None: self.db = SQLiteDB() try: sql = "select distinct user from PullRequests where user NOT IN (select distinct userName from USERS)" result = self.db.getResult(sql) if result[0][0] != None: team_members = [x[0] for x in result] self.no_rackhd.set_team_members(team_members) else: print( " select sql may wrong, or pull request don't have no_rackhd members' pr" ) except Exception as e: print("Error: %s" % e) def draw_pr_count_monthly(self, startDate, endDate, repos=None): """ 1.1 draw pr count monthly with rackhd and no-rackhd args: startDate: endDate: repos: rackhd repository """ month, rackhd_created_count = self.rackhd.get_pr_count_monthly( startDate, endDate, repos) _, rackhd_merged_count = self.rackhd.get_pr_count_monthly( startDate, endDate, repos, isMerged=True) _, rackhd_unmerged_count = self.rackhd.get_pr_count_monthly( startDate, endDate, repos, isMerged=False) _, no_rackhd_created_count = self.no_rackhd.get_pr_count_monthly( startDate, endDate, repos) _, no_rackhd_merged_count = self.no_rackhd.get_pr_count_monthly( startDate, endDate, repos, isMerged=True) _, no_rackhd_unmerged_count = self.no_rackhd.get_pr_count_monthly( startDate, endDate, repos, isMerged=False) ind = np.linspace(0.5, 9.5, len(month)) # y_ind = range(0, max(rackhd_created_count)+200, 100) fig, ax = plt.subplots(figsize=(12, 6)) plt.plot(ind, rackhd_created_count, 'r--^', linewidth=1, label='rackhd create pr count') plt.plot(ind, rackhd_merged_count, 'r-*', linewidth=1, label='rackhd merged pr count') plt.plot(ind, rackhd_unmerged_count, 'r-.o', linewidth=1, label='rackhd unmerged pr count') plt.plot(ind, no_rackhd_created_count, 'c--^', linewidth=1, label='norackhd create pr count') plt.plot(ind, no_rackhd_merged_count, 'c-*', linewidth=1, label='norackhd merged pr count') plt.plot(ind, no_rackhd_unmerged_count, 'c-.o', linewidth=1, label='norackhd unmerged pr count') plt.xticks(ind, month, rotation=30) # plt.yticks(y_ind) plt.xlabel('Month') plt.ylabel('PR Count') plt.title('PR Count Monthly') plt.legend() canvas = FigureCanvas(fig) png_output = BytesIO() canvas.print_png(png_output) return png_output.getvalue() def draw_comments_monthly(self, startDate, endDate, repos=None): """ 1.2 draw review count monthly with rackhd and no-rackhd args: startDate: endDate: repos: rackhd repository """ month, rackhd_comments_count = self.rackhd.get_comments_count_monthly( startDate, endDate, repos) _, no_rackhd_comments_count = self.no_rackhd.get_comments_count_monthly( startDate, endDate, repos) x_ind = np.linspace(0.5, 9.5, len(month)) y_ind = range( 0, max(rackhd_comments_count + no_rackhd_comments_count) + 400, 100) fig, ax = plt.subplots(figsize=(12, 6)) plt.plot(x_ind, rackhd_comments_count, 'r--^', linewidth=1, label='rackhd comments count') plt.plot(x_ind, no_rackhd_comments_count, 'c--^', linewidth=1, label='norackhd comments count') plt.xticks(x_ind, month, rotation=30) plt.yticks(y_ind) plt.xlabel('Month') plt.ylabel('Review Count') plt.title('Review Count Monthly') plt.legend() canvas = FigureCanvas(fig) png_output = BytesIO() canvas.print_png(png_output) return png_output.getvalue()
def __init__(self): self.rackhd = Team("rackhd", []) self.no_rackhd = Team("no_rackhd", []) self.db = SQLiteDB() self.set_rackhd() self.set_no_rackhd()
def byStudent(): if session.get("id") is None: return redirect("/user/login") name=session.get("name") courseId=request.args.get("courseId") studentList=CourseAndStudent.query.filter_by(CourseId=courseId).all() list=[] for i in studentList: student=Student.query.filter_by(id=i.studentId).first() if student is not None: list.append(student) #每组的人数 totalNum=Course.query.filter_by(CourseId=courseId).first().numofmember #组的数量 # teamNum=len(list)/totalNum+1 # print(teamNum) # # if teamNum==1: # list2=[] # list2.append(list) # pass # else: from random import shuffle shuffle(list) # 重排序 list2 = [] for i in range(0, len(list), totalNum): list2.append(list[i:i + totalNum]) result=[] for i in list2: dict1 = dict() nameTeam=random.randint(100,1000) dict1["name"]=str(nameTeam) dict1["value"]=i print(i) result.append(dict1) with db.auto_commit(): team = Team() team.TeamName=str(nameTeam) team.courseId=courseId # 数据库的insert操作 db.session.add(team) team=Team.query.filter(Team.courseId==courseId).filter(Team.TeamName==nameTeam).first() with db.auto_commit(): for x in i: member=Member() member.teamId=team.TeamNumber member.studentId=x.id db.session.add(member) Course.query.filter(Course.CourseId == courseId).update({"teamType": 2}) db.session.commit() return render_template("teacher_templates/displaygroup.html",name=name,courseId=courseId,result=result)
def validate_team_id(self, value): if not Team.get_by_id(self.team_id.data): raise ValidationError('The team does not exist')
def get_team(team_unid): team = TeamModel.get_team_by_unid(team_unid) if not team: abort(404, message='No team found', status='false') return team