Ejemplo n.º 1
0
def get_team_ids():
    attr_id = get_config("split_scoreboard_attr", 0)
    attr_value = get_config("split_scoreboard_value", "hidden")

    team_ids = []
    if attr_id == "-1":  # Where team size is <value>
        teams = Teams.query.outerjoin(Teams.members).group_by(Teams).having(
            func.count_(Teams.members) == attr_value)
        for team in teams:
            team_ids.append(team.id)
    elif attr_id == "-2":  # Where team size is less than <value>
        teams = Teams.query.outerjoin(Teams.members).group_by(Teams).having(
            func.count_(Teams.members) <= attr_value)
        for team in teams:
            team_ids.append(team.id)
    elif attr_id == "-3":  # Where team size is greater than <value>
        teams = Teams.query.outerjoin(Teams.members).group_by(Teams).having(
            func.count_(Teams.members) >= attr_value)
        for team in teams:
            team_ids.append(team.id)
    else:
        teams = TeamFieldEntries.query.filter_by(field_id=attr_id).filter(
            func.lower(TeamFieldEntries.value) == func.lower(str(attr_value)))
        for team in teams:
            team_ids.append(team.team_id)

    return team_ids
Ejemplo n.º 2
0
def create_session_data_file(search_string, count=1):
    attributes = Attribute.query.all()

    sessions = Session.query\
                      .filter((Session.session_ident.contains(search_string)) |
                              (Session.selected_class.has(BuildingClass.class_id.contains(search_string))) |
                              (Session.answered_questions.any((AnswerQuestion.attribute.has(Attribute.attribute_id.contains(search_string))) |
                                                              (AnswerQuestion.answer.has(Answer.value.contains(search_string))))))\
                      .outerjoin(AnswerQuestion)\
                      .group_by(Session)\
                      .having(func.count_(Session.answered_questions) >= count)\
                      .all()

    columns = {'session_id': [x.session_ident for x in sessions],
               'selected_class': [x.selected_class.class_id if x.selected_class is not None else '-' for x in sessions]}
    attr_columns = {x.attribute_id: '-' for x in attributes}
    columns.update(attr_columns)

    df = pd.DataFrame(columns)
    df = df.set_index('session_id')

    for x in sessions:
        for y in x.answered_questions:
            df.loc[x.session_ident, y.attribute.attribute_id] = y.answer.value

    df.to_csv('./tmp/session_export.csv')

    return './tmp/session_export.csv'
Ejemplo n.º 3
0
def results_view():
    # Change default_minimum to 0 if you want to always see empty sessions by default, or some other number if you want the filtering to be rougher.
    # For a quick temporary filter- In the browser, you can use /801fc3r?min=5 for example, to set the filter to only show sessions with 5 or more answered questions
    default_minimum = 1
    count = request.args.get('min')
    try:
        if count:
            count = max(int(count), default_minimum)
        else:
            count = default_minimum
    except:
        count = default_minimum

    return render_template(
        "resultsView.html",
        sessions=Session.query.outerjoin(
            AnswerQuestion).group_by(Session).having(
                func.count_(Session.answered_questions) >= count).all())
Ejemplo n.º 4
0
    def new_tournaments(cls):
        """Return new tournaments that should be created base on templates"""
        new_tourns = []
        # pull active templates:
        templates = TournamentTemplate.query.filter_by(active=True).all()
        for temp in templates:
            for region in ["GMAN", "REL", "Big O"]:
                # find free tournament
                tourns = Tournament.query.outerjoin(Tournament.tournament_signups).filter( \
                    Tournament.status == "OPEN", \
                    Tournament.type == temp.type, \
                    Tournament.mode == temp.mode, \
                    Tournament.coach_limit == temp.coach_limit, \
                    Tournament.deck_limit == temp.deck_limit, \
                    Tournament.deck_value_limit == temp.deck_value_limit, \
                    Tournament.deck_value_target == temp.deck_value_target, \
                    Tournament.conclave_distance == temp.conclave_distance, \
                    Tournament.region == region
                ).group_by(Tournament).having(func.count_(Tournament.tournament_signups) < Tournament.coach_limit+Tournament.reserve_limit).all()
                # create new one if there is not
                if not tourns:
                    new_tourns.append((region, temp))

        return new_tourns
