def test_participants_add_two_count(self): # add two/more participants, assert the number of participants num_participants = self.session.query(Participant).count() character_one = Character(name='Snorlax', universe='Pokemon', weight='180', moves='Rollout, Belly Drum, Heavy Slam, Yawn', debut='2004', tier='E', image_path='Snorlax.png') character_two = Character(name='Sonic', universe='Sonic', weight='95', moves='Hammer Spin Dash, Burning Spin Dash, Spring Jump, Springing Headbutt', debut='2013', tier='A', image_path='Sonic.png') tournament_one = Tournament(name='bust2', sanitized='bust2', date='April 11th, 2015', location='CA', image_path='https://images.smash.gg/images/tournament/1035/image-10e39229043ff962dd367a516b0bc090.png') tournament_two = Tournament(name='Smash Broski', sanitized='smash-broski', date='April 1, 2017', location='MA', image_path='path_to_image') participant_one = Participant(sponsor='C9', tag='mang0', main=character_one, location='California', tournament=tournament_one) participant_two = Participant(sponsor='Selfless', tag='Broseidon', main=character_two, location='Russia', tournament=tournament_two) self.object_list.append(character_one) self.object_list.append(character_two) self.object_list.append(tournament_one) self.object_list.append(tournament_two) self.object_list.append(participant_one) self.object_list.append(participant_two) self.commit_objects() self.assertEqual(self.session.query(Participant).count(), num_participants + 2)
def test_participants_add_one(self): # add a participant character = Character(name='Snorlax', universe='Pokemon', weight='180', moves='Rollout, Belly Drum, Heavy Slam, Yawn', debut='2004', tier='E', image_path='Snorlax.png') tournament = Tournament(name='bust2', sanitized='bust2', date='April 11th, 2015', location='CA', image_path='https://images.smash.gg/images/tournament/1035/image-10e39229043ff962dd367a516b0bc090.png') participant = Participant(sponsor='C9', tag='mang0', main=character, location='California', tournament=tournament) self.object_list.append(character) self.object_list.append(tournament) self.object_list.append(participant) self.commit_objects() result = self.session.query(Participant).order_by( Participant.id.desc()).first() self.assertEqual(result.sponsor, participant.sponsor) self.assertEqual(result.tag, participant.tag) self.assertEqual(result.location, participant.location) self.assertEqual(result.tournament, participant.tournament)
def join_meeting(meeting_id: str, user_session_tuple: (UserInDB, Session) = Depends(get_current_user)): user: UserInDB = user_session_tuple[0] session: Session = user_session_tuple[1] meeting = session.query(MeetingInDB).filter_by(id=meeting_id).first() number_participants = len(meeting.participants) # Limit the capacity of a meeting to six if number_participants + 1 > 6: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='The meeting is full.', ) last_joined_meeting = max([p.datetime_join for p in user.participants], default=None) # Avoid people joining two meetings in the same hour if last_joined_meeting and last_joined_meeting > datetime.now( ) - timedelta(hours=1): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='Don\'t hop meetings so fast, dude', ) new_participant = Participant(user=user, meeting=meeting, datetime_join=datetime.now()) session.add(new_participant) session.commit() return make_meeting_from_db(meeting)
def add_contacts(self): if request.method == 'POST': if not request.form.get('conference') or not request.form.get( 'profile'): flash('You must select Conference and Profile') if current_user.has_role('admin'): return redirect(url_for('contact_admin.index_view')) else: return redirect(url_for('contact_user.index_view')) conference = Conference.query.filter_by( id=request.form['conference']).first_or_404() profile = ParticipantProfile.query.filter_by( id=request.form['profile']).first_or_404() contacts = Contact.query.filter( Contact.id.in_(request.form['ids'].split(','))) for c in contacts: if Participant.query.filter_by(phone=c.phone, conference=conference).first(): flash(gettext('%(contact)s is already there.', contact=c)) continue p = Participant(phone=c.phone, name=c.name, user=current_user, profile=profile, conference=conference) flash(gettext('%(contact)s added.', contact=c)) db.session.add(p) db.session.commit() return redirect(url_for('.edit_view', id=conference.id))
def process(self, commit, *args, **kwargs): data = commit.data ## check try try: pool = Pool.objects.get(id=data["poolId"]) new_raised = int(pool.raised) + int(data.get("tokens")) pool.raised = str(new_raised) participant = pool.participants.get(lender=data["lender"]) new_joined = int(participant.balance) + int(data.get("tokens")) participant.balance = str(new_joined) commit.save() pool.save() except Pool.DoesNotExist: self.logger.warning("Pool with id {} does not exist".format( data["poolId"])) except Participant.DoesNotExist: participant = Participant() participant.lender = data["lender"] participant.balance = data["tokens"] pool.participants.append(participant) commit.save() pool.save()
def create_new_participant(db, form, hunt_id): participant = Participant() form.populate_obj(participant) participant.registered = True participant.hunt_id = hunt_id db.session.add(participant) db.session.commit()
def add_participant(request): name = request.POST.get('name') address = request.POST.get('address') phone = request.POST.get('phone') participant = Participant(name=name, address=address, phone=phone) participant.save() callback = request.GET.get("callback") return HttpResponse(callback + '(Success)')
def get_or_create_participant(corpus, attr_map, target_child=None): if not attr_map: return None age = parse_age(attr_map.get('age')) code = attr_map.get('id') name = attr_map.get('name') role = attr_map.get('role') language = attr_map.get('language') group = attr_map.get('group') sex = attr_map.get('sex') ses = attr_map.get('SES') education = attr_map.get('education') custom = attr_map.get('custom') query_set = Participant.objects.filter(code=code, name=name, role=role, corpus=corpus) # Filter participant candidates by target child if target_child: query_set = query_set.filter(target_child=target_child) participant = query_set.first() if not participant: participant = Participant( code=code, name=name, role=role, language=language, group=group, sex=sex, ses=ses, education=education, custom=custom, corpus=corpus, corpus_name=corpus.name, collection=corpus.collection, collection_name=corpus.collection.name ) if target_child: participant.target_child = target_child update_age(participant, age) # TODO very confusing. in memory attribute gets passed to child process # Mark the age for this participant for this transcript, to be saved in utterance / token as speaker_age participant.age = age participant.save() return participant
def participant(): form = ParticipantForm() if request.method == 'POST': if form.validate_on_submit(): participant = Participant(form.first_name.data, form.last_name.data, form.age.data, form.major.data, form.college_name.data, form.academic_year.data) db.session.add(participant) db.session.commit() return redirect('/photo') return render_template('participant.html', title='Participant Registration', form=form)
async def get_handler(request): participant = Participant() if request.method == 'GET': participant_list = participant.list_participants() return json({'data': participant_list}) elif request.method == 'POST': participant_ins = request.json participant.create_participant(name=participant_ins['name'], age=participant_ins['age'], city=participant_ins['city']) return json({'status': True}) else: return json({'status': False, 'message': 'method not implemented'})
def load(): """Read from csv and add to database""" with codecs.open('participants.csv', 'r', 'utf-8') as f: for line in f: line = unicode(line) try: data = line.split(',') lc = str(data[0]) name = str(data[1]) surname = str(data[2]) new_part = Participant(first_name=name, last_name=surname, lc=lc) new_part.save() except: print line
def start_exp(): """ Serves up the experiment applet. """ if not (request.args.has_key('hitId') and request.args.has_key('assignmentId') and request.args.has_key('workerId')): raise ExperimentError('hit_assign_worker_id_not_set_in_exp') hitId = request.args['hitId'] assignmentId = request.args['assignmentId'] workerId = request.args['workerId'] print hitId, assignmentId, workerId # check first to see if this hitId or assignmentId exists. if so check to see if inExp is set matches = Participant.query.\ filter(Participant.hitid == hitId).\ filter(Participant.assignmentid == assignmentId).\ filter(Participant.workerid == workerId).\ all() numrecs = len(matches) if numrecs == 0: # Choose condition and counterbalance subj_cond, subj_counter = get_random_condcount() if not request.remote_addr: myip = "UKNOWNIP" else: myip = request.remote_addr # set condition here and insert into database part = Participant(hitId, myip, assignmentId, workerId, subj_cond, subj_counter) db_session.add(part) db_session.commit() elif numrecs == 1: part = matches[0] if part.status >= STARTED: # in experiment (or later) can't restart at this point raise ExperimentError('already_started_exp') else: print "Error, hit/assignment appears in database more than once (serious problem)" raise ExperimentError('hit_assign_appears_in_database_more_than_once') return render_template('exp.html', workerId=part.workerid, assignmentId=part.assignmentid, cond=part.cond, counter=part.counterbalance)
def register(): json_data = request.get_json() if json_data: if db.session.query(Participant).filter( Participant.email == json_data.get('email')).first(): return jsonify({"status": "Already exists"}) user = Participant(**json_data) try: db.session.add(user) try: db.session.commit() except: return abort(404) except: return jsonify({"status": "error"}) usershema = ParticipantsSchema() serialized = usershema.dump(user) serialized.update(dict(password=json_data.get('password'))) return jsonify(serialized), 201 return jsonify({"status": "error"}), 500
def register(): email = request.args.get("email") name = request.args.get("name") location = request.args.get("location") about = request.args.get("about") password = request.args.get("password") if email and name and location and about and password: if db.session.query(Participant).filter( Participant.email == email).first(): return {"status": "error"} user = Participant(name=name, email=email, password=password, about=about, location=location) db.session.add(user) db.session.commit() part = ParticipantSchema() return jsonify(part.dump(user)) return {"status": "error"}
def create_mentor(payload): try: data = request.get_json() name = data.get('name', '') skills = data.get('skills', '') is_mentor = data.get('is_mentor') participant = Participant(name=name, skills=skills, is_mentor=is_mentor) participant.insert() participants = Participant.query.all() formatted_participants = pagenate(request, participants) return jsonify({ 'success': True, 'created': participant.id, 'participants': formatted_participants, 'total_participants': len(participants) }), 200 except BaseException: abort(422)
def add_participant(user_id: UUID, user_role: Role, participant: schemas.Participant): is_authorized(user_role, "add_participant") exam_id = participant.exam_id learner_id = participant.user_id exam = Exam.get(id=exam_id, user=User[user_id]) if not exam: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Exam not found : id: {}".format(exam_id)) learner = User.get(id=learner_id, role=Role.learner) if not learner: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Learner not found : id: {}".format(learner_id)) participant = Participant(exam=exam, user=learner) return participant.to_dict()
def register_user(): data = request.json user = db.session.query(Participant).filter_by( email=data.get('email')).one_or_none() if user: return jsonify({'error': 'Already exists'}) new_user_schema = ParticipantSchema() new_user = Participant(name=data.get('name'), email=data.get('email'), picture=data.get('picture'), location=data.get('location'), about=data.get('about')) new_user.password = data.get('password') db.session.add(new_user) try: db.session.commit() except: return jsonify(), 500 return jsonify(new_user_schema.dump(new_user)), 201, { 'Location': f'/login/{new_user.id}' }
def create_hunt(context): hunt = Hunt() hunt.name = uuid.uuid4().hex participant = Participant() participant.email = email() db.session.add(participant) db.session.commit() hunt.participants = [participant] item = Item() item.name = uuid.uuid4().hex db.session.add(item) db.session.commit() hunt.items = [item] hunt.admin_id = 1 # fresh db for each scenario db.session.add(hunt) db.session.commit() context.hunt = hunt
def create_meeting(hours: int, location: str, subject: str, user_session_tuple: (UserInDB, Session) = Depends(get_current_user)): user: UserInDB = user_session_tuple[0] session: Session = user_session_tuple[1] last_joined_meeting = max([p.datetime_join for p in user.participants], default=None) # Avoid people joining two meetings in the same hour if last_joined_meeting and last_joined_meeting > datetime.now( ) - timedelta(hours=1): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='Don\'t hop meetings so fast, dude', ) meeting_id = generate_meeting_id(8) now = datetime.now() later = now + timedelta(hours=hours) new_meeting = MeetingInDB( id=meeting_id, datetime_start=now, datetime_end=later, location=location, subject=subject, ) new_participant = Participant(user=user, meeting=new_meeting, datetime_join=now) session.add(new_participant) session.commit() return make_meeting_from_db(new_meeting)
def process_participant(data, roster_id, createdAt=None): test = db.session.query(Participant).get(data['id']) if not test: p = Participant(id=data['id'], roster_id=roster_id, player_id=data['relationships']['player']['data']['id'], actor=data['attributes']['actor'], kills=data['attributes']['stats']['kills'], assists=data['attributes']['stats']['assists'], deaths=data['attributes']['stats']['deaths'], jungleKills=data['attributes']['stats']['jungleKills'], crystalMineCaptures=data['attributes']['stats']['crystalMineCaptures'], goldMindCaptures=data['attributes']['stats']['goldMineCaptures'], krakenCaptures=data['attributes']['stats']['krakenCaptures'], turrentCaptures=data['attributes']['stats']['turretCaptures'], winner=data['attributes']['stats']['winner'], farm=data['attributes']['stats']['farm'], minionKills=data['attributes']['stats']['minionKills'], nonJungleMinionKills=data['attributes']['stats']['nonJungleMinionKills'], firstAfkTime=data['attributes']['stats']['firstAfkTime'], wentAfk=data['attributes']['stats']['wentAfk'], itemGrants=data['attributes']['stats']['itemGrants'], itemSells=data['attributes']['stats']['itemSells'], itemUses=data['attributes']['stats']['itemUses'], items=data['attributes']['stats']['items'], skinKey=data['attributes']['stats']['skinKey'], karmaLevel=data['attributes']['stats']['karmaLevel'], level=data['attributes']['stats']['level'], skillTier=data['attributes']['stats']['skillTier']) if createdAt: p.createdAt = createdAt db.session.add(p) try: db.session.commit() except SQLAlchemyError as e: db.session.rollback() app.logger.error('ERROR: Session rollback - reason "%s"' % str(e))
def get(self, group_key): # confirm participant id in cookie c_group_key = ChatTrait.get_group_key(self) participant_key = ChatTrait.get_participant_key(self) # get group group = Group.get(group_key) # if participant is none or login to another group, create new participant in group if not participant_key: participant = Participant() participant.store(group.key) participant_key = participant.key ChatTrait.store_participant_key(self, participant_key) if c_group_key: if c_group_key != group_key: group.participant(Participant.get(participant_key)) ChatTrait.store_group_key(self, group.key) else: ChatTrait.store_group_key(self, group.key) # return response self.render("chat.html", group_name=group.name)
def create_participant(**form_kwargs): new_participant = Participant(**form_kwargs) db.session.add(new_participant) db.session.commit() return jsonify(new_participant.as_dict())
def get_participant_for_file(path, metadata_by_pid): with open(path, "r") as data_file: reader = DictReader(data_file) blocks = [] prolific_pid = None slowdown = None keyset = None compensation = None user_agent = None current_block_responses = [] current_block_center = None compensation_descriptor = None version = None model_name = None for row in reader: prolific_pid = row.get("prolificPid") if prolific_pid in invalid_prolific_pids: raise ParticipantException(prolific_pid, "marked-invalid") if row.get("version") is None: raise ParticipantException(prolific_pid, "no-version") if row["trial_type"] == "keyset-select": keyset = row.get("chosenKeyset") if row["trial_type"] == "block-bookend" and len( current_block_responses) == 20: next_block = Block(center_azimuth=current_block_center, responses=current_block_responses) blocks.append(next_block) current_block_responses = [] if row["trial_type"] == "echo-presentation": compensation_str = row.get("compensation") if compensation_str == "NaN": compensation = 0 else: compensation = int(compensation_str) choices = list(map(int, row.get("choices").split(","))) current_block_center = choices[2] slowdown = int(row.get("slowdown")) compensation_descriptor = row.get("compensationDescriptor") true_azimuth = row.get("azimuth") user_agent = row.get("userAgent") version = row.get("version") model_name = row.get("modelName") response_azimuth = row.get("responseAzimuth") response_delay = row.get("responseDelay") filename = row.get("filename") if true_azimuth and response_azimuth: response = Response( true_azimuth=int(true_azimuth), response_azimuth=int(response_azimuth), azimuth_choices=choices, response_delay_ms=int(response_delay), filename=filename, ) current_block_responses.append(response) metadata = metadata_by_pid.get(prolific_pid) if (len(blocks) == 6 and slowdown and compensation is not None and compensation_descriptor and version and prolific_pid): return Participant( version=version, user_agent=user_agent, compensation=compensation, compensation_descriptor=compensation_descriptor, slowdown=slowdown, blocks=blocks, keyset=keyset, prolific_pid=prolific_pid, model_name=model_name, sex=metadata["sex"], age=(int(metadata["age"]) if metadata["age"] else None), ) raise ParticipantException(prolific_pid, "missing-data")
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_path = os.getenv('DATABASE_URL') setup_db(self.app, self.database_path) self.new_project = { 'name': 'Test_Project', 'description': 'This is a test project.' } self.new_participant = { 'name': 'Meeral', 'skills': 'Programming', 'is_mentor': False } self.admin_token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI' \ '6IllITVdXZjF4X19aU3FOMWd1dDVEYiJ9.eyJpc3MiO' \ 'iJodHRwczovL21lZXJhbHNmaXJzdHdlYmFwcC51cy5h' \ 'dXRoMC5jb20vIiwic3ViIjoiZ29vZ2xlLW9hdXRoMnw' \ 'xMTMxNjU3NDgyMjEzMzE3NTM1NzIiLCJhdWQiOlsibW' \ 'VudG9yc2hpcCIsImh0dHBzOi8vbWVlcmFsc2ZpcnN0d' \ '2ViYXBwLnVzLmF1dGgwLmNvbS91c2VyaW5mbyJdLCJp' \ 'YXQiOjE2MDM1MDI0ODYsImV4cCI6MTYwMzU4ODg4Niw' \ 'iYXpwIjoicGhTaWY4NXVLVTkyZDhWNXdvZGxwbXJNZE' \ 'pxd2tyM1ciLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlI' \ 'GVtYWlsIiwicGVybWlzc2lvbnMiOlsiY3JlYXRlOnBh' \ 'cnRpY2lwYW50cyIsImNyZWF0ZTpwcm9qZWN0cyIsImR' \ 'lbGV0ZTpwYXJ0aWNpcGFudHMiLCJkZWxldGU6cHJvam' \ 'VjdHMiLCJlbnJvbGw6cGFydGljaXBhbnRzIiwicmVhZ' \ 'DpwYXJ0aWNpcGFudHMiLCJyZWFkOnByb2plY3RzIl19' \ '.daW63fl2a2zVtNxWAapUhGzGA68BahYr8WP2MuRcnf' \ 'pftkRhfIOKwqTfd3UyDji4Gb39DdIHO1-QKQh7kjluM' \ 'JdekDpCfLWslIPmokpxHDOJGr98JE56cepWeE_V5XcA' \ 'pI1nh0dnXhOkDeeeb5y3upsXlROsJx-8q1HUhjZ0CAb' \ 'A0Wi3L1sYtUmpsyhbYv9PYtikZTsFv0ofaumBg9b1C6' \ '43BIpTtg08Flh3g0fnPav-Yw8wi_a4SWn3mj4zBw2E1' \ '_zA60q4sY9Hea90JrFaU_1EfGIhLpE1nDsphKe_JRqO' \ 'J6mdy3ZKfTBVnfU2qA6Lk3jY_vJsSVtIERwlL8bfnA' self.user_token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI' \ '6IllITVdXZjF4X19aU3FOMWd1dDVEYiJ9.eyJpc3MiO' \ 'iJodHRwczovL21lZXJhbHNmaXJzdHdlYmFwcC51cy5h' \ 'dXRoMC5jb20vIiwic3ViIjoiZ29vZ2xlLW9hdXRoMnw' \ 'xMDkxMjkzMzA4MTUwNzA2MzkxMzgiLCJhdWQiOlsibW' \ 'VudG9yc2hpcCIsImh0dHBzOi8vbWVlcmFsc2ZpcnN0d' \ '2ViYXBwLnVzLmF1dGgwLmNvbS91c2VyaW5mbyJdLCJp' \ 'YXQiOjE2MDM1MDI2MDYsImV4cCI6MTYwMzU4OTAwNiw' \ 'iYXpwIjoicGhTaWY4NXVLVTkyZDhWNXdvZGxwbXJNZE' \ 'pxd2tyM1ciLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlI' \ 'GVtYWlsIiwicGVybWlzc2lvbnMiOlsicmF0ZTpwYXJ0' \ 'aWNpcGFudHMiLCJyZWFkOnBhcnRpY2lwYW50cyIsInJ' \ 'lYWQ6cHJvamVjdHMiXX0.fzZkrGdTSMEbVOPYPbG28X' \ 'EOJRMyWepxjBN6IYOxFgHBG1QNiHey-61LiQFGyxA32' \ 'GwIaNyWFQ80-57tIc6s6vVnEGNxJDG0pU05D7aVsIbN' \ 'KZtt3OQ7WowmLdc1fTjd0eyQ_39zOyzn2vLJY9ytEvl' \ 'wABwXx3FeMjW1uOkF02fRc5_9xvyK6fiEAyFWJ-J14d' \ 'qFlZ49k6-jC8m9N8-8h5d96hfnuMapqLhcvrmvKvhdy' \ '-0368oWGy7-N1HULT0emHM773GF6aIODGXk1Mplf6pl' \ 'moRpHhZGb3KP024oGsGLewH8PkRHj2abvyFGcchu0y4' \ 'o-d63-M2v-gXIdA4wFw' self.admin_header = {'Authorization': 'Bearer ' + self.admin_token} self.user_header = {'Authorization': 'Bearer ' + self.user_token} # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() dummy_participant_delete = Participant( name='dummy', skills='dummy', is_mentor=True) dummy_mentor_populate = Participant( name='Meeral', skills='Programming', is_mentor=True) dummy_mentee_populate = Participant( name='Tofy', skills='Gaming', is_mentor=False) dummy_project_delete = Project(name='dummy', description='dummy') dummy_project_populate = Project(name='dummy', description='dummy') dummy_mentee_populate.projects.append(dummy_project_populate) dummy_mentor_populate.projects.append(dummy_project_populate) self.db.session.add(dummy_project_delete) self.db.session.add(dummy_project_populate) self.db.session.add(dummy_participant_delete) self.db.session.add(dummy_mentor_populate) self.db.session.add(dummy_mentee_populate) self.db.session.commit() self.deleted_participant_id = dummy_participant_delete.id self.deleted_project_id = dummy_project_delete.id self.unauthorized_delete_participant_id = dummy_mentee_populate.id self.selected_participant_id = dummy_mentor_populate.id self.selected_project_id = dummy_project_populate.id
def start_exp(): """ Serves up the experiment applet. """ if not ('hitId' in request.args and 'assignmentId' in request.args and 'workerId' in request.args): raise ExperimentError('hit_assign_worker_id_not_set_in_exp') hit_id = request.args['hitId'] assignment_id = request.args['assignmentId'] worker_id = request.args['workerId'] mode = request.args['mode'] app.logger.info("Accessing /exp: %(h)s %(a)s %(w)s " % { "h": hit_id, "a": assignment_id, "w": worker_id }) if hit_id[:5] == "debug": debug_mode = True else: debug_mode = False # Check first to see if this hitId or assignmentId exists. If so, check to # see if inExp is set matches = Participant.query.\ filter(Participant.workerid == worker_id).\ all() numrecs = len(matches) if numrecs == 0: # Choose condition and counterbalance subj_cond, subj_counter = get_random_condcount() worker_ip = "UNKNOWN" if not request.remote_addr else \ request.remote_addr browser = "UNKNOWN" if not request.user_agent.browser else \ request.user_agent.browser platform = "UNKNOWN" if not request.user_agent.platform else \ request.user_agent.platform language = "UNKNOWN" if not request.user_agent.language else \ request.user_agent.language # Set condition here and insert into database. participant_attributes = dict(assignmentid=assignment_id, workerid=worker_id, hitid=hit_id, cond=subj_cond, counterbalance=subj_counter, ipaddress=worker_ip, browser=browser, platform=platform, language=language) part = Participant(**participant_attributes) db_session.add(part) db_session.commit() else: # A couple possible problems here: # 1: They've already done an assignment, then we should tell them they # can't do another one # 2: They've already worked on this assignment, and got too far to # start over. # 3: They're in the database twice for the same assignment, that should # never happen. # 4: They're returning and all is well. nrecords = 0 for record in matches: other_assignment = False if record.assignmentid != assignment_id: other_assignment = True else: nrecords += 1 if nrecords <= 1 and not other_assignment: part = matches[0] # In experiment (or later) can't restart at this point if part.status >= STARTED and not debug_mode: raise ExperimentError('already_started_exp') else: if nrecords > 1: app.logger.error("Error, hit/assignment appears in database \ more than once (serious problem)") raise ExperimentError( 'hit_assign_appears_in_database_more_than_once') if other_assignment: raise ExperimentError('already_did_exp_hit') if mode == 'sandbox' or mode == 'live': # If everything goes ok here relatively safe to assume we can lookup # the ad. ad_id = get_ad_via_hitid(hit_id) if ad_id != "error": if mode == "sandbox": ad_server_location = 'https://sandbox.ad.psiturk.org/complete/'\ + str(ad_id) elif mode == "live": ad_server_location = 'https://ad.psiturk.org/complete/' +\ str(ad_id) else: raise ExperimentError('hit_not_registered_with_ad_server') else: ad_server_location = '/complete' return render_template('exp.html', uniqueId=part.uniqueid, condition=part.cond, counterbalance=part.counterbalance, adServerLoc=ad_server_location, mode=mode)
def test_run_rogers(self): """ SIMULATE ROGERS """ hit_id = str(random.random()) overall_start_time = timenow() print("Running simulated experiment...", end="\r") sys.stdout.flush() exp_setup_start = timenow() exp = RogersExperiment(self.db) exp_setup_stop = timenow() exp_setup_start2 = timenow() exp = RogersExperiment(self.db) exp_setup_stop2 = timenow() p_ids = [] p_times = [] dum = timenow() assign_time = dum - dum process_time = dum - dum while exp.networks(full=False): num_completed_participants = len(exp.networks()[0].nodes(type=Agent)) if p_times: print("Running simulated experiment... participant {} of {}, {} participants failed. Prev time: {}".format( num_completed_participants+1, exp.networks()[0].max_size, len(exp.networks()[0].nodes(failed=True)), p_times[-1]), end="\r") else: print("Running simulated experiment... participant {} of {}, {} participants failed.".format( num_completed_participants+1, exp.networks()[0].max_size, len(exp.networks()[0].nodes(failed=True))), end="\r") sys.stdout.flush() worker_id = str(random.random()) assignment_id = str(random.random()) from models import Participant p = Participant(workerid=worker_id, assignmentid=assignment_id, hitid=hit_id) self.db.add(p) self.db.commit() p_id = p.uniqueid p_ids.append(p_id) p_start_time = timenow() while True: assign_start_time = timenow() network = exp.get_network_for_participant(participant=p) if network is None: break else: agent = exp.create_node( participant_id=p_id, network=network) exp.add_node_to_network( participant_id=p_id, node=agent, network=network) self.db.commit() exp.node_post_request(participant_id=p_id, node=agent) self.db.commit() assign_stop_time = timenow() assign_time += (assign_stop_time - assign_start_time) process_start_time = timenow() agent.receive() from operator import attrgetter current_state = max(State.query.filter_by(network_id=agent.network_id).all(), key=attrgetter('creation_time')).contents if float(current_state) >= 0.5: right_answer = "blue" wrong_answer = "yellow" else: right_answer = "yellow" wrong_answer = "blue" if num_completed_participants == 0: info = Meme(origin=agent, contents=right_answer) else: if random.random() < 0.9: info = Meme(origin=agent, contents=right_answer) else: info = Meme(origin=agent, contents=wrong_answer) self.db.commit() exp.info_post_request( node=agent, info=info) #print("state: {}, answer: {}, score: {}, fitness {}".format(current_state, info.contents, agent.score, agent.fitness)) process_stop_time = timenow() process_time += (process_stop_time - process_start_time) worked = exp.data_check(participant=p) assert worked bonus = exp.bonus(participant=p) assert bonus >= 0 assert bonus <= 1 attended = exp.attention_check(participant=p) if not attended: participant_nodes = models.Node.query\ .filter_by(participant_id=p_id, failed=False)\ .all() p.status = 102 for node in participant_nodes: node.fail() self.db.commit() else: exp.submission_successful(participant=p) p_stop_time = timenow() p_times.append(p_stop_time - p_start_time) print("Running simulated experiment... done! ") sys.stdout.flush() overall_stop_time = timenow() assert len(exp.networks()) == exp.practice_repeats + exp.experiment_repeats """ TEST NODES """ print("Testing nodes...", end="\r") sys.stdout.flush() for network in [exp.networks()[0]]: agents = network.nodes(type=Agent) assert len(agents) == network.max_size source = network.nodes(type=Source) assert len(source) == 1 source = source[0] assert type(source) == RogersSource environment = network.nodes(type=Environment) assert len(environment) == 1 environment = environment[0] assert type(environment) == RogersEnvironment vectors = network.vectors() role = network.role if role == "practice": for agent in agents: assert type(agent) == RogersAgentFounder elif role == "catch": for agent in agents: assert type(agent) == RogersAgentFounder else: for agent in agents: if agent.generation == 0: assert type(agent) == RogersAgentFounder else: assert type(agent) == RogersAgent for agent in agents: if agent.generation == 0: assert len(agent.vectors(direction="incoming")) == 2 assert agent.is_connected(direction="from", whom=source) assert agent.is_connected(direction="from", whom=environment) else: assert len(agent.vectors(direction="incoming")) in [2, 3] assert not agent.is_connected(direction="from", whom=source) assert agent.is_connected(direction="from", whom=environment) assert RogersAgent in [type(a) for a in agent.neighbors(direction="from")] or\ RogersAgentFounder in [type(a) for a in agent.neighbors(direction="from")] print("Testing nodes... done!") sys.stdout.flush() """ TEST VECTORS """ print("Testing vectors...", end="\r") sys.stdout.flush() for network in [exp.networks()[0]]: agents = network.nodes(type=Agent) vectors = network.vectors() source = network.nodes(type=Source)[0] environment = network.nodes(type=Environment)[0] for v in vectors: if isinstance(v.origin, Agent): assert v.origin.generation == v.destination.generation - 1 else: assert isinstance(v.origin, Source) or isinstance(v.origin, Environment) for agent in agents: if agent.generation == 0: assert len(models.Vector.query.filter_by(origin_id=source.id, destination_id=agent.id).all()) == 1 else: assert len(models.Vector.query.filter_by(origin_id=source.id, destination_id=agent.id).all()) == 0 for agent in agents: assert len([v for v in vectors if v.origin_id == environment.id and v.destination_id == agent.id]) == 1 for v in [v for v in vectors if v.origin_id == source.id]: assert isinstance(v.destination, RogersAgentFounder) print("Testing vectors... done!") sys.stdout.flush() """ TEST INFOS """ print("Testing infos...", end="\r") sys.stdout.flush() for network in [exp.networks()[0]]: agents = network.nodes(type=Agent) vectors = network.vectors() source = network.nodes(type=Source)[0] environment = network.nodes(type=Environment)[0] infos = network.infos() for agent in agents: assert len([i for i in infos if i.origin_id == agent.id]) == 2 assert len([i for i in infos if i.origin_id == agent.id and isinstance(i, Gene)]) == 1 assert len([i for i in infos if i.origin_id == agent.id and isinstance(i, LearningGene)]) == 1 assert len([i for i in infos if i.origin_id == agent.id and isinstance(i, Meme)]) == 1 print("Testing infos... done!") sys.stdout.flush() """ TEST TRANSMISSIONS """ print("Testing transmissions...", end="\r") sys.stdout.flush() for network in [exp.networks()[0]]: agents = network.nodes(type=Agent) vectors = network.vectors() source = network.nodes(type=Source)[0] environment = network.nodes(type=Environment)[0] infos = network.infos() transmissions = network.transmissions() for agent in agents: in_ts = [t for t in transmissions if t.destination_id == agent.id] types = [type(t.info) for t in in_ts] assert len(in_ts) == 2 assert len([t for t in transmissions if t.destination_id == agent.id and t.status == "pending"]) == 0 lg = [i for i in infos if i.origin_id == agent.id and isinstance(i, LearningGene)] assert len(lg) == 1 lg = lg[0] if lg.contents == "asocial": assert State in types assert LearningGene in types assert Meme not in types else: assert State not in types assert LearningGene in types assert Meme in types print("Testing transmissions... done!") """ TEST FITNESS """ print("Testing fitness...", end="\r") sys.stdout.flush() p0_nodes = models.Node.query.filter_by(participant_id=p_ids[0]).all() assert len(p0_nodes) == len(exp.networks()) is_asocial = True e = 2 b = 1 c = 0.3*b baseline = c+0.0001 for n in p0_nodes: assert n.fitness == (baseline + 1 * b - is_asocial * c) ** e for network in [exp.networks()[0]]: agents = network.nodes(type=Agent) for agent in agents: is_asocial = agent.infos(type=LearningGene)[0].contents == "asocial" assert agent.fitness == ((baseline + agent.score*b - is_asocial*c) ** e) print("Testing fitness... done!") sys.stdout.flush() """ TEST BONUS """ print("Testing bonus payments...", end="\r") sys.stdout.flush() assert exp.bonus(participant=Participant.query.filter_by(uniqueid=p_ids[0]).all()[0]) == exp.bonus_payment print("Testing bonus payments... done!") sys.stdout.flush() print("All tests passed: good job!") print("Timings:") overall_time = overall_stop_time - overall_start_time print("Overall time to simulate experiment: {}".format(overall_time)) setup_time = exp_setup_stop - exp_setup_start print("Experiment setup(): {}".format(setup_time)) print("Experiment load: {}".format(exp_setup_stop2 - exp_setup_start2)) print("Participant assignment: {}".format(assign_time)) print("Participant processing: {}".format(process_time)) for i in range(len(p_times)): if i == 0: total_time = p_times[i] else: total_time += p_times[i] print("Participant {}: {}, total: {}".format(i, p_times[i], total_time)) print("#########") test = [p.total_seconds() for p in p_times] print(test)
def test_participants_add_two_validate_data(self): # add a participant, assertEqual for Gamertag, Profile Pic, Real Name, # Main, Location num_participants = self.session.query(Participant).count() character_one = Character(name='Snorlax', universe='Pokemon', weight='180', moves='Rollout, Belly Drum, Heavy Slam, Yawn', debut='2004', tier='E', image_path='Snorlax.png') character_two = Character(name='Sonic', universe='Sonic', weight='95', moves='Hammer Spin Dash, Burning Spin Dash, Spring Jump, Springing Headbutt', debut='2013', tier='A', image_path='Sonic.png') tournament_one = Tournament(name='bust2', sanitized='bust2', date='April 11th, 2015', location='CA', image_path='https://images.smash.gg/images/tournament/1035/image-10e39229043ff962dd367a516b0bc090.png') tournament_two = Tournament(name='Smash Broski', sanitized='smash-broski', date='April 1, 2017', location='MA', image_path='path_to_image') participant_one = Participant(sponsor='C9', tag='mang0', main=character_one, location='California', tournament=tournament_one) participant_two = Participant(sponsor='Selfless', tag='Broseidon', main=character_two, location='Russia', tournament=tournament_two) participants = [] participants.append(participant_one) participants.append(participant_two) self.object_list.append(character_one) self.object_list.append(character_two) self.object_list.append(tournament_one) self.object_list.append(tournament_two) self.object_list.append(participant_two) self.object_list.append(participant_one) self.commit_objects() for i in range(0, 2): result = self.session.query(Participant).order_by( Participant.id.desc()).first() self.assertEqual(result.tag, participants[i].tag) self.assertEqual(result.sponsor, participants[i].sponsor) self.assertEqual(result.tag, participants[i].tag) self.assertEqual(result.main, participants[i].main) self.assertEqual(result.location, participants[i].location) self.assertEqual(result.tournament, participants[i].tournament) # Removing current element from the table self.session.delete(result) self.session.commit() self.object_list.remove(result)
def init(): db.drop_all() db.create_all() # Create roles user_datastore.create_role(name='admin', description='System administrator') user_datastore.create_role(name='user', description='Conference user') admin = user_datastore.create_user( username='******', password=utils.encrypt_password('admin')) user = user_datastore.create_user(username='******', password=utils.encrypt_password('user')) user_datastore.add_role_to_user(admin, 'admin') user_datastore.add_role_to_user(user, 'user') contacts = [ ('1010', gettext('John Smith')), ('1020', gettext('Sam Brown')), ] for c in contacts: rec = Contact(phone=c[0], name=c[1], user=admin) db.session.add(rec) guest_user_profile = ParticipantProfile(name=gettext('Guest'), startmuted=True) db.session.add(guest_user_profile) marked_user_profile = ParticipantProfile(name=gettext('Marker'), marked=True) db.session.add(marked_user_profile) admin_user_profile = ParticipantProfile(name=gettext('Administrator'), admin=True) db.session.add(admin_user_profile) conf_profile = ConferenceProfile(name=gettext('Default')) db.session.add(conf_profile) conf = Conference( number=100, name=gettext('Test Conference'), conference_profile=conf_profile, public_participant_profile=guest_user_profile, is_public=True, user=admin, ) db.session.add(conf) p1 = Participant(conference=conf, profile=admin_user_profile, phone='1001', user=admin) p2 = Participant(conference=conf, profile=guest_user_profile, phone='1002', user=admin) p3 = Participant(conference=conf, profile=marked_user_profile, phone='1003', user=admin) db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.commit()
def new_participant(email): p = Participant() p.email = email return p
def construct_objects(replay_file, pro = False): try: replay = sc2reader.load_replay(replay_file) game = db.session.query(Game).filter_by(name = str(replay.date) + '_' + replay.players[0].play_race + ' v ' + replay.players[1].play_race + '_' + replay.players[0].name + ' v ' + replay.players[1].name).first() if game != None: #print('Game already exists: ', game) return None game = Game(name = str(replay.date) + '_' + replay.players[0].play_race + ' v ' + replay.players[1].play_race + '_' + replay.players[0].name + ' v ' + replay.players[1].name, map = replay.map_name, game_winner = replay.winner.players[0].name, start_time = replay.start_time, end_time = replay.end_time, category = replay.category, expansion = replay.expansion, time_zone = replay.time_zone ) userOne = db.session.query(User).filter_by(name = replay.players[0].name).first() userTwo = db.session.query(User).filter_by(name = replay.players[1].name).first() if userOne == None: userOne = User(name = replay.players[0].name, region = replay.players[0].region, subregion = replay.players[0].subregion) if userTwo == None: userTwo = User(name = replay.players[1].name, region = replay.players[1].region, subregion = replay.players[1].subregion) users = [userOne, userTwo] if replay.players[0].is_human: highest_league_playerOne = replay.players[0].highest_league avg_apm_playerOne = replay.players[0].avg_apm if pro: highest_league_playerOne = 20 else: highest_league_playerOne = -1 avg_apm_playerOne = -1 if replay.players[1].is_human: highest_league_playerTwo = replay.players[1].highest_league avg_apm_playerTwo = replay.players[1].avg_apm if pro: highest_league_playerTwo = 20 else: highest_league_playerTwo = -1 avg_apm_playerTwo = -1 participantOne = Participant(user = [users[0]], game = [game], name = userOne.name, league = highest_league_playerOne, scaled_rating = replay.raw_data['replay.initData']['user_initial_data'][0]['scaled_rating'], playrace = replay.players[0].play_race, avg_apm = avg_apm_playerOne, winner = userOne.name == replay.winner.players[0].name ) participantTwo = Participant(user = [users[1]], game = [game], name = userTwo.name, league = highest_league_playerTwo, scaled_rating = replay.raw_data['replay.initData']['user_initial_data'][1]['scaled_rating'], playrace = replay.players[0].play_race, avg_apm = avg_apm_playerTwo, winner = userTwo.name == replay.winner.players[0].name ) participants = [participantOne, participantTwo] events = replay.events participantOne_events = [] participantTwo_events = [] for event in events: try: if event.name == 'PlayerStatsEvent': if event.player.name == participants[0].name: participantOne_events.append(PlayerStatsEvent(participant = participants[0], name = event.name, second = event.second, minerals_current = event.minerals_current, vespene_current = event.vespene_current, minerals_collection_rate = event.minerals_collection_rate, vespene_collection_rate = event.vespene_collection_rate, workers_active_count = event.workers_active_count, minerals_used_in_progress_army = event.minerals_used_in_progress_army, minerals_used_in_progress_economy = event.minerals_used_in_progress_economy, minerals_used_in_progress_technology = event.minerals_used_in_progress_technology, minerals_used_in_progress = event.minerals_used_in_progress, vespene_used_in_progress_army = event.vespene_used_in_progress_army, vespene_used_in_progress_economy = event.vespene_used_in_progress_economy, vespene_used_in_progress_technology = event.vespene_used_in_progress_technology, vespene_used_in_progress = event.vespene_used_in_progress, resources_used_in_progress = event.resources_used_in_progress, minerals_used_current_army = event.minerals_used_current_army, minerals_used_current_economy = event.minerals_used_current_economy, minerals_used_current_technology = event.minerals_used_current_technology, minerals_used_current = event.minerals_used_current, vespene_used_current_army = event.vespene_used_current_army, vespene_used_current_economy = event.vespene_used_current_economy, vespene_used_current_technology = event.vespene_used_current_technology, vespene_used_current = event.vespene_used_current, resources_used_current = event.resources_used_current, minerals_lost_army = event.minerals_lost_army, minerals_lost_economy = event.minerals_lost_economy, minerals_lost_technology = event.minerals_lost_technology, minerals_lost = event.minerals_lost, vespene_lost_army = event.vespene_lost_army, vespene_lost_economy = event.vespene_lost_economy, vespene_lost_technology = event.vespene_lost_technology, vespene_lost = event.vespene_lost, resources_lost = event.resources_lost, minerals_killed_army = event.minerals_killed_army, minerals_killed_economy = event.minerals_killed_economy, minerals_killed_technology = event.minerals_killed_technology, minerals_killed = event.minerals_killed, vespene_killed_army = event.vespene_killed_army, vespene_killed_economy = event.vespene_killed_economy, vespene_killed_technology = event.vespene_killed_technology, vespene_killed = event.vespene_killed, resources_killed = event.resources_killed, food_used = event.food_used, food_made = event.food_made, minerals_used_active_forces = event.minerals_used_active_forces, vespene_used_active_forces = event.vespene_used_active_forces, ff_minerals_lost_army = event.ff_minerals_lost_army, ff_minerals_lost_economy = event.ff_minerals_lost_economy, ff_minerals_lost_technology = event.ff_minerals_lost_technology, ff_vespene_lost_army = event.ff_vespene_lost_army, ff_vespene_lost_economy = event.ff_vespene_lost_economy, ff_vespene_lost_technology = event.ff_vespene_lost_technology )) else: participantTwo_events.append(PlayerStatsEvent(participant = participants[1], name = event.name, second = event.second, minerals_current = event.minerals_current, vespene_current = event.vespene_current, minerals_collection_rate = event.minerals_collection_rate, vespene_collection_rate = event.vespene_collection_rate, workers_active_count = event.workers_active_count, minerals_used_in_progress_army = event.minerals_used_in_progress_army, minerals_used_in_progress_economy = event.minerals_used_in_progress_economy, minerals_used_in_progress_technology = event.minerals_used_in_progress_technology, minerals_used_in_progress = event.minerals_used_in_progress, vespene_used_in_progress_army = event.vespene_used_in_progress_army, vespene_used_in_progress_economy = event.vespene_used_in_progress_economy, vespene_used_in_progress_technology = event.vespene_used_in_progress_technology, vespene_used_in_progress = event.vespene_used_in_progress, resources_used_in_progress = event.resources_used_in_progress, minerals_used_current_army = event.minerals_used_current_army, minerals_used_current_economy = event.minerals_used_current_economy, minerals_used_current_technology = event.minerals_used_current_technology, minerals_used_current = event.minerals_used_current, vespene_used_current_army = event.vespene_used_current_army, vespene_used_current_economy = event.vespene_used_current_economy, vespene_used_current_technology = event.vespene_used_current_technology, vespene_used_current = event.vespene_used_current, resources_used_current = event.resources_used_current, minerals_lost_army = event.minerals_lost_army, minerals_lost_economy = event.minerals_lost_economy, minerals_lost_technology = event.minerals_lost_technology, minerals_lost = event.minerals_lost, vespene_lost_army = event.vespene_lost_army, vespene_lost_economy = event.vespene_lost_economy, vespene_lost_technology = event.vespene_lost_technology, vespene_lost = event.vespene_lost, resources_lost = event.resources_lost, minerals_killed_army = event.minerals_killed_army, minerals_killed_economy = event.minerals_killed_economy, minerals_killed_technology = event.minerals_killed_technology, minerals_killed = event.minerals_killed, vespene_killed_army = event.vespene_killed_army, vespene_killed_economy = event.vespene_killed_economy, vespene_killed_technology = event.vespene_killed_technology, vespene_killed = event.vespene_killed, resources_killed = event.resources_killed, food_used = event.food_used, food_made = event.food_made, minerals_used_active_forces = event.minerals_used_active_forces, vespene_used_active_forces = event.vespene_used_active_forces, ff_minerals_lost_army = event.ff_minerals_lost_army, ff_minerals_lost_economy = event.ff_minerals_lost_economy, ff_minerals_lost_technology = event.ff_minerals_lost_technology, ff_vespene_lost_army = event.ff_vespene_lost_army, ff_vespene_lost_economy = event.ff_vespene_lost_economy, ff_vespene_lost_technology = event.ff_vespene_lost_technology )) elif event.name == 'UnitBornEvent': if event.unit_controller.name == participants[0].name: participantOne_events.append(UnitBornEvent(participant = participants[0], name = event.name, second = event.second, unit_type_name = event.unit_type_name, loc_x = event.x, loc_y = event.y )) else: participantTwo_events.append(UnitBornEvent(participant = participants[1], name = event.name, second = event.second, unit_type_name = event.unit_type_name, loc_x = event.x, loc_y = event.y )) elif event.name == 'UnitTypeChangeEvent': if event.unit.owner.name == participants[0].name: participantOne_events.append(UnitTypeChangeEvent(participant = participants[0], name = event.name, second = event.second, unit = event.unit.name, unit_type_name = event.unit_type_name )) else: participantTwo_events.append(UnitTypeChangeEvent(participant = participants[1], name = event.name, second = event.second, unit = event.unit.name, unit_type_name = event.unit_type_name )) elif event.name == 'UpgradeCompleteEvent': if event.player.name == participants[0].name: participantOne_events.append(UpgradeCompleteEvent(participant = participants[0], name = event.name, second = event.second, upgrade_type_name = event.upgrade_type_name )) else: participantTwo_events.append(UpgradeCompleteEvent(participant = participants[1], name = event.name, second = event.second, upgrade_type_name = event.upgrade_type_name )) elif event.name == 'UnitInitEvent': if event.unit_controller.name == participants[0].name: participantOne_events.append(UnitInitEvent(participant = participants[0], name = event.name, second = event.second, unit_type_name = event.unit_type_name, loc_x = event.x, loc_y = event.y )) else: participantOne_events.append(UnitInitEvent(participant = participants[1], name = event.name, second = event.second, unit_type_name = event.unit_type_name, loc_x = event.x, loc_y = event.y )) elif event.name == 'UnitDoneEvent': if event.unit.owner.name == participants[0].name: participantOne_events.append(UnitDoneEvent(participant = participants[0], name = event.name, second = event.second, unit = event.unit.name )) else: participantTwo_events.append(UnitDoneEvent(participant = participants[1], name = event.name, second = event.second, unit = event.unit.name )) elif event.name == 'BasicCommandEvent': if event.player.name == participants[0].name: participantOne_events.append(BasicCommandEvent(participant = participants[0], name = event.name, second = event.second, ability_name = event.ability_name )) else: participantTwo_events.append(BasicCommandEvent(participant = participants[1], name = event.name, second = event.second, ability_name = event.ability_name )) elif event.name == 'TargetPointCommandEvent': if event.player.name == participants[0].name: participantOne_events.append(TargetPointEvent(participant = participants[0], name = event.name, second = event.second, ability_name = event.ability_name, loc_x = event.x, loc_y = event.y )) else: participantTwo_events.append(TargetPointEvent(participant = participants[1], name = event.name, second = event.second, ability_name = event.ability_name, loc_x = event.x, loc_y = event.y )) elif event.name == 'UnitDiedEvent': if event.killing_player.name == participants[0].name: # if event.killer_pid != None: # import pdb; pdb.set_trace() if event.killing_unit.owner.name != event.unit.owner.name: participantOne_events.append(UnitDiedEvent(participant = participants[0], name = event.name, second = event.second, killing_unit = event.killing_unit.name, unit = event.unit.name, loc_x = event.x, loc_y = event.y )) #participantOne_events.append(UnitDiedEvent(participant = [participants[0]], killing_participant = [participants[1]], name = event.name, second = event.second, killing_unit = event.killing_unit.name, unit = event.unit.name, loc_x = event.x, loc_y = event.y)) #UnitDiedEvent(participant = participants[0], killing_participant = participants[1], game = game, name = event.name, second = event.second, killing_unit = event.killing_unit.name, unit = event.unit.name, loc_x = event.x, loc_y = event.y) else: # if event.killer_pid != None: # import pdb; pdb.set_trace() if event.killing_unit.owner.name != event.unit.owner.name: participantTwo_events.append(UnitDiedEvent(participant = participants[1], name = event.name, second = event.second, killing_unit = event.killing_unit.name, unit = event.unit.name, loc_x = event.x, loc_y = event.y )) except Exception as e: pass #print(e, event.name) # if event.name == 'PlayerStatsEvent': # print(event.name, event.player) # elif event.name == 'UnitBornEvent': # print(participants[0].name, participants[1].name, game, event.name, event.unit_controller, event.unit_type_name, event.second, event.x, event.y) #import pdb; pdb.set_trace() db.session.add_all(participantOne_events + participantTwo_events + participants + [game] + users) db.session.commit() return [participantOne, participantTwo, userOne, userTwo, game] except Exception as e: pass