Example #1
0
    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()
Example #2
0
def add_tournament():
    add_url = url_for('.add_tournament')

    if request.method == 'POST':
        file = request.files['file']

        filename = file.filename
        if not filename:
            flash('Додайте файл з турнірними даними', 'isa_warning')
            return redirect(url_for('.add_tournament'))

        if not allowed_file(filename):
            flash('Файл має бути текстовим', 'isa_error')
            return redirect(url_for('.add_tournament'))

        insert_data = dict(request.form)
        insert_data['is_ranked'] = 'is_ranked' in insert_data.keys()
        insert_data['date_start'] = request.form.getlist('date_start')[0]
        insert_data['date_end'] = request.form.getlist('date_end')[0]
        tournament_id = None
        try:
            tournament_id = Tournament.execute_insert([insert_data])[0]
            parser = TournamentParser(file.read(), tournament_id)
            parser.run()
        except Exception:
            flash('Oops!', 'isa_error')
            if tournament_id:
                pairing_ids = Pairing.select_attrs(
                    ['id'], {'tp.tournament_id': tournament_id})
                existing_participant_ids = Participant.select_attrs(
                    ['id'], {'tournament_id': tournament_id})
                Pairing.execute_delete([p[0] for p in pairing_ids])
                Participant.execute_delete(
                    [p[0] for p in existing_participant_ids])
                Tournament.execute_delete([tournament_id])
            return redirect(url_for('.add_tournament'))
        return redirect(
            url_for('.tournament_info', tournament_id=tournament_id))

    cities = City.select_attrs(['id', 'name'])

    form = '\n'.join([
        '<div class="container">',
        f'<form action="{add_url}" enctype="multipart/form-data" method="post">',
        render_text_input_row("name", "Назва"),
        render_select_row('city_id', "Місто", cities),
        render_date_row('date_start', 'Дата початку',
                        str(datetime.date.today())),
        render_date_row('date_end', 'Дата закінчення',
                        str(datetime.date.today())),
        render_text_input_row("pin", "EGF PIN"),
        render_checkbox_row('is_ranked', "Рейтинговий"),
        render_file_row('file', 'Файл'),
        render_submit(),
        '</form>',
        '</div>',
    ])

    return render_template('add_tournament.html', form=form)
Example #3
0
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()
Example #4
0
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()
Example #5
0
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)')
Example #6
0
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)')
Example #7
0
    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)
Example #8
0
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
Example #10
0
def delete_tournament(tournament_id):
    try:
        pairing_ids = Pairing.select_attrs(['id'],
                                           {'tp.tournament_id': tournament_id})
        existing_participant_ids = Participant.select_attrs(
            ['id'], {'tournament_id': tournament_id})
        Pairing.execute_delete([str(p[0]) for p in pairing_ids])
        Participant.execute_delete(
            [str(p[0]) for p in existing_participant_ids])
        Tournament.execute_delete([str(tournament_id)])
        flash('Турнір видалений', 'isa_success')
        return redirect(url_for('.tournaments'))
    except mysql.connector.Error as err:
        flash(err.msg, 'isa_error')
        return redirect(
            url_for('.tournament_info', tournament_id=tournament_id))
Example #11
0
    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)
Example #12
0
def player_info(player_id):
    player = Player.execute_select({'id': player_id})[0]
    participant = Participant.execute_select({'player_id': player.id},
                                             [('t.date_start', False)])
    return render_template('player_info.html',
                           player=player,
                           participant=participant)
Example #13
0
    def populate_participant(index, reg_model, data):
        index_suffix = "-{i}".format(i=index)
        form_keys = [key for key in data if key.endswith(index_suffix)]
        model = Participant()
        for key in form_keys:
            real_key = key.split('-')[0]
            setattr(model, real_key, data[key])

        if reg_model:
            model.registration = reg_model

        model.conference_dinner = model.conference_dinner == "on"
        model.ride_from_helsinki = model.ride_from_helsinki == "on"
        model.ride_from_tampere = model.ride_from_tampere == "on"

        return model
Example #14
0
    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))
Example #15
0
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)
Example #16
0
 def get(self):
     participants = Participant.get_all()
     participant_list = []
     for participant in participants:
         participant_list.append(participant.to_json_dict('full_name', 'email',
             'is_starred', 'is_active', 'is_deleted', 'when_created'))
     response = json.dumps(participant_list)
     self.response.out.write(response)
def autor():
    all_participants = Participant.select(Participant.registrationId,
                                          Participant.name,
                                          Participant.workplace)
    for p in all_participants:
        AutorDW.get_or_create(idautor=p.registrationId,
                              autorname=p.name,
                              workplace=p.workplace)
Example #18
0
 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 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}'
    }