Ejemplo n.º 5
0
    async def complist(self, ctx, *args):
        """List all available tournaments"""
        if len(args) == 1 and not (represents_int(args[0])
                                   or args[0] in ["all", "full", "free"]):
            raise ValueError(
                f"**{args[0]}** is not a number or 'all', 'full' or 'free'!!!")

        if len(args) > 1:
            if args[0] not in ["all", "full", "free"]:
                raise ValueError(
                    f"**{args[0]}** is not 'all', 'full' or 'free'!!!")

            if args[1] not in ["bigo", "gman", "rel"]:
                raise ValueError(
                    f"**{args[1]}** is not 'bigo', 'gman' or 'rel'!!!")

        #detail
        if len(args) == 1 and represents_int(args[0]):
            tourn = Tourn.query.filter_by(
                tournament_id=int(args[0])).one_or_none()
            if not tourn:
                raise ValueError(f"Tournament **id** does not exist")
            coaches = tourn.coaches.filter(
                TournamentSignups.mode == "active").all()
            count = len(coaches)

            msg = [
                f"__**{tourn.name}**__  - **{tourn.status}**\n",
                f"**Type**: {tourn.region} - {tourn.type} - {tourn.mode}",
                f"**Dates**: Signup By/Start By/End By/Deadline  - {tourn.signup_close_date}/{tourn.expected_start_date}/{tourn.expected_end_date}/{tourn.deadline_date}",
                f"**Entrance Fee**: {tourn.fee}",
                f"**Deck Size/Deck Target Value/Deck Max Value**: {tourn.deck_limit}/{tourn.deck_value_target}/{tourn.deck_value_limit}",
                f"**Conclave Ranges**:",
                f"\t**3 Blessing Points:**\t\t {tourn.conclave_ranges().blessing3.start}-{tourn.conclave_ranges().blessing3.stop}",
                f"\t**2 Blessing Points:**\t\t {tourn.conclave_ranges().blessing2.start}-{tourn.conclave_ranges().blessing2.stop}",
                f"\t**1 Blessing Point:** \t\t   {tourn.conclave_ranges().blessing1.start}-{tourn.conclave_ranges().blessing1.stop}",
                f"\t**Conclave equilibrium:**  {tourn.deck_value_target}",
                f"\t**1 Curse Point:**\t\t\t\t {tourn.conclave_ranges().curse1.start}-{tourn.conclave_ranges().curse1.stop}",
                f"\t**2 Curse Points:**\t\t\t  {tourn.conclave_ranges().curse2.start}-{tourn.conclave_ranges().curse2.stop}",
                f"\t**3 Curse Points:**\t\t\t  {tourn.conclave_ranges().curse3.start}-{tourn.conclave_ranges().curse3.stop}",
                f"**Sponsor**: {tourn.sponsor}",
                f"**Sponsor Description**: {tourn.sponsor_description}",
                f"**Special Rules**: {tourn.special_rules}",
                f"**Banned Cards**: {', '.join(tourn.banned_cards.split(';'))}",
                f"**Prizes**: {tourn.prizes}",
                f"**Unique Prize**: {tourn.unique_prize}",
                f"**Channel**: {tourn.discord_channel}",
                f"**Admin**: {tourn.admin}",
            ]
            if tourn.status == "RUNNING":
                msg.append(
                    f"**Signups**: {count}/{tourn.coach_limit} {', '.join([coach.short_name() for coach in coaches])}"
                )
            else:
                msg.append(f"**Signups**: {count}/{tourn.coach_limit}")

            if tourn.reserve_limit > 0:
                reserves = tourn.coaches.filter(
                    TournamentSignups.mode == "reserve").all()
                count_res = len(reserves)
                if tourn.status == "RUNNING":
                    msg.append(
                        f"**Reserves**: {count_res}/{tourn.reserve_limit} {', '.join([coach.short_name() for coach in reserves])}"
                    )
                else:
                    msg.append(
                        f"**Reserves**: {count_res}/{tourn.reserve_limit}")

            await self.send_message(ctx.channel, msg)
            return
        #list
        else:
            if len(args) >= 1 and args[0] == "all":
                tourns = Tourn.query.all()
                tmsg = "All"
            elif len(args) >= 1 and args[0] == "full":
                tourns = Tourn.query.outerjoin(
                    Tourn.tournament_signups).filter(
                        Tourn.status == "OPEN").group_by(Tourn).having(
                            func.count_(Tourn.tournament_signups) ==
                            Tourn.coach_limit + Tourn.reserve_limit).all()
                tmsg = "Full"
            elif len(args) >= 1 and args[0] == "free":
                tourns = Tourn.query.outerjoin(
                    Tourn.tournament_signups).filter(
                        Tourn.status == "OPEN").group_by(Tourn).having(
                            func.count_(Tourn.tournament_signups) <
                            Tourn.coach_limit + Tourn.reserve_limit).all()
                tmsg = "Free"
            else:
                tourns = Tourn.query.filter_by(status="OPEN").all()
                tmsg = "Open"

            if len(args) > 1:
                tourns = [
                    tourn for tourn in tourns
                    if tourn.region.lower().replace(" ", "") == args[1]
                    or tourn.region.lower() == "all"
                ]

            msg = [f"__**{tmsg} Tournaments:**__"]
            for tournament in tourns:
                coaches = tournament.coaches.filter(
                    TournamentSignups.mode == "active").all()
                reserves = tournament.coaches.filter(
                    TournamentSignups.mode == "reserve").all()
                count = len(coaches)
                count_res = len(reserves)
                reserve_message = f" ({count_res}/{tournament.reserve_limit}) " if tournament.reserve_limit != 0 else ""
                msg.append(
                    f"**{tournament.tournament_id}.** {tournament.name}{' (Imperium)' if tournament.type == 'Imperium' else ''} - Signups: {count}/{tournament.coach_limit}{reserve_message}, Closes: {tournament.signup_close_date}"
                )

            msg.append(
                " \nUse **!complist all|full|free <bigo|gman|rel>** to display tournaments"
            )
            msg.append(
                "Use **!complist <id>** to display details of the tournament")
            msg.append("Use **!sign <id>** to register for tournament")
            msg.append("Use **!resign <id>** to resign from tournament")
            await self.send_message(ctx.channel, msg)
            return
