def test_delete_removes_team(self): user = User.create(name='foo', email='*****@*****.**') team = Team.create(name='Team Foo', captain_id=user.uid, program_id=self.demo_program.uid) team.put() user.owned_teams = [team.uid] user.put() survey = Survey.create(team_id=team.uid) survey.put() url = '/api/teams/{}'.format(team.uid) headers = self.login_headers(user) # Delete the team. self.testapp.delete(url, headers=headers, status=204) # Expect the team is gone from the db. self.assertIsNone(Team.get_by_id(team.uid)) # Api should show a 404. self.testapp.get(url, headers=headers, status=404) self.testapp.delete(url, headers=headers, status=404)
def test_post_preview_setting(self): for x in range(1, 4): Team.create( id='00{}'.format(x), captain_id='User_cap', program_id=self.program.uid, ).put() def body(x): return { 'filename': 'file_00{}.html'.format(x), 'team_id': 'Team_00{}'.format(x), 'dataset_id': 'Dataset_00{}'.format(x), 'template': 'template.html', } headers = {'Authorization': 'Bearer ' + self.valid_jwt} preview_rsp = self.testapp.post_json('/api/reports', dict(body(1), preview=True), headers=headers) non_pre_rsp = self.testapp.post_json('/api/reports', dict(body(2), preview=False), headers=headers) default_rsp = self.testapp.post_json('/api/reports', body(3), headers=headers) preview_fetched = Report.get_by_id(json.loads(preview_rsp.body)['uid']) non_pre_fetched = Report.get_by_id(json.loads(non_pre_rsp.body)['uid']) default_fetched = Report.get_by_id(json.loads(default_rsp.body)['uid']) self.assertEqual(preview_fetched.preview, True) self.assertEqual(non_pre_fetched.preview, False) self.assertEqual(default_fetched.preview, True)
def add_slack(): try: code = request.args.get('code') # state = request.args.get('state') # An empty string is a valid token for this request temp_sc = SlackClient("") # Request the auth tokens from Slack auth_response = temp_sc.api_call("oauth.access", client_id=SLACK_CLIENT_ID, client_secret=SLACK_CLIENT_SECRET, code=code) user_token = auth_response['access_token'] bot_token = auth_response['bot']['bot_access_token'] team_id = auth_response['team_id'] team_name = auth_response['team_name'] team = Team(code=code, bot_token=bot_token, user_token=user_token, team_name=team_name, team_id=team_id) team.save() return render_template('add_successful.html') except: # noqa: #722 return render_template('error.html')
def test_disallow_classroom_move(self): """Update the team_id of all class reports when class moves.""" user = User.create(name='foo', email='*****@*****.**') team1 = Team.create(name='Team Foo', captain_id=user.uid, program_id=self.program.uid) team1.put() team2 = Team.create(name='Team Bar', captain_id=user.uid, program_id=self.program.uid) team2.put() user.owned_teams = [team1.uid, team2.uid] user.put() classroom = Classroom.create( name='Classroom Foo', code='trout viper', team_id=team1.uid, contact_id=user.uid, num_students=22, grade_level='9-12', ) classroom.put() # move class to new team self.testapp.put_json( '/api/classrooms/{}'.format(classroom.uid), {'team_id': team2.uid}, headers=self.login_headers(user), status=403, )
def test_delete_disassociates_teams(self): """When you delete an org, associated teams lose their org id.""" user, org_dict = self.test_create() teams = [ Team.create( name="Team Foo", organization_ids=[org_dict['uid']], captain_id='User_captain', program_id=self.program.uid, ), Team.create( name="Team Bar", organization_ids=[org_dict['uid']], captain_id='User_captain', program_id=self.program.uid, ), ] Team.put_multi(teams) response = self.testapp.delete('/api/organizations/{}'.format( org_dict['uid']), headers=self.login_headers(user), status=204) # Make sure the teams have lost their association to the org. for t in teams: fetched = Team.get_by_id(t.uid) self.assertNotIn(org_dict['uid'], fetched.organization_ids)
def resolve_id_mismatch(klass, user, new_id): """Change all references to user's id to a new id. N.B. this is obviously brittle; when the relationship schema changes, this will also have to change. """ # The auth server has a different id for this user; defer to it. teams = Team.get(captain_id=user.uid) for t in teams: t.captain_id = new_id Team.put_multi(teams) classrooms = Classroom.get(contact_id=user.uid) for c in classrooms: c.contact_id = new_id Classroom.put_multi(classrooms) params = {'uid': new_id, 'short_uid': SqlModel.convert_uid(new_id)} with mysql_connection.connect() as sql: sql.update_row(klass.table, 'uid', user.uid, **params) for k, v in params.items(): setattr(user, k, v) return user
def test_rserve_skips_existing(self): program = Program.create( name="The Engagement Project", label="ep19", preview_url='foo.com', ) week = util.datelike_to_iso_string(datetime.date.today()) org = Organization.create(name="Organization", captain_id="User_cap", program_id=program.uid) org_to_skip = Organization.create(name="Organization", captain_id="User_cap", program_id=program.uid) Organization.put_multi([org, org_to_skip]) team = Team.create(name="Team", captain_id="User_cap", program_id=program.uid) team_to_skip = Team.create(name="Team", captain_id="User_cap", program_id=program.uid) Team.put_multi([team, team_to_skip]) cl = Classroom.create(name="Classroom", team_id=team.uid, code="foo", contact_id="User_contact") cl_to_skip = Classroom.create(name="Classroom", team_id=team.uid, code="foo", contact_id="User_contact") Classroom.put_multi([cl, cl_to_skip]) Report.put_multi([ Report.create(parent_id=org_to_skip.uid, filename="foo", issue_date=week), Report.create(parent_id=team_to_skip.uid, filename="foo", issue_date=week), Report.create(parent_id=cl_to_skip.uid, filename="foo", issue_date=week), ]) # Skips all the parents who have reports already this week. orgs, teams, classes = cron_rserve.get_report_parents( program, week, False) self.assertEqual(len(orgs), 1) self.assertEqual(len(teams), 1) self.assertEqual(len(classes), 1) # ...unless you force it, then they're all there. orgs, teams, classes = cron_rserve.get_report_parents( program, week, True) self.assertEqual(len(orgs), 2) self.assertEqual(len(teams), 2) self.assertEqual(len(classes), 2)
def test_task_data_too_large(self): user = User.create(name='foo', email='*****@*****.**') user.put() team_params = {'name': 'Team Foo', 'program_id': self.demo_program.uid} # A property is too long. self.testapp.post_json( '/api/teams', dict(team_params, task_data={'foo': 'x' * 10**5}), headers=self.login_headers(user), status=413, ) # Too many properties. self.testapp.post_json( '/api/teams', dict( team_params, task_data={'foo{}'.format(x): 'x' for x in range(10**3)}, ), headers=self.login_headers(user), status=413, ) # Both posts should have prevented teams from being stored. self.assertEqual(len(Team.get()), 0) # Successful POST response = self.testapp.post_json( '/api/teams', dict(team_params, task_data={'safe': 'data'}), headers=self.login_headers(user), ) response_dict = json.loads(response.body) put_url = '/api/teams/{}'.format(response_dict['uid']) # Same errors but for PUT # A property is too long. self.testapp.put_json( put_url, {'task_data': {'foo': 'x' * 10**5}}, headers=self.login_headers(user), status=413, ) # Too many properties. self.testapp.put_json( put_url, {'task_data': {'foo{}'.format(x): 'x' for x in range(10**3)}}, headers=self.login_headers(user), status=413, ) # Puts should have left body unchanged. self.assertEqual( Team.get_by_id(response_dict['uid']).task_data, {'safe': 'data'}, )
def viewTeam(): hold = 123 tt = 0 tc = tm.select().count() while (hold == 123): t = tm.select().limit(5).offset(tt) print( '{:<25s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}'.format( 'Team', 'Point Guard', 'Shooting Guard', 'Small Forward', 'Power Forward', 'Center', 'Owner', 'Coach')) print('-' * 157) for team in t: print('{:<25s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}'. format(team.tName, team.tPG, team.tSG, team.tSF, team.tPF, team.tC, team.tOwner, team.tCoach)) hold = input('\nNEXT[N]|END[X]: ') while (hold == 'n') or (hold == 'N'): os.system('cls') tt = tt + 5 t = tm.select().limit(5).offset(tt) print('{:<25s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}'. format('Team', 'Point Guard', 'Shooting Guard', 'Small Forward', 'Power Forward', 'Center', 'Owner', 'Coach')) print('-' * 160) for team in t: print( '{:<25s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}'. format(team.tName, team.tPG, team.tSG, team.tSF, team.tPF, team.tC, team.tOwner, team.tCoach)) hold = input('\nPREV[P]|NEXT[N]|END[X]: ') while (hold == 'p') or (hold == 'P'): os.system('cls') tt = tt - 5 t = tm.select().limit(5).offset(tt) print( '{:<25s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}'. format('Team', 'Point Guard', 'Shooting Guard', 'Small Forward', 'Power Forward', 'Center', 'Owner', 'Coach')) print('-' * 160) for team in t: print( '{:<25s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}{:<20s}' .format(team.tName, team.tPG, team.tSG, team.tSF, team.tPF, team.tC, team.tOwner, team.tCoach)) hold = input('\nPREV[P]|NEXT[N]|END[X]: ') if (tt == 5) & (hold == 'p') or (hold == 'P'): os.system('cls') tt = 0 hold = 123 elif tt < 0: break
def default_values(self): "Set some default values in the database" # Add some information box = hub.getConnection() t1 = Team(city='Pittsburgh', nickname='Ferrous Metals') box.memorize(t1) t2 = Team(city='Seattle', nickname='Seagulls') box.memorize(t2) p1 = Player(name='Bob Waffleburger', birthdate=datetime.date(1982,3,2), points=21) box.memorize(p1) p2 = Player(name='Mike Handleback', birthdate=datetime.date(1975,9,25), points=10) box.memorize(p2) p1.team = t1.ID p2.team = t2.ID # Add a default Page page = Page( pagename="FrontPage", data="This is the main page, please edit it." ) box.memorize( page ) # Setup identity data jrodrigo = TG_User( user_name = "jrodrigo" ) box.memorize( jrodrigo ) jrodrigo.password = "******" root = TG_User( user_name = "root" ) box.memorize( root ) root.password = "******" user = TG_Group( group_name = "user" ) box.memorize( user ) admin = TG_Group( group_name = "admin" ) box.memorize( admin ) format = TG_Permission( permission_name = "format" ) box.memorize( format ) ls = TG_Permission( permission_name = "ls" ) box.memorize( ls ) cat = TG_Permission( permission_name = "cat" ) box.memorize( cat ) o = TG_UserGroup( user_id = root.user_id, group_id = user.group_id ) box.memorize( o ) o = TG_UserGroup( user_id = root.user_id, group_id = admin.group_id ) box.memorize( o ) o = TG_UserGroup( user_id = jrodrigo.user_id, group_id = user.group_id ) box.memorize( o ) o = TG_GroupPermission( group_id = admin.group_id, permission_id = format.permission_id ) box.memorize( o ) o = TG_GroupPermission( group_id = user.group_id, permission_id = ls.permission_id ) box.memorize( o ) o = TG_GroupPermission( group_id = user.group_id, permission_id = cat.permission_id ) box.memorize( o ) return "done"
def POST(self,playerName, currentTeam, selectedMember): try: connection = functions.Worker() playerTagObject = PlayerTag() playerTagObject.SetPlayerTag(playerName) currentTeamObject = Team() currentTeamObject.SetTeamName(currentTeam) selectedMemberObject = PlayerTag() selectedMemberObject.SetPlayerTag(selectedMember) teamDB = connection.FindTeam(currentTeamObject) members = [] for member in teamDB['Members']: if(members.__contains__(member)):continue else: members.append(member) except: template = jinja_environment.get_template('templates/manageateam.html') return template.render({'the_title': 'Manage A Team.', 'playerTagHeader': playerName, 'errorMatch': ("Unexpected error:", sys.exc_info()[1]), 'team' : currentTeam, 'members' : members}) if(teamDB['Administrator'] != playerName): template = jinja_environment.get_template('templates/manageateam.html') return template.render({'the_title': 'Manage A Team.', 'playerTagHeader': playerName, 'errorMatch': 'Administrators privilege required in order to remove members.', 'team' : currentTeam, 'members' : members}) else: if(teamDB['Administrator'] == selectedMember): template = jinja_environment.get_template('templates/manageateam.html') return template.render({'the_title': 'Manage A Team.', 'playerTagHeader': playerName, 'errorMatch': 'Administrators cannot be removed. Delete the Team instead!', 'team' : currentTeam, 'members' : members}) else: t = [] t = teamDB['Members'] for item in t: if(item.__contains__(selectedMember)): #Get the member t.remove(item) playerTagObject = PlayerTag() playerTagObject.SetPlayerTag(str(item)) playerDB = connection.FindPlayerTagNoPass(playerTagObject) playerDB['Teams'].remove(teamDB['TeamName']) connection.UpdatePlayerTag(playerDB) teamDB['Members'] = t connection.UpdateTeam(teamDB) raise cherrypy.HTTPRedirect("/dash/", 302)
def get(self): existing = Team.for_user(users.get_current_user()) votes = Votes.for_user(users.get_current_user()) city = self.get_user_city(votes) if city is None: self.render('listlocal_fail', { }) else: all_teams = Team.for_city(city) all_teams.sort(key=attrgetter('local_votes')) self.render('winnerslocal', { 'teams': all_teams, 'city': city, 'team': existing })
def create_for_paging(self, n): # Pad numeric names so they sort alphabetically. teams = [ Team.create(name=str(x).rjust(2, '0'), captain_id='User_captain', program_id=self.demo_program.uid) for x in range(n) ] Team.put_multi(teams) super_admin = User.create(name='super', email='*****@*****.**', user_type='super_admin') super_admin.put() return teams, super_admin
def test_delete_own_forbidden(self): team = Team.create(name='foo', captain_id='User_cap', program_id=self.demo_program.uid) team.put() user = User.create(name='foo', email='*****@*****.**', owned_teams=[team.uid]) user.put() response = self.testapp.delete( '/api/teams/{}'.format(team.uid), headers=self.login_headers(user), status=403 ) self.assertIsNotNone(Team.get_by_id(team.uid))
def __init__(self, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10): self.t1 = T.Team(p1, p2, p3, p4, p5) self.t2 = T.Team(p6, p7, p8, p9, p10) self.score = 0 self.rating = 0 self.level_diff = 0 self.role_pref = 0 self.value_diff = 0 self.synergy = 0 self.other_value_diff = 0 self.calc_score()
def POST(self, playerName, selectedTeam): try: connection = functions.Worker() playerTagObject = PlayerTag() playerTagObject.SetPlayerTag(playerName) selectedTeamObject = Team() selectedTeamObject.SetTeamName(selectedTeam) teamNames = connection.GetAllTeams() team = connection.GetTeams(playerTagObject) for item in team: if (teamNames.__contains__(item)): teamNames.remove(item) except: template = jinja_environment.get_template( 'templates/joinateam.html') return template.render({ 'playerTagHeader': playerTagObject.GetPlayerTag(), 'errorMatch': ("Unexpected error:", sys.exc_info()[1]), 'teams': teamNames }) #Check if this user is part of this current team teamMember = connection.GetTeams(playerTagObject) if (teamMember.__contains__(selectedTeam)): template = jinja_environment.get_template( 'templates/joinateam.html') return template.render({ 'the_title': 'Join A Team.', 'playerTagHeader': playerTagObject.GetPlayerTag(), 'errorMatch': 'Player Tag is already a member of this Team!', 'teams': teamNames }) else: teamDB = connection.FindTeam(selectedTeamObject) teamDB['Members'].append(playerName) connection.UpdateTeam(teamDB) playerDB = connection.FindPlayerTagNoPass(playerTagObject) playerDB['Teams'].append(teamDB['TeamName']) connection.UpdatePlayerTag(playerDB) raise cherrypy.HTTPRedirect("/dash/", 302)
def test_change_captain_forbidden(self): team = Team.create(name='foo', captain_id='User_cap', program_id=self.demo_program.uid) team.put() user = User.create(name='foo', email='*****@*****.**', owned_teams=[team.uid]) user.put() response = self.testapp.put_json( '/api/teams/{}'.format(team.uid), {'captain_id': user.uid}, headers=self.login_headers(user), status=403, ) team = Team.get_by_id(team.uid) self.assertNotEqual(team.captain_id, user.uid)
def __init__(self, settings): # ----- init simulator ----- self.simulation_id = settings['simulation_id'] if settings[ 'simulation_id'] else random.randint(1000, 9999) self.time = 0.0 self.time_step = 1.0 random.seed(self.simulation_id) # ----- create scenario ----- scenario = Scenario(settings['scenario_type'], settings['scenario_id']) self.scenario_type = scenario.scenario_type self.scenario_id = scenario.scenario_id self.time_max = scenario.time_max # ----- init logger ----- self.logger = Logger(settings['logger_verbose_level']) # ----- init reporter ----- reporter_settings = { 'print_enabled': settings['reporter_print'], 'export_enabled': settings['reporter_export'] } reporter_init_data = { 'experiment_id': settings['experiment_id'], 'scenario_type': self.scenario_type, 'scenario_id': self.scenario_id, 'time_max': self.time_max, 'simulation_id': self.simulation_id, 'planner': settings['planner'], 'agents_ids': [ agent_specs['id'] for agent_specs in scenario.team_specs['agents_specs'] ], } self.reporter = Reporter(reporter_settings, reporter_init_data) # ----- init behavior & team ----- self.behavior = Behavior(scenario.behavior_specs, scenario.actions_names, self.logger) self.team = Team(scenario.team_specs, settings['planner'], self.logger, self.reporter)
def post(self): team_key = self.request.get('team_key') team = Team.get(team_key) text = self.request.get('text') team.annotation = text team.put() self.redirect('/', {})
def get(self, program_id_or_label): user = self.get_current_user() if not user.super_admin: return self.http_forbidden() program = Program.get_by_id(program_id_or_label) if not program: program = Program.get_by_label(program_id_or_label) if not program: return self.http_not_found() search_str = self.get_param('q', unicode, None) if not search_str: return self.write([]) if search_str.startswith('user:'******'t have team r orgs = Organization.query_by_name(search_str, program.uid) teams = Team.query_by_name(search_str, program.uid) classrooms = Classroom.query_by_name(search_str, program.uid) users = User.query_by_name_or_email(search_str) self.write({ 'organizations': [e.to_client_dict() for e in orgs], 'teams': [e.to_client_dict() for e in teams], 'classrooms': [e.to_client_dict() for e in classrooms], 'users': [e.to_client_dict() for e in users], })
def get(self): #TODO(kushal): Support location filter all_teams = Team.all().fetch(1000) for team in all_teams: team.totalvotes = team.votes + team.local_votes all_teams.sort(key=attrgetter('totalvotes')) self.render('winners', { 'teams': all_teams })
def test_create(self): """Team owners can create classrooms with themselves as contact.""" team = Team.create(name='Team Foo', captain_id='User_cap', program_id=self.program.uid) team.put() user = User.create(name='User Foo', email='*****@*****.**', owned_teams=[team.uid]) user.put() response = self.testapp.post_json( '/api/classrooms', { 'name': 'Classroom Foo', 'team_id': team.uid, 'code': 'a a', 'contact_id': user.uid }, headers=self.login_headers(user), ) # Make sure the response is right. response_dict = json.loads(response.body) classroom = Classroom.get_by_id(response_dict['uid']) self.assertEqual( response.body, json.dumps(classroom.to_client_dict(), default=util.json_dumps_default), ) # Make sure the contact is set. self.assertEqual(classroom.contact_id, user.uid) # Clear the user's cookie so we can use the app as other people. self.testapp.reset() return user, classroom
def set_up(self): # Let ConsistencyTestCase set up the datastore testing stub. super(TestApiSurveys, self).set_up() application = webapp2.WSGIApplication(api_routes, config={ 'webapp2_extras.sessions': { 'secret_key': self.cookie_key } }, debug=True) self.testapp = webtest.TestApp(application) with mysql_connection.connect() as sql: sql.reset({ 'classroom': Classroom.get_table_definition(), 'metric': Metric.get_table_definition(), 'program': Program.get_table_definition(), 'survey': Survey.get_table_definition(), 'team': Team.get_table_definition(), 'user': User.get_table_definition(), }) self.ep_program = Program.create( name="Engagement Project", label='ep18', active=True, preview_url='foo.com', ) self.ep_program.put()
def create(self): other = User.create(name='other', email='*****@*****.**') teammate = User.create(name='teammate', email='*****@*****.**') contact = User.create(name='contact', email='*****@*****.**') captain = User.create(name='captain', email='*****@*****.**') super_admin = User.create(name='super', email='*****@*****.**', user_type='super_admin') team = Team.create(name='Team foo', captain_id=captain.uid, program_id=self.program.uid) team.put() classroom = Classroom.create(name='Class foo', team_id=team.uid, code='trout viper', contact_id=contact.uid) classroom.put() teammate.owned_teams.append(team.uid) contact.owned_teams.append(team.uid) captain.owned_teams.append(team.uid) User.put_multi((other, teammate, contact, captain, super_admin)) return (other, teammate, contact, captain, super_admin, team, classroom)
def post(self, team_id, date_str=None): if date_str: today = datetime.strptime(date_str, config.iso_date_format).date() else: today = date.today() # Guaranteed to have start and end dates. cycle = Cycle.get_current_for_team(team_id, today) if not cycle: logging.info( "Either the team doesn't exist, or they don't have a cycle " "matching the current date. Doing nothing.") return team = Team.get_by_id(team_id) classrooms = Classroom.get(team_id=team_id) if len(classrooms) == 0: logging.info("No classrooms, setting participation to 0.") cycle.students_completed = 0 else: ppn = get_participation(cycle, classrooms) num_complete = 0 for code, counts in ppn.items(): complete_count = next( (c for c in counts if c['value'] == '100'), None) num_complete += complete_count['n'] if complete_count else 0 cycle.students_completed = num_complete cycle.put()
def create_for_permission(self): org = Organization.create( name="Foo Org", program_id=self.ep_program.uid) org.put() team = Team.create(name="Foo Team", program_id=self.ep_program.uid, captain_id="User_cap", organization_ids=[org.uid]) team.put() network = Network.create( name="Foo Network", program_id=self.ep_program.uid, association_ids=[org.uid] ) meta_network = Network.create( name="Foo Network", program_id=self.ep_program.uid, association_ids=[network.uid] ) Network.put_multi([network, meta_network]) net_admin = User.create(email="*****@*****.**", owned_networks=[network.uid]) meta_admin = User.create(email="*****@*****.**", owned_networks=[meta_network.uid]) User.put_multi([net_admin, meta_admin]) return (meta_admin, net_admin, meta_network, network, org, team)
def edit_team(): getid = request.args.get('id') teamData = db_session.query(Team).filter(Team.id == getid).\ with_entities(Team.title, Team.id).first() form = EditTeamForm() if teamData: form.id.data = teamData.id form.title.data = teamData.title db_session.close() if form.validate_on_submit(): id = request.form.get('id') title = request.form.get('title') team = Team(title=title) db_session.query(Team).filter(Team.id == id).update( {Team.title: title}) db_session.commit() # 记录日志 actions = ('%s%s%s' % ('修改产品组', ':', title)) savelog(actions) db_session.close() flash("修改成功,<span id='time'>3</span>秒后自动跳转管理页。") return redirect('/manage/edit_team') return render_template("edit_team.html", pagename='manage_team', this='edit', form=form)
def add_team(): form = AddTeamForm() if form.validate_on_submit(): title = request.form.get('title') team = Team(title=title, addtime=datetime.datetime.now()) team_check = db_session.query(Team).filter(Team.title == title).first() if team_check: flash('产品组已存在') return redirect('/manage/add_team') if len(title): try: db_session.add(team) db_session.commit() # 记录日志 actions = ('%s%s%s' % ('增加产品组', ':', title)) savelog(actions) db_session.close() except: flash("数据库错误!") return redirect('/manage/add_team') flash("添加成功,<span id='time'>3</span>秒后自动跳转管理页。") return redirect('/manage/add_team') return render_template("edit_team.html", pagename='manage_team', this='add', form=form)
def load_teams(teams_json): """load teams json into data base""" py_dict = json.loads(open(teams_json).read()) for team in py_dict: team_id = team['id'] name = team['name'] country_code = team['country_code'] result = team['result'] position = result['position'] points_check = result.get('points', 0) podiums_check = result.get('podiums', 0) victories_check = result.get('victories', 0) team = Team(team_id=team_id, name=name, country_code=country_code, position=position, points=points_check, podiums=podiums_check, victories=victories_check) print(team) db.session.add(team) db.session.commit()
def set_up(self): # Let ConsistencyTestCase set up the datastore testing stub. super(TestApiParticipants, self).set_up() application = self.patch_webapp(webapp2.WSGIApplication)( api_routes, config={ 'webapp2_extras.sessions': { 'secret_key': self.cookie_key } }, debug=True) self.testapp = webtest.TestApp(application) with mysql_connection.connect() as sql: sql.reset({ 'classroom': Classroom.get_table_definition(), 'cycle': Cycle.get_table_definition(), 'participant': Participant.get_table_definition(), 'program': Program.get_table_definition(), 'team': Team.get_table_definition(), 'user': User.get_table_definition(), }) self.program = Program.create( name="Engagement Project", label='ep18', min_cycles=3, active=True, preview_url='foo.com', ) self.program.put()
def test_delete_forbidden(self): """Only team captains can delete classrooms.""" teammate = User.create(name='teammate', email='*****@*****.**') other = User.create(name='other', email='*****@*****.**') team = Team.create(name='Team Foo', captain_id='User_captain', program_id=self.program.uid) team.put() teammate.owned_teams = [team.uid] User.put_multi([teammate, other]) classroom = Classroom.create( name='Classroom Foo', code='trout viper', team_id=team.uid, contact_id='User_contact', num_students=22, grade_level='9-12', ) classroom.put() for user in (teammate, other): self.testapp.delete( '/api/classrooms/{}'.format(classroom.uid), headers=self.login_headers(user), status=403, )
def updateTeam(): viewTeam() teamN = input('Enter the name of the Team: ') _tName = input('Enter the name of the new Team: ') _tPG = input('Point Guard: ') _tSG = input('Shooting Guard: ') _tSF = input('Small Forward: ') _tPF = input('Power Forward: ') _tC = input('Center: ') _tOwner = input('Team Owner: ') _tCoach = input('Team Coach: ') x = tm.update({ tm.tName: _tName, tm.tPG: _tPG, tm.tSG: _tSG, tm.tSF: _tSF, tm.tPF: _tPF, tm.tC: _tC, tm.tOwner: _tOwner, tm.tCoach: _tCoach }).where(tm.tName == teamN) cnfrm = input( 'Are you sure you want to replace the {} with the {}? [Y]: '.format( teamN, _tName)) if (cnfrm == 'y') or (cnfrm == 'Y'): y = x.execute() os.system('cls') puts(colored.cyan('\n{} team has been updated!\n'.format(y))) viewTeam()
def test_status_code_not_found_returned_when_student_id(self): """404 Not Found is returned when class exists but student_id doesn't.""" code = 'forest temple' student_id = 'zelda' bad_student_id = 'NOTzelda' team = Team.create( name="Foo Team", captain_id="User_cap", program_id=self.program.uid, ) team.put() classroom = Classroom.create( code=code, name='Adventuring 101', contact_id='User_LINK', team_id=team.uid, ) classroom.put() participant = Participant.create( student_id=student_id, team_id=team.uid, classroom_ids=[classroom.uid], ) participant.put() self.testapp.get( '/api/codes/{}/participants/{}'.format(code, bad_student_id), status=404, )
def deleteTeam(cityid, schoolid, teamid): # Удаление текущей записи в БД if session['demo']: pass else: # Ограничение по внешнему ключу FK_SAST_Team # не позволяет удалить команду при наличии связанных с ней игровых этапов. try: Team.get(school_ID = schoolid, team_ID = teamid).delete_instance() except IntegrityError: flash('Вы не можете удалить эту команду, пока она добавлена хотя бы в один игровой этап', 'danger') # Редирект на вид list return redirect( url_for('listTeam', cityid = cityid, schoolid = schoolid, teamid = teamid))
def get(self): if not checkAdmin(users.get_current_user().email()): return self.error(403) #TODO(kushal): Support location filter all_teams = filter_hidden(Team.all().fetch(1000)) for team in all_teams: team.totalvotes = team.votes + team.local_votes all_teams.sort(key=attrgetter('totalvotes')) self.render('winners', { 'teams': all_teams })
def get(self): existing = Team.for_user(users.get_current_user()) if config['enable_team_adding']: self.render('add', { 'existing': existing }) return if config['enable_team_editing']: if existing: self.render('add', { 'existing': existing }) else: self.render('noadd', { })
def delete(self, team_name): team = Team.retrieve_one_by('name',team_name) #team = Team.get_by_id(team_id) print team if team is None: abort(404) user_repo = UserRepo() followed_teams = user_repo.unfollow_team(team.put()) response = get_array_result_object(followed_teams,simple_team_field) return response
def createTeam(cityid, schoolid): # Получение полей формы из шаблона teamname = request.form['teamName'] ageid = request.form['filterAge'] # Сохранение новой записи в БД if session['demo']: pass else: Team.create( school_ID = schoolid, age_ID = ageid, teamName = teamname) # Редирект на вид list return redirect( url_for('listTeam', cityid = cityid, schoolid = schoolid))
def post(self): team_key = self.request.get('team_key') team = Team.get(team_key) hidden = self.request.get('hidden') if hidden == 'true': team.hidden = True else: team.hidden = False team.put() self.redirect('/', {})
def get(self): votes = Votes.for_user(users.get_current_user()) city = self.get_user_city(votes) if city is None: self.render('listlocal_fail', { }) else: all_teams = Team.for_city(city) votes = Votes.for_user(users.get_current_user()) for team in all_teams: team.voted = (team.key() in votes.local_teams or team.key() in votes.teams) self.render('listlocal', { 'city': city, 'teams': all_teams })
def parse_season(season): content = urlopen(season.url).read() ctx = libxml2.htmlParseDoc(content, "UTF-8") gamedays = ctx.xpathEval("//div[@class='data']/table[@class='standard_tabelle']/tr") day = None while gamedays: g = gamedays.pop(0) cls = g.get_children().prop("class") if cls == "ueberschrift": if "Spieltag" in g.content: number = int(g.content.strip().split(".", 1)[0]) day = GameDay.from_data(season, number) if day is not None: cols = g.xpathEval("td") if len(cols) == 7: team_home = cols[1].get_children() team_guest = cols[3].get_children() team_home = Team( {"caption": team_home.prop("title"), "url": team_home.prop("href")} ).url team_guest = Team( {"caption": team_guest.prop("title"), "url": team_guest.prop("href")} ).url result = Result({ "url": cols[4].xpathEval("a")[0].prop("href"), "result": parse_result(cols[4].content.strip()) }) Match({ "url": result.url, "gameday": day.url, "home": team_home, "guest": team_guest, "result": result.result }) return season
def init_team(self, team): """Create team if not exists.""" team_stored = Team.all().filter('name =',team['name']).get() if team_stored is None: team_stored = Team(name=team['name']) short_match = re.search(r'([a-z]{3})\.png$',team['flag']) team_stored.flag = team['flag'] team_stored.short = short_match.group(1) team_stored.href = "http://www.uefa.com/" + team['href'] team_stored.teamId = re.match(r'/uefaeuro/season=2012/teams/team=([0-9]+)/index.html', team['href']).group(1) team_stored.put() return team_stored
def listTeam(cityid, schoolid): # Список городов и их дочерних школ, название текущего города и школы listCity = City.select().order_by(City.cityName) listSchool = School.select().join(City).where(City.city_ID == cityid).order_by(School.schoolName) try: cityname = City.get(city_ID = cityid).cityName schoolname = School.get(school_ID = schoolid).schoolName except DoesNotExist: cityname = None schoolname = None # Список команд в выбранной школе listTeam = Team.select().join(School).where(School.school_ID == schoolid).join(City).where(City.city_ID == cityid).switch(Team).join(Age).order_by(Team.teamName) for lt in listTeam: lt.age_ID.ageName = int(date.today().year) - int(lt.age_ID.ageName) # Список возрастов по состоянию на текущий год listAge = Age.select().order_by(Age.ageName) for age in listAge: age.ageName = int(date.today().year) - int(age.ageName) # Переменные для автозаполнения модальной формы добавления/обновления данных в JS-скрипте шаблона ## Список полей modifyFields = ['teamName', 'filterAge', 'ageName'] ## Список групп радиокнопок modifyRadios = ['filterAge'] ## Заголовки модального окна createHeader = ['"Создать новую юношескую команду"'] updateHeader = ['"Изменить "', 'teamName', '" (возраст "', 'ageName', '")"'] ## Действия формы createAction = ['"/city/"', cityid, '"/school/"', schoolid, '"/team/create"'] updateAction = ['"/city/"', cityid, '"/school/"', schoolid, '"/team/"', 'PK_ID', '"/update"'] deleteAction = ['"/city/"', cityid, '"/school/"', schoolid, '"/team/"', 'PK_ID', '"/delete"'] # Вывод шаблона return render_template( 'Team.jinja.html', listCity = listCity, cityid = cityid, cityname = cityname, listSchool = listSchool, schoolid = schoolid, schoolname = schoolname, listTeam = listTeam, listAge = listAge, modifyFields = modifyFields, modifyRadios = modifyRadios, createHeader = createHeader, updateHeader = updateHeader, createAction = createAction, updateAction = updateAction, deleteAction = deleteAction)
def init_team(self, team): """Create team if not exists.""" team_stored = Team.all().filter('name =',team['name']).get() if team_stored is None: team_stored = Team(name=team['name']) short_match = re.search(r'([a-z]{3})\.gif$',team['flag']) team_stored.flag = team['flag'] team_stored.short = short_match.group(1) team_stored.href = team['href'] team_stored.put() return team_stored
def get(self): current_user = users.get_current_user() votes = Votes.for_user(current_user) team_comments = {} user_comments = {} if shouldShowComments(): comments = Comment.all() for comment in comments: team_key = str(comment.team.key()) comment.author_name = generateCommentAuthorName(comment) if not team_key in team_comments: team_comments[team_key] = [] if comment.user == current_user: user_comments[team_key] = comment team_comments[team_key].append(comment) all_teams = filter_hidden(Team.all().fetch(1000)) for team in all_teams: team.voted = (team.key() in votes.local_teams or team.key() in votes.teams) team_key = str(team.key()) if shouldShowComments(): if team_key in team_comments: team.comments = team_comments[team_key] if team_key in user_comments: team.user_comment = user_comments[team_key].text logout_url = users.create_logout_url("/") winning_teams = filter(lambda x: config['highlight_winners'] and x.annotation is not None and x.annotation != '', all_teams) all_teams = filter(lambda x: x not in winning_teams, all_teams) # Disable randomness for commenting always if config["list_teams_randomly"] and not shouldEnableCommenting(): random.shuffle(all_teams) random.shuffle(winning_teams) self.render('list', { 'teams': all_teams, 'winning_teams': winning_teams, 'votes': votes, 'team_comments': team_comments, 'user_comments': user_comments, 'highlight_winners': config['highlight_winners'], 'enable_voting': config['enable_voting'], 'enable_commenting': shouldEnableCommenting(), 'show_winner_entry': config['show_winner_entry'], 'logout_url': logout_url })
def get(self): team_key = self.request.get('team_key') team = Team.get(team_key) votes = Votes.for_user(users.get_current_user()) team.voted = (team.key() in votes.local_teams or team.key() in votes.teams) enable_commenting = False user_is_owner = users.get_current_user() == team.user if config["enable_owner_commenting"] and user_is_owner: enable_commenting = True if config['show_comments']: team.comments = list(Comment.get_team_comments(team)) for comment in team.comments: comment.author_name = generateCommentAuthorName(comment) self.render('team', { 'team': team, 'show_comments': config['show_comments'], 'enable_commenting': enable_commenting })
def get(self): current_user = users.get_current_user() votes = Votes.for_user(current_user) team_comments = {} user_comments = {} if shouldShowComments(): comments = Comment.all() for comment in comments: team_key = str(comment.team.key()) comment.author_name = comment.user.nickname().split('@', 1)[0] if not team_key in team_comments: team_comments[team_key] = [] if comment.user == current_user: user_comments[team_key] = comment team_comments[team_key].append(comment) all_teams = Team.all().fetch(1000) for team in all_teams: team.voted = (team.key() in votes.local_teams or team.key() in votes.teams) team_key = str(team.key()) if shouldShowComments(): if team_key in team_comments: team.comments = team_comments[team_key] if team_key in user_comments: team.user_comment = user_comments[team_key].text logout_url = users.create_logout_url("/") # Disable randomness for commenting always if config["list_teams_randomly"] and not shouldEnableCommenting(): random.shuffle(all_teams) self.render('list', { 'teams': all_teams, 'votes': votes, 'team_comments': team_comments, 'user_comments': user_comments, 'enable_voting': config['enable_voting'], 'enable_commenting': shouldEnableCommenting(), 'logout_url': logout_url })
def updateTeam(cityid, schoolid, teamid): # Получение полей формы из шаблона teamname = request.form['teamName'] ageid = request.form['filterAge'] # Обновление текущей записи в БД if session['demo']: pass else: team = Team() team.team_ID = teamid team.school_ID = schoolid team.age_ID = ageid team.teamName = teamname team.save() # Редирект на вид list return redirect( url_for('listTeam', cityid = cityid, schoolid = schoolid, teamid = teamid))
def get(self): existing = Team.for_user(users.get_current_user()) self.render('add', { 'existing': existing })
def get(self): team_key = self.request.get('team_key') team = Team.get(team_key) votes = Votes.for_user(users.get_current_user()) team.voted = (team.key() in votes.local_teams or team.key() in votes.teams) self.render('team', { 'team': team })
def test_basics(self): team = Team() team.id = 1 team.code = 'MAR' team.name = "Martian War Machines" team.name_full = "Martian War Machines" team.name_brief = "Mars" self.session.add(team) team2 = Team() team2.id = 2 team2.code = 'VEN' team2.name = "Venusian Pressure Cookers" team2.name_full = "Venusian Pressure Cookers" team2.name_brief = "Venus" self.session.add(team2) self.session.flush()
def listSAST(seasonid, ageid, sasid): # Список сезонов и возрастов по состоянию на текущий год, название текущего сезона и возраста, название и тип игровой стадии текущего игрового этапа listSeason = Season.select().order_by(Season.season_ID.asc()) listAge = Age.select().order_by(Age.ageName) for age in listAge: age.ageName = int(date.today().year) - int(age.ageName) try: seasonname = Season.get(season_ID = seasonid).seasonName agename = Age.get(age_ID = ageid).ageName sasname = SAS.get(SAS_ID = sasid).stage_ID.stageName sastype = SAS.get(SAS_ID = sasid).stage_ID.stageType except DoesNotExist: seasonname = None agename = None sasname = None sastype = None # Список игровых этапов по типам listSAS_Z = SAS.select().where(SAS.season_ID == seasonid, SAS.age_ID == ageid).join(Stage).where(Stage.stageType == "Z").order_by(Stage.stageName) listSAS_G = SAS.select().where(SAS.season_ID == seasonid, SAS.age_ID == ageid).join(Stage).where(Stage.stageType == "G").order_by(Stage.stageName) listSAS_P = SAS.select().where(SAS.season_ID == seasonid, SAS.age_ID == ageid).join(Stage).where(Stage.stageType == "P").order_by(Stage.stageName) # Список городов, спортивных школ и команд для фильтрации по связанным выпадающим спискам filterCity = City.select().order_by(City.cityName) filterSchool = School.select().order_by(School.schoolName) filterTeam = Team.select().order_by(Team.teamName) # Список команд в текущем игровом этапе listSAST = SAST.select().where(SAST.SAS_ID == sasid).join(Stage, JOIN_LEFT_OUTER).order_by(SAST.SAST_ID) # Список игровых стадий listStage = Stage.select().order_by(Stage.stageType, Stage.stageName).order_by(Stage.stage_ID) # Есть ли в текущем игровом этапе подгруппы is_SASTsubstage = SAST.select().where(SAST.SAS_ID == sasid).join(Stage).exists() # Список подгрупп текущего игрового этапа (если они есть) listSASTsubstage = SAST.select(SAST.substage_ID).distinct().where(SAST.SAS_ID == sasid).join(Stage, JOIN_LEFT_OUTER) # Переменные для автозаполнения формы добавления/обновления данных в JS-скрипте шаблона ## Список полей modifyFields = ['filterCity', 'filterSchool', 'filterTeam', 'substage_ID', 'stageType', 'stageName'] ## Список групп радиокнопок modifyRadios = ['substage_ID'] ## Список выпадающих списков modifySelect = ['filterCity', 'filterSchool', 'filterTeam'] ## Заголовки модального окна createHeader = ['"Добавить команду в "', 'stageType', '" "', 'stageName'] updateHeader = ['"Изменить команду, участвующую в "', 'stageType', '" "', 'stageName'] ## Действия формы createAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', sasid, '"/team/create"'] updateAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', sasid, '"/team/"', 'PK_ID', '"/update"'] deleteAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', sasid, '"/team/"', 'PK_ID', '"/delete"'] # Вывод шаблона return render_template( 'SAST.jinja.html', listSeason = listSeason, seasonid = seasonid, seasonname = seasonname, listAge = listAge, ageid = ageid, agename = agename, listSAS_Z = listSAS_Z, listSAS_G = listSAS_G, listSAS_P = listSAS_P, sasid = sasid, sasname = sasname, sastype = sastype, filterCity = filterCity, filterSchool = filterSchool, filterTeam = filterTeam, listSAST = listSAST, listStage = listStage, is_SASTsubstage = is_SASTsubstage, listSASTsubstage = listSASTsubstage, modifyFields = modifyFields, modifyRadios = modifyRadios, modifySelect = modifySelect, createHeader = createHeader, updateHeader = updateHeader, createAction = createAction, updateAction = updateAction, deleteAction = deleteAction)
def post(self): team = Team.for_user(users.get_current_user()) if not team: team = Team() team.name = self.request.get('name') team.people = self.request.get('people') location = self.request.get('location') team.location = self.request.get('location') if location == 'Other': team.location = self.request.get('otherLocation') team.description = self.request.get('description') team.url = self.request.get('url') team.video = self.request.get('video') team.image = self.request.get('image') team.winner = self.request.get('winner') team.email = self.request.get('email') team.votes = 0 team.hackday = '092011' team.user = users.get_current_user() team.put() self.render('add_received', { })
def team_process(self, f): pattern = r""" <td>(\d+)</td> # rank <td>([A-Za-z. (),_]+)</td> # name .* # rest of the line <td>(\d+)/(\d+)</td> # attempt, problemcount """ reg = re.compile( pattern, re.VERBOSE ) rankpat = r""" [A-Za-z]+\ ([A-Za-z]+\ \d+) # weekday, month, day \ \d\d:\d\d:\d\d\ [A-Za-z]+\ (\d+) # year """ rankreg = re.compile( rankpat, re.VERBOSE ) #finding the date of the event match = rankreg.search( f ) cdate = "" if match: cdate = match.group(1) + " " + match.group(2) logging.error( cdate ) logging.error( "finding something" ) else: logging.error( "nothing found" ) bests = "" results = reg.finditer(f) rank = 0; for result in results: # picking up details rank += 1 name = result.group(2) attempts = int(result.group(3)) solved = int(result.group(4)) earned = 0 # pick up the earned points if rank <= 10 and int(solved) != 0: earned = points[ rank-1 ] if rank <= 3: if rank == 2: bests += ", " elif rank == 3: bests += " and " bests += name c = db.Query( Team ) c.filter( 'name =' , name ) teams = c.fetch(1) # updating database if len( teams ) == 0: # it was never in ranklist team = Team() team.name = name team.solve = solved team.points = earned team.contest = 1 team.attempt = attempts team.image = "img/nsu2.gif" team.accuracy = str( round(( team.solve * 100. ) / team.attempt, 2) ) team.put() else: for team in teams: # it's one object though team.solve += solved team.points += earned team.contest += 1 team.attempt += attempts team.accuracy = str( round(( team.solve * 100. ) / team.attempt,2) ) team.put() return [ bests, cdate ]