Example #20
0
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
Example #21
0
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
Example #22
0
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)
Example #23
0
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))
Example #24
0
def user_created(sender, user, request, **kwargs):
    form = UserRegistrationForm(request.POST)
    user_profile = UserProfile(user=user, user_type='P')
    user_profile.save()
    participant = Participant(user=user_profile)
    participant.name = form.data["fullname"]
    user.firstname = participant.name
    participant.email_id = user.email
    participant.phone_no = form.data["phone_no"]
    if int(form.data["college"]) == -1:
        if form.data["add_your_college"] is not None:
            new_college = College(name=form.data["add_your_college"])
            new_college.save()
            participant.college = new_college
        else:
            raise Exception("No College name specified")
    else:
        participant.college = College.objects.get(pk=form.data["college"])
    participant.roll_no = form.data['rollno']
    participant.save()
Example #25
0
    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)
Example #26
0
    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)
Example #27
0
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)
Example #28
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        try:
            participant = Participant.get(
                Participant.Email == self.Email.data.lower().strip())
            print(participant.Name, self.Name.data)
            if participant.Name != self.Name.data.strip():
                self.Name.errors.append(
                    'This name / email combination has already been used, contact [email protected] for help'
                )
                return False
            else:
                return True
        except peewee.DoesNotExist:
            return True
Example #29
0
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
Example #30
0
    def process_participant(self, row, player_id, rank_id):
        place = int(row[self.slices[self.indices['place']]])
        rating = row[self.slices[self.indices['rating']]].strip()
        rating = float(rating) if rating else None

        participant_data = {
            'player_id': player_id,
            'tournament_id': self.tournament_id,
            'rank_id': rank_id,
            'place': place,
            'rating_start': rating,
            'rating_end': None,
        }
        participant_id = Participant.execute_insert([participant_data])[0]
        self.participants[place] = participant_id

        self.rounds.append((participant_id, [row[self.slices[i]].strip() for i in
                                             range(self.indices['first_round'], self.indices['last_round'] + 1)]))

        return participant_id
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"}
Example #32
0
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
Example #33
0
def signup(request):
    result = {
        'success': False,
        'message': 'operation failed'
    }

    if request.method == 'POST':
        error_message, data = Participant.signup(request.POST)
        if error_message == None:
            result['success'] = True
            result['message'] = 'operation success'
            return JsonResponse(result, status = 200)
        else:
            log(data, error_message)
            result['message'] = error_message
            return JsonResponse(result, status = 422)
    else:
        log(None, 'method %s not support' % request.method)
        result['message'] = 'method not support'
        return JsonResponse(result, status = 405)
Example #34
0
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()
Example #35
0
def start_page(request):
    # For GET, display the form
    if request.method == "GET":
        return render_to_response("consent.html", context_instance=RequestContext(request))
    # For POST, create a new user and then send user to the next page, then update the session.
    elif request.method == "POST":
        participant = Participant()
        participant.save()
        participant.num_images = 2 if participant.id % 2 is 0 else 3
        # Demographics will be set at the end.
        participant.save()
        request.session['participant_id'] = participant.id
        response = HttpResponse()
        response.status_code = 303
        response['Location'] = "/experiment/" # Get the URL and set it.
        return response
Example #36
0
def create_submission(user_id: UUID, user_role: Role,
                      submission: schemas.Submission):
    is_authorized(user_role, "create_submission")

    question = Question.get(id=submission.question_id)
    if not question:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=("Question not found : question_id: {}".format(
                submission.question_id)))

    participant = Participant.get(exam=question.exam, user=User[user_id])
    if not participant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=("Participant not found : exam_id: {}".format(
                question.exam.id)))

    if len(question.multi_choice) > 0:
        if submission.answer == question.answer:
            marks_obtained = question.marks
            mark = Mark.auto_tick
        else:
            marks_obtained = 0
            mark = Mark.auto_cross

        submission = Submission(answer=submission.answer,
                                question=question,
                                user=User[user_id],
                                marks_obtained=marks_obtained,
                                mark=mark)
    else:
        submission = Submission(answer=submission.answer,
                                question=question,
                                user=User[user_id])

    performance_review(submission)

    return submission.to_dict()
Example #37
0
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)
Example #38
0
        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)
Example #39
0
    def post(self):
        participant = Participant()
        participant.full_name = self.request.get('full_name')
        participant.email = self.request.get('email')
        participant.mobile_number = self.request.get('mobile_number')
        participant.phone_number = self.request.get('phone_number')
        participant.pricing = Decimal(self.request.get('pricing'))
        participant.designation = self.request.get('designation')
        participant.department = self.request.get('department')
        participant.organization = self.request.get('organization')
        participant.address = self.request.get('address')
        participant.put()

        queue_mail_task(url='/worker/mail/thanks/registration/',
            params=dict(
                full_name=participant.full_name,
                email = participant.email,
                key=str(participant.key())
            ),
            method='POST'
        )
        self.response.out.write(participant.to_json('full_name', 'is_starred', 'is_deleted', 'is_active'))