Ejemplo n.º 6
0
    def __new__word__message__(self, is_start=False):
        # закончился ли раунд?
        if self.session.query(
                bot_users_answers).count() % 10 == 0 and not is_start:
            answers = self.session.query(bot_users_answers).order_by(
                bot_users_answers.id.desc()).limit(10).all()
            score = 0
            for answer in answers:
                if answer.is_right:
                    score = score + 1
            message = [
                TextMessage(text='Раунд завершен. Ваш результат: ' +
                            str(score) + ' из 10'),
                TextMessage(text='Отлично сыграно!')
            ] + self.__help__message__()
            return message

        KeysNewWord = json.load(open('word_keyboard.json', encoding='utf-8'))

        # Полуаем количество повторов для запоминания
        repeats_number = self.current_user.repeats_number
        if repeats_number is None:
            repeats_number = 20

        # получаем слова
        words = self.session.query(bot_words) \
            .outerjoin(bot_words.bot_users_answers) \
            .group_by(bot_words) \
            .having(func.count_(bot_words.bot_users_answers) < repeats_number) \
            .order_by(func.random()) \
            .limit(4) \
            .all()

        # выбираем индекс правильного ответа
        right_answer_index = random.choice(range(0, 4))

        # создаем клавиатуру
        KeysNewWord['Buttons'][0]['Text'] = words[0].translation
        KeysNewWord['Buttons'][1]['Text'] = words[1].translation
        KeysNewWord['Buttons'][2]['Text'] = words[2].translation
        KeysNewWord['Buttons'][3]['Text'] = words[3].translation

        # сохраняем данные о текущем вопросе
        sentences = list()
        if len(words[right_answer_index].bot_examples) != 0:
            for i in range(0, len(words[right_answer_index].bot_examples)):
                sentences.append(
                    words[right_answer_index].bot_examples[i].sentence)
        print(sentences)
        KeysWords[self.current_user.id] = dict(
            right_answer=words[right_answer_index],
            right_answer_index=right_answer_index,
            keyboard=KeysNewWord,
            examples=sentences,
            is_right=False)

        # обрабокта законена. подтверждаем транзакцию
        self.session.commit()

        # задаем вопрос
        return [
            TextMessage(text='Ваше слово: ' + words[right_answer_index].word),
            TextMessage(text='Выберите верный вариант на клавиатуре'),
            KeyboardMessage(keyboard=KeysNewWord)
        ]
Ejemplo n.º 7
0
def process_form():
    """Recieve and store filtration input into JSON"""

    name = request.args.get('name')
    zipcode = request.args.get('zipcode')
    city = request.args.get('city')
    min_cit = request.args.get('min_cit')
    max_cit = request.args.get('max_cit')
    status = request.args.get('status')
    suppress_date = request.args.get('suppress_date')
    f_type = request.args.get('type')
    page_num = request.args.get('page_num') ### For use in pagination
    
    fquery = Facility.query ### Base query


    if name or zipcode or city or min_cit or max_cit or status or suppress_date or f_type:

        if name:
            name = name.upper()
            fquery = fquery.filter(Facility.name.like(f'%{name}%')
                )
        
        if zipcode:
            fquery = fquery.filter(Facility.f_zip == int(zipcode))

        if city:
            city = city.upper()
            fquery = fquery.filter(Facility.city.like(f'%{city}%')
                )            

        if min_cit:
            ### Below query based off of https://stackoverflow.com/a/38639550
            fquery = (fquery
                .outerjoin(Facility.citations)
                .group_by(Facility)
                .having(func.count_(Facility.citations) >= min_cit)
                )

        if max_cit:
            ### Below query based off of https://stackoverflow.com/a/38639550
            fquery = (fquery
                .outerjoin(Facility.citations)
                .group_by(Facility)
                .having(func.count_(Facility.citations) <= max_cit)
                )

        if suppress_date:
            ### Show only facilities who have had 0 citations since input date
            suppress_date = isoparse(suppress_date)

            fquery = (fquery
                .outerjoin(Facility.citations)
                .group_by(Facility)
                .having((func.max(Citation.date) <= suppress_date) | (func.count_(Facility.citations) == 0))
                )
        
        if status:
            status = status.upper()
            if status == 'PROBATION':
                status = 'ON PROBATION'
            fquery = fquery.filter(Facility.status == status)

        if f_type:
            if f_type == 'infant':
                f_type = 'INFANT CENTER'
            elif f_type == 'ill':
                f_type = 'DAY CARE CENTER - ILL CENTER'
            elif f_type == 'prek':
                f_type = 'DAY CARE CENTER'
            elif f_type == 'school':
                f_type = 'SCHOOL AGE DAY CARE CENTER'
            fquery = fquery.filter(Facility.f_type == f_type)

    
    testquery = fquery ### To show total num markers that should be produced

    fquery = fquery.limit(200)
    page_num = int(page_num)

    if page_num > 1:
        fquery = fquery.offset(200 * (page_num - 1))
        ### Add offset and limit to keep ea query to ~100
        ### Logic for pagination so front end can request specific "page"

    facilities = fquery.all() ### Conglomerate all applicable queries
    testquery = testquery.all()
    testquery_count = len(testquery)

    facility_count = len(facilities)
    
    facilities_dict = {"count": facility_count}

    for facility in facilities:     
        mapinfo = {
                    "title": facility.name,
                    "lat": facility.latitude, 
                    "lng": facility.longitude,
                    "status": facility.status,
                    "citation_count": len(facility.citations),
                    }
        facilities_dict[str(facility.f_id)] = mapinfo 
        ### must stringify for comparison of f_id to "count"
    
    return jsonify(facilities_dict)