Example #40
0
    def get(self):
        participants = self.session.get('participants', None)
        if participants:
            db.put(participants)
            self.session['participants'] = participants
            total_price = self.session.get('total_price', None)
            tax_amount = self.session.get('tax_amount', None)
            calculated_price = self.session.get('calculated_price', None)
            group = self.session['participant_group']
            #primary_participant = self.session.get('primary_participant')
            primary_participant = Participant.get_primary_participant_for_group(group)
            self.session['primary_participant'] = primary_participant
            participant_count = self.session.get('participant_count')
#           This mail should go in the thank you part after receiving successful payment from payment gateway.
#            for participant in participants:
#                queue_mail_task(url='/worker/mail/thanks/registration/',
#                    params=dict(
#                        full_name=participant.full_name,
#                        email = participant.email,
#                        key=str(participant.key())
#                    ),
#                    method='POST'
#                )
            #primary_participant.put()
            billing_settings = BillingSettings.get_settings(deployment_mode=ebs_mode)

            billing_contact = BillingContact(name=primary_participant.full_name, \
                phone=primary_participant.phone_number, \
                email=primary_participant.email,
                address=primary_participant.address, \
                city=primary_participant.city, \
                postal_code=primary_participant.zip_code, \
                state=primary_participant.state_province, \
                country=primary_participant.country_code)
            shipping_contact = ShippingContact(name=primary_participant.full_name, \
                phone=primary_participant.phone_number, \
                email=primary_participant.email,
                address=primary_participant.address, \
                city=primary_participant.city, \
                postal_code=primary_participant.zip_code, \
                state=primary_participant.state_province, \
                country=primary_participant.country_code)
            billing_information = BillingInformation(account_id=billing_settings.account_id, \
                reference_no=group.key().id(), \
                amount=total_price, \
                mode=ebs_mode, \
                description= str(total_price) + ' for ' + str(participant_count) + ' participant(s) to attend CLO Summit.', \
                return_url=url_join_path(config.ABSOLUTE_ROOT_URL, '/billing/ebs?DR={DR}'))
            d = {}
            d.update(billing_contact.fields())
            d.update(shipping_contact.fields())
            d.update(billing_information.fields())
            form_fields = [(k,v) for (k,v) in d.iteritems()]

            response = render_template('register/payment.html',
                form_fields=form_fields,
                payment_gateway_url=PAYMENT_GATEWAY_URL,
                participants=participants,
                total_price=total_price,
                tax_amount=tax_amount,
                calculated_price=calculated_price)
            self.response.out.write(response)
        else:
            self.redirect('/register/pricing/')
Example #41
0
 def new_participant(email):
     p = Participant()
     p.email = email
     return p
Example #42
0
def result(name):
    try:
        participant = Participant.get(name=name.title())
        return render_template('result.html', name=participant.name, giving_to=participant.giving_to)
    except:
        return redirect(url_for('index'))
Example #43
0
    def post(self):
        participant = Participant()
        participant.full_name = self.request.get("full_name")
        participant.email = self.request.get("email")
        participant.mobile_number = self.request.get("mobile_number")
        participant.phone_number = self.request.get("phone_number")
        participant.pricing = Decimal(self.request.get("pricing"))
        participant.designation = self.request.get("designation")
        participant.department = self.request.get("department")
        participant.organization = self.request.get("organization")
        participant.address = self.request.get("address")
        participant.put()

        queue_mail_task(
            url="/worker/mail/thanks/registration/",
            params=dict(full_name=participant.full_name, email=participant.email, key=str(participant.key())),
            method="POST",
        )
        self.response.out.write(participant.to_json("full_name", "is_starred", "is_deleted", "is_active"))
Example #44
0
    def post(self):
        count = dec(self.request.get('count'))
        pricing = Decimal(str(get_pricing_per_individual(count)))

        total_price = Decimal('0')
        participants = []

        host_info = get_host_info(self.request)
        host_info.put()

        group = ParticipantGroup()
        group.title = self.request.get('organization_1') + '/' + self.request.get('email_1')
        group.host_info = host_info
        group.put()

        primary_participant = None
        for x in range(count):
            i = str(x + 1)

            full_name = self.request.get('full_name_' + i)
            if full_name:
                participant = Participant()
                participant.full_name = full_name
                participant.email = self.request.get('email_' + i)
                participant.mobile_number = self.request.get('mobile_number_' + i)
                participant.address = self.request.get('address_' + i)
                participant.phone_number = self.request.get('phone_number_' + i)
                participant.designation = self.request.get('designation_' + i)
                participant.organization = self.request.get('organization_' + i)
                participant.department = self.request.get('department_' + i)
                participant.country_code = self.request.get('country_code_' + i)
                participant.state_province = self.request.get('state_province_' + i)
                participant.city = self.request.get('city_' + i)
                participant.zip_code = self.request.get('zip_code_' + i)
                participant.pricing = pricing
                if x == 0:
                    participant.is_primary = True
                    primary_participant = participant
                participant.group = group
                total_price += pricing
                participants.append(participant)

        tax_amount = (total_price * PRICING_TAX)
        tax_amount = tax_amount.quantize(Decimal('.01'), rounding=ROUND_DOWN)
        calculated_price = total_price
        total_price = total_price + tax_amount

        self.session['calculated_price'] = calculated_price
        self.session['tax_amount'] = tax_amount
        self.session['total_price'] = total_price
        self.session['participant_count'] = count
        self.session['participants'] = participants
        self.session['participant_group'] = group
        self.session['primary_participant'] = primary_participant



        self.redirect('/register/payment/')
Example #45
0
def email_exists(form, field):
    email = field.data.lower()
    if Participant.select().where(Participant.Email == email).exists():
        raise ValidationError(
            'Participant with that email already exists, check the name you have entered matches '
            'previously, or contact [email protected] for help.')
Example #46
0
def results():
    participants = Participant.select()
    return render_template('results.html', participants=participants)
Example #47
0
def index():
    participants = Participant.select()
    return render_template('index.html', participants=participants)
Example #48
0
def recipient_to_txt():
    query = Participant.get(name=input('Who do you need the recipient for? ex: Justin: '))
    with open(query.name + '.txt', 'w') as file:
        file.write(query.name + ', you are giving to ' + query.giving_to + "!") 
def create_participant(**form_kwargs):
    new_participant = Participant(**form_kwargs)
    db.session.add(new_participant)
    db.session.commit()
    return jsonify(new_participant.as_dict())
Example #50
0
    def run(self):
        lastIP = None #上一个发送者的IP
        while not self.shouldStop:
            if self.importQueue.empty():
                continue

            # elements = []
            # for i in range(0, DataProcessor.BATCH_DATA_SIZE):
            #     element = self.importQueue.get()
            #     print '\nI`ve got an element type = %d, remaining element size :%d' %(element.type, self.importQueue.qsize())
            #     elements.append(element)
            #self.importQueue.task_done()
            #TODO: PROCESS DATA RIGHT HERE
            element = self.importQueue.get()
            eventElem, classElem = self.get_full_elements(element)#self.get_valid_elems(elements)
            if (eventElem, classElem) == (None, None):
                continue  #尚未填满
            print ' > > > I`m full...'
            eveContent = eventElem.content
            clsContent = classElem.content
            timestamp = eveContent.timestamp
            ip = eveContent.senderip
            emoState = clsContent.result
            posRate = clsContent.positive_rate

            posdiff = 0
            negdiff = 0
            if emoState == ClassifierData.RESULT_POSITIVE:
                posdiff = 1
            else:
                negdiff = 1
            duration = eveContent.dur

            if not self.has_participant(ip):
                #如果没有这个参与者,则新建一条记录
                participant = Participant(ip, duration, posdiff, negdiff)
                participant.latest_pos_val = posRate  # 判断为positive的rate
                self.participants[ip] = participant
            else:
                #如果有记录,则在之前的基础上加上时间和相关的东西
                self.participants[ip].totalTime += duration
                self.participants[ip].posCount += posdiff
                self.participants[ip].negCount += negdiff

            self.participants[ip].latest_pos_val = posRate  # 判断为positive的rate
            self.participants[ip].latest_timestamp = timestamp  #消息发送时间
            self.participants[ip].ip = ip   #IP地址还是要的
            if self.nicknames.has_key(ip):
                self.participants[ip].nickname = self.nicknames[ip]  # 设置昵称

            if (lastIP is not None) and (lastIP != ip):
                #构造Conversation (排除上个人的ip是自己的情况!)
                convContent = ConvContent(lastIP, timestamp, duration, emoState)
                if not self.participants[ip].conversations.has_key(lastIP):
                    self.participants[ip].conversations[lastIP] = []  #新建一个列表,存放与这个人的conversations
                self.participants[ip].conversations[lastIP].append(convContent)

            #TODO: PUT PROCESSED DATA TO EXPORT QUEUE
            #exportQueue里面是完整的participants数据
            self.exportQueue.put(self.participants)


            lastIP = ip     # Update lastIP to current ip