def friends_trending():
    friends, cusfriends = utilities.get_friends(session.user_id)

    # The Original IDs of duplicate custom_friends
    custom_friends = []
    for cus_id in cusfriends:
        if cus_id[1] is None:
            custom_friends.append(cus_id[0])
        else:
            custom_friends.append(cus_id[1])

    friends, custom_friends = set(friends), set(custom_friends)
    stable = db.submission
    today = datetime.datetime.today()
    # Consider submissions only after PAST_DAYS(customizable)
    # for trending problems
    start_date = str(today - datetime.timedelta(days=current.PAST_DAYS))
    query = (stable.time_stamp >= start_date) & \
            (stable.user_id.belongs(friends) | \
             stable.custom_user_id.belongs(custom_friends))
    last_submissions = db(query).select(stable.problem_name,
                                        stable.problem_link, stable.user_id,
                                        stable.custom_user_id)

    return utilities.compute_trending_table(last_submissions, "friends",
                                            session.user_id)
Esempio n. 2
0
def submissions():
    """
        Retrieve submissions of the logged-in user
    """

    if len(request.args) == 0:
        active = 1
    else:
        try:
            active = int(request.args[0])
        except ValueError:
            # The pagination page number is not integer
            raise HTTP(404)
            return

    cftable = db.custom_friend
    ftable = db.friends
    stable = db.submission
    atable = db.auth_user

    # Get all the friends/custom friends of the logged-in user
    friends, cusfriends = utilities.get_friends(session.user_id)

    # The Original IDs of duplicate custom_friends
    custom_friends = []
    for cus_id in cusfriends:
        if cus_id[1] is None:
            custom_friends.append(cus_id[0])
        else:
            custom_friends.append(cus_id[1])

    query = (stable.user_id.belongs(friends)) | \
            (stable.custom_user_id.belongs(custom_friends))
    total_count = db(query).count()

    PER_PAGE = current.PER_PAGE
    count = total_count / PER_PAGE
    if total_count % PER_PAGE:
        count += 1

    if request.extension == "json":
        return dict(count=count,
                    total_rows=1)

    user = session.auth.user
    db.sessions_today.insert(message="%s %s %d %s" % (user.first_name,
                                                      user.last_name,
                                                      user.id,
                                                      datetime.datetime.now()))

    offset = PER_PAGE * (active - 1)
    # Retrieve only some number of submissions from the offset
    rows = db(query).select(orderby=~db.submission.time_stamp,
                            limitby=(offset, offset + PER_PAGE))

    table = utilities.render_table(rows, cusfriends)
    return dict(table=table,
                friends=friends,
                cusfriends=cusfriends,
                total_rows=len(rows))
def friends_trending():
    import trending_utilities
    friends, cusfriends = utilities.get_friends(session.user_id)

    # The Original IDs of duplicate custom_friends
    custom_friends = []
    for cus_id in cusfriends:
        if cus_id[1] is None:
            custom_friends.append(cus_id[0])
        else:
            custom_friends.append(cus_id[1])

    friends, custom_friends = set(friends), set(custom_friends)
    stable = db.submission
    query = (stable.user_id.belongs(friends) | \
             stable.custom_user_id.belongs(custom_friends))
    last_submissions = trending_utilities.get_last_submissions_for_trending(
        query)

    # for api
    if utilities.is_apicall():
        problems = trending_utilities.get_trending_problem_list(
            last_submissions)
        return response.json(dict(problems=problems))

    return trending_utilities.compute_trending_table(last_submissions,
                                                     "friends",
                                                     session.user_id)
Esempio n. 4
0
def pie_chart_helper():
    """
        Helper function for populating pie chart with different
        submission status of a problem
    """

    problem_link = request.post_vars["plink"]
    global_submissions = False
    if request.post_vars["global"] == "True":
        global_submissions = True

    stable = db.submission
    count = stable.id.count()
    query = (stable.problem_link == problem_link)

    # Show stats only for friends and logged-in user
    if global_submissions is False:
        if session.user_id:
            friends, cusfriends = utilities.get_friends(session.user_id)
            # The Original IDs of duplicate custom_friends
            custom_friends = []
            for cus_id in cusfriends:
                if cus_id[1] == None:
                    custom_friends.append(cus_id[0])
                else:
                    custom_friends.append(cus_id[1])

            query &= (stable.user_id.belongs(friends)) | \
                     (stable.custom_user_id.belongs(custom_friends)) | \
                     (stable.user_id == session.user_id)
        else:
            query &= (1 == 0)

    row = db(query).select(stable.status, count, groupby=stable.status)
    return dict(row=row)
Esempio n. 5
0
def get_submissions_list():
    if request.vars.has_key("problem_id") is False:
        # Disables direct entering of a URL
        session.flash = T("Please click on a Problem Link")
        redirect(URL("default", "index"))
        return

    try:
        problem_id = int(request.vars["problem_id"])
    except ValueError:
        session.flash = T("Invalid problem!")
        redirect(URL("default", "index"))
        return

    submission_type = "friends"
    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False and submission_type != "global":
        response.flash = T("Login to view your/friends' submissions")
        submission_type = "global"

    stable = db.submission
    query = (stable.problem_id == problem_id)
    cusfriends = []

    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            response.flash = T("Login to view your/friends' submissions")

    submissions = db(query).select(orderby=~stable.time_stamp,
                                   limitby=(0, 200))

    if len(submissions):
        table = utilities.render_table(submissions, cusfriends,
                                       session.user_id)
    else:
        table = DIV(T("No submissions found"))
    return table
def submissions():
    """
        Retrieve submissions of the logged-in user
    """

    if len(request.args) == 0:
        active = "1"
    else:
        active = request.args[0]

    cftable = db.custom_friend
    ftable = db.friends
    stable = db.submission
    atable = db.auth_user

    # Get all the friends/custom friends of the logged-in user
    friends, cusfriends = utilities.get_friends(session["user_id"])

    query = (stable.user_id.belongs(friends))
    query |= (stable.custom_user_id.belongs(cusfriends))
    total_count = db(query).count()

    PER_PAGE = current.PER_PAGE
    count = total_count / PER_PAGE
    if total_count % PER_PAGE:
        count += 1

    friend_query = (atable.id.belongs(friends))
    friends_list = db(friend_query).select(atable.id, atable.first_name,
                                           atable.last_name)
    all_friends = []
    for friend in friends_list:
        friend_name = friend["first_name"] + " " + friend["last_name"]
        all_friends.append([friend["id"], friend_name])

    cusfriend_query = (cftable.id.belongs(cusfriends))
    cusfriends_list = db(cusfriend_query).select(cftable.id,
                                                 cftable.first_name,
                                                 cftable.last_name)
    all_custom_friends = []
    for friend in cusfriends_list:
        friend_name = friend["first_name"] + " " + friend["last_name"]
        all_custom_friends.append([friend["id"], friend_name])

    if request.extension == "json":
        return dict(count=count,
                    friends=all_friends,
                    cusfriends=all_custom_friends)

    offset = PER_PAGE * (int(active) - 1)
    # Retrieve only some number of submissions from the offset
    rows = db(query).select(orderby=~db.submission.time_stamp,
                            limitby=(offset, offset + PER_PAGE))

    table = utilities.render_table(rows)
    return dict(table=table, friends=friends, cusfriends=cusfriends)
Esempio n. 7
0
def submissions():
    """
        Retrieve submissions of the logged-in user
    """

    if len(request.args) == 0:
        active = "1"
    else:
        active = request.args[0]

    cftable = db.custom_friend
    ftable = db.friends
    stable = db.submission
    atable = db.auth_user

    # Get all the friends/custom friends of the logged-in user
    friends, cusfriends = utilities.get_friends(session.user_id)

    # The Original IDs of duplicate custom_friends
    custom_friends = []
    for cus_id in cusfriends:
        if cus_id[1] is None:
            custom_friends.append(cus_id[0])
        else:
            custom_friends.append(cus_id[1])

    query = (stable.user_id.belongs(friends)) | \
            (stable.custom_user_id.belongs(custom_friends))
    total_count = db(query).count()

    PER_PAGE = current.PER_PAGE
    count = total_count / PER_PAGE
    if total_count % PER_PAGE:
        count += 1

    if request.extension == "json":
        return dict(count=count,
                    total_rows=1)

    user = session.auth.user
    db.sessions_today.insert(message="%s %s %s %s" % (user.first_name,
                                                      user.last_name,
                                                      user.institute,
                                                      datetime.datetime.now()))

    offset = PER_PAGE * (int(active) - 1)
    # Retrieve only some number of submissions from the offset
    rows = db(query).select(orderby=~db.submission.time_stamp,
                            limitby=(offset, offset + PER_PAGE))

    table = utilities.render_table(rows, cusfriends)
    return dict(table=table,
                friends=friends,
                cusfriends=cusfriends,
                total_rows=len(rows))
Esempio n. 8
0
def trending():
    """
        Show trending problems globally and among friends
    """

    stable = db.submission

    today = datetime.datetime.today()
    start_date = str(today - datetime.timedelta(days=current.PAST_DAYS))
    end_date = str(today)

    count = stable.id.count()
    PROBLEMS_PER_PAGE = current.PROBLEMS_PER_PAGE

    if session.user_id:
        friends, custom_friends = utilities.get_friends(session.user_id)

        query = (stable.user_id.belongs(friends))
        query |= (stable.custom_user_id.belongs(custom_friends))
        query &= (stable.time_stamp >= start_date)
        query &= (stable.time_stamp <= end_date)

        friend_trending = db(query).select(stable.problem_name,
                                           stable.problem_link,
                                           count,
                                           orderby=~count,
                                           groupby=stable.problem_link,
                                           limitby=(0, PROBLEMS_PER_PAGE))
        friend_table = _render_trending("Trending among friends",
                                        friend_trending)

    query = (stable.time_stamp >= start_date)
    query &= (stable.time_stamp <= end_date)
    global_trending = db(query).select(stable.problem_name,
                                       stable.problem_link,
                                       count,
                                       orderby=~count,
                                       groupby=stable.problem_link,
                                       limitby=(0, PROBLEMS_PER_PAGE))
    global_table = _render_trending("Trending Globally", global_trending)

    if session.user_id:
        div = DIV(_class="row col s12")
        div.append(DIV(friend_table, _class="col s6"))
        div.append(DIV(global_table, _class="col s6"))
    else:
        div = DIV(global_table, _class="center")

    return dict(div=div)
def trending():
    """
        Show trending problems globally and among friends
    """

    stable = db.submission

    today = datetime.datetime.today()
    start_date = str(today - datetime.timedelta(days=current.PAST_DAYS))
    end_date = str(today)

    count = stable.id.count()
    PROBLEMS_PER_PAGE = current.PROBLEMS_PER_PAGE

    if session.user_id:
        friends, custom_friends = utilities.get_friends(session.user_id)

        query = (stable.user_id.belongs(friends))
        query |= (stable.custom_user_id.belongs(custom_friends))
        query &= (stable.time_stamp >= start_date)
        query &= (stable.time_stamp <= end_date)

        friend_trending = db(query).select(stable.problem_name,
                                           stable.problem_link,
                                           count,
                                           orderby=~count,
                                           groupby=stable.problem_link,
                                           limitby=(0, PROBLEMS_PER_PAGE))
        friend_table = _render_trending("Trending among friends",
                                        friend_trending)

    query = (stable.time_stamp >= start_date)
    query &= (stable.time_stamp <= end_date)
    global_trending = db(query).select(stable.problem_name,
                                       stable.problem_link,
                                       count,
                                       orderby=~count,
                                       groupby=stable.problem_link,
                                       limitby=(0, PROBLEMS_PER_PAGE))
    global_table = _render_trending("Trending Globally", global_trending)

    if session.user_id:
        div = DIV(_class="row col s12")
        div.append(DIV(friend_table, _class="col s6"))
        div.append(DIV(global_table, _class="col s6"))
    else:
        div = DIV(global_table, _class="center")

    return dict(div=div)
Esempio n. 10
0
def submissions():
    """
        Retrieve submissions of the logged-in user
    """

    if len(request.args) == 0:
        active = "1"
    else:
        active = request.args[0]

    cftable = db.custom_friend
    ftable = db.friends
    stable = db.submission
    atable = db.auth_user

    # Get all the friends/custom friends of the logged-in user
    friends, cusfriends = utilities.get_friends(session["user_id"])

    # The Original IDs of duplicate custom_friends
    custom_friends = []
    for cus_id in cusfriends:
        if cus_id[1] == None:
            custom_friends.append(cus_id[0])
        else:
            custom_friends.append(cus_id[1])

    query = (stable.user_id.belongs(friends)) | \
            (stable.custom_user_id.belongs(custom_friends))
    total_count = db(query).count()

    PER_PAGE = current.PER_PAGE
    count = total_count / PER_PAGE
    if total_count % PER_PAGE:
        count += 1

    if request.extension == "json":
        return dict(count=count, total_rows=1)

    offset = PER_PAGE * (int(active) - 1)
    # Retrieve only some number of submissions from the offset
    rows = db(query).select(orderby=~db.submission.time_stamp,
                            limitby=(offset, offset + PER_PAGE))

    table = utilities.render_table(rows, cusfriends)
    return dict(table=table,
                friends=friends,
                cusfriends=cusfriends,
                total_rows=len(rows))
def pie_chart_helper():
    """
        Helper function for populating pie chart with different
        submission status of a problem
    """

    problem_link = request.post_vars["plink"]
    submission_type = "friends"

    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False:
        submission_type = "global"

    stable = db.submission
    count = stable.id.count()
    query = (stable.problem_link == problem_link)

    # Show stats only for friends and logged-in user
    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            return dict(row=[])
    else:
        # For global submissions only query for last 90 days
        query &= (stable.time_stamp > (datetime.datetime.now() - \
                                       datetime.timedelta(days=3 * 30)))

    row = db(query).select(stable.status, count, groupby=stable.status)
    return dict(row=row)
Esempio n. 12
0
def pie_chart_helper():
    """
        Helper function for populating pie chart with different
        submission status of a problem
    """

    problem_link = request.post_vars["plink"]
    submission_type = "friends"

    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False:
        submission_type = "global"

    stable = db.submission
    count = stable.id.count()
    query = (stable.problem_link == problem_link)

    # Show stats only for friends and logged-in user
    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            return dict(row=[])
    row = db(query).select(stable.status,
                           count,
                           groupby=stable.status)
    return dict(row=row)
Esempio n. 13
0
    def should_show(self):
        final_data = self.get_from_cache()
        if final_data:
            pass
        else:
            import datetime
            db = current.db
            stable = db.submission
            friends, _ = utilities.get_friends(self.user_id)
            if len(friends):
                today = datetime.datetime.today()
                last_week = today - datetime.timedelta(days=7)
                rows = db.executesql(
                    """
                    SELECT user_id, site, count(*)
                    FROM submission
                    WHERE time_stamp >= "%s" AND
                        user_id in (%s) AND custom_user_id is NULL
                    GROUP BY 1, 2
                    ORDER BY 3 DESC
                """ %
                    (str(last_week.date()), ",".join([str(x)
                                                      for x in friends])))
                final_hash = {}
                for row in rows:
                    if row[0] not in final_hash:
                        final_hash[row[0]] = {"total": 0}
                    final_hash[row[0]][row[1]] = int(row[2])
                    final_hash[row[0]]["total"] += int(row[2])

                final_data = sorted(final_hash.items(),
                                    key=lambda x: x[1]["total"],
                                    reverse=True)[:3]
            else:
                final_data = []

            self.set_to_cache(final_data)

        if len(final_data) > 0:
            self.final_data = final_data
            return True
        return False
Esempio n. 14
0
def main(argv=None):
    logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT)

    if argv is None:
        argv = sys.argv

    parser = init_argparser()
    args = parser.parse_args(argv)

    try:
        config_fname = args.config if args.config \
            else DEFAULT_TWITTER_CONFIG_FNAME
        friends = get_friends(config_fname, args.screen_name)
        print("{0} has {1} friends".format(args.screen_name, len(friends)))
    except:
        trace = traceback.format_exc()
        logging.error("OMGWTFBBQ: {0}".format(trace))
        sys.exit(1)

    # Yayyy-yah
    sys.exit(0)
Esempio n. 15
0
def pie_chart_helper():
    """
        Helper function for populating pie chart with different
        submission status of a problem
    """

    problem_link = request.post_vars["plink"]
    global_submissions = False
    if request.post_vars["global"] == "True":
        global_submissions = True

    stable = db.submission
    count = stable.id.count()
    query = (stable.problem_link == problem_link)

    # Show stats only for friends and logged-in user
    if global_submissions is False:
        if session.user_id:
            friends, cusfriends = utilities.get_friends(session.user_id)
            # The Original IDs of duplicate custom_friends
            custom_friends = []
            for cus_id in cusfriends:
                if cus_id[1] == None:
                    custom_friends.append(cus_id[0])
                else:
                    custom_friends.append(cus_id[1])

            query &= (stable.user_id.belongs(friends)) | \
                     (stable.custom_user_id.belongs(custom_friends)) | \
                     (stable.user_id == session.user_id)
        else:
            query &= (1 == 0)

    row = db(query).select(stable.status,
                           count,
                           groupby=stable.status)
    return dict(row=row)
Esempio n. 16
0
def submissions():
    """
        Retrieve submissions of the logged-in user
    """

    if len(request.args) == 0:
        active = 1
    else:
        try:
            active = int(request.args[0])
        except ValueError:
            # The pagination page number is not integer
            raise HTTP(404)
            return

    cftable = db.custom_friend
    stable = db.submission
    atable = db.auth_user
    ptable = db.problem

    # Get all the friends/custom friends of the logged-in user
    friends, cusfriends = utilities.get_friends(session.user_id)

    # The Original IDs of duplicate custom_friends
    custom_friends = []
    for cus_id in cusfriends:
        if cus_id[1] is None:
            custom_friends.append(cus_id[0])
        else:
            custom_friends.append(cus_id[1])

    query = (stable.user_id.belongs(friends)) | \
            (stable.custom_user_id.belongs(custom_friends))
    total_count = db(query).count()

    PER_PAGE = current.PER_PAGE
    count = total_count / PER_PAGE
    if total_count % PER_PAGE:
        count += 1

    if request.extension == "json":
        return dict(count=count, total_rows=1)

    user = session.auth.user
    db.sessions_today.insert(
        message="%s %s %d %s" %
        (user.first_name, user.last_name, user.id, datetime.datetime.now()))

    offset = PER_PAGE * (active - 1)
    # Retrieve only some number of submissions from the offset
    rows = db(query).select(orderby=~db.submission.time_stamp,
                            limitby=(offset, offset + PER_PAGE))

    table = utilities.render_table(rows, cusfriends)

    country_value = session.auth.user.get("country")
    country = country_value if country_value else "not-available"

    country_form = None
    if country == "not-available":
        country_form = SQLFORM(db.auth_user,
                               session.auth.user,
                               fields=["country"],
                               showid=False)
        if country_form.process(onvalidation=current.sanitize_fields).accepted:
            session.auth.user = db.auth_user(session.user_id)
            session.flash = T("Country updated!")
            redirect(URL("default", "submissions", args=1))
        elif country_form.errors:
            response.flash = T("Form has errors")

    return dict(table=table,
                friends=friends,
                cusfriends=cusfriends,
                total_rows=len(rows),
                country=country,
                country_form=country_form)
Esempio n. 17
0
def index():
    """
        The main problem page
    """

    if request.vars.has_key("pname") == False or \
       request.vars.has_key("plink") == False:

        # Disables direct entering of a URL
        session.flash = "Please click on a Problem Link"
        redirect(URL("default", "index"))

    global_submissions = False
    if request.vars.has_key("global"):
        if request.vars["global"] == "True":
            global_submissions = True

    stable = db.submission
    ptable = db.problem_tags
    problem_name = request.vars["pname"]
    problem_link = request.vars["plink"]

    query = (stable.problem_link == problem_link)

    cusfriends = []

    if global_submissions is False:
        if session.user_id:
            friends, cusfriends = utilities.get_friends(session.user_id)
            # The Original IDs of duplicate custom_friends
            custom_friends = []
            for cus_id in cusfriends:
                if cus_id[1] == None:
                    custom_friends.append(cus_id[0])
                else:
                    custom_friends.append(cus_id[1])

            query &= (stable.user_id.belongs(friends)) | \
                     (stable.custom_user_id.belongs(custom_friends)) | \
                     (stable.user_id == session.user_id)
        else:
            session.flash = "Login to view Friends' Submissions"
            new_vars = request.vars
            new_vars["global"] = True
            redirect(URL("problems", "index",
                         vars=new_vars))

    submissions = db(query).select(orderby=~stable.time_stamp)
    try:
        query = (ptable.problem_link == problem_link)
        all_tags = db(query).select(ptable.tags).first()
        if all_tags:
            all_tags = eval(all_tags["tags"])
        else:
            all_tags = []
        if all_tags != [] and all_tags != ['-']:
            tags = DIV(_class="center")
            for tag in all_tags:
                tags.append(DIV(A(tag,
                                  _href=URL("problems",
                                            "tag",
                                            vars={"q": tag, "page": 1}),
                                  _style="color: white;",
                                  _target="_blank"),
                                _class="chip"))
                tags.append(" ")
        else:
            tags = DIV("No tags available")
    except AttributeError:
        tags = DIV("No tags available")

    problem_details = TABLE(_style="font-size: 140%;")
    tbody = TBODY()
    tbody.append(TR(TD(),
                    TD(STRONG("Problem Name:")),
                    TD(problem_name,
                       _id="problem_name"),
                    TD(_id="chart_div",
                       _style="width: 50%; height: 30%;",
                       _rowspan="4")))
    tbody.append(TR(TD(),
                    TD(STRONG("Site:")),
                    TD(utilities.urltosite(problem_link).capitalize())))
    tbody.append(TR(TD(),
                    TD(STRONG("Problem Link:")),
                    TD(A(I(_class="fa fa-link"), " Link",
                         _href=problem_link,
                         _target="_blank"))))
    tbody.append(TR(TD(),
                    TD(STRONG("Tags:")),
                    TD(tags)))
    problem_details.append(tbody)

    table = utilities.render_table(submissions, cusfriends)
    switch = DIV(LABEL(H6("Friends' Submissions",
                          INPUT(_type="checkbox", _id="submission-switch"),
                          SPAN(_class="lever pink accent-3"),
                          "Global Submissions")),
                 _class="switch")
    div = TAG[""](H4("Recent Submissions"), switch, table)

    return dict(problem_details=problem_details,
                problem_name=problem_name,
                problem_link=problem_link,
                global_submissions=global_submissions,
                div=div)
Esempio n. 18
0
def trending():
    """
        Show trending problems globally and among friends
        @ToDo: Needs lot of comments explaining the code
    """

    stable = db.submission
    atable = db.auth_user
    cftable = db.custom_friend

    today = datetime.datetime.today()
    # Consider submissions only after PAST_DAYS(customisable)
    # for trending problems
    start_date = str(today - datetime.timedelta(days=current.PAST_DAYS))
    end_date = str(today)

    count = stable.id.count()

    if session.user_id:
        friends, cusfriends = utilities.get_friends(session.user_id)

        # The Original IDs of duplicate custom_friends
        custom_friends = []
        for cus_id in cusfriends:
            if cus_id[1] == None:
                custom_friends.append(cus_id[0])
            else:
                custom_friends.append(cus_id[1])

        first_query = (stable.user_id.belongs(friends))
        first_query |= (stable.custom_user_id.belongs(custom_friends))
        query = (stable.time_stamp >= start_date)
        query &= (stable.time_stamp <= end_date)
        query = first_query & query

        friend_trending = db(query).select(stable.problem_name,
                                           stable.problem_link,
                                           count,
                                           orderby=~count,
                                           groupby=stable.problem_link)

        friends = [str(x) for x in friends]
        custom_friends = [str(x) for x in custom_friends]
        friend_trending = _get_total_users(friend_trending.as_list(),
                                           friends,
                                           custom_friends,
                                           start_date,
                                           end_date)
        # Sort the rows according to the
        # number of users who solved the
        # problem in last PAST_DAYS
        rows = sorted(friend_trending, key=lambda k: k["unique"], reverse=True)
        rows = rows[:current.PROBLEMS_PER_PAGE]
        problems = []
        for problem in rows:
            submission = problem["submission"]
            problems.append([submission["problem_name"],
                             submission["problem_link"],
                             problem["_extra"]["COUNT(submission.id)"],
                             problem["unique"]])

        friend_table = _render_trending("Trending among friends",
                                        problems,
                                        "Friends")

    tptable = db.trending_problems
    rows = db(tptable).select()
    global_trending = []
    for problem in rows:
        global_trending.append([problem["problem_name"],
                                problem["problem_link"],
                                problem["submission_count"],
                                problem["user_count"]])

    global_table = _render_trending("Trending Globally",
                                    global_trending,
                                    "Users")

    if session.user_id:
        div = DIV(_class="row col s12")
        div.append(DIV(friend_table, _class="col s6"))
        div.append(DIV(global_table, _class="col s6"))
    else:
        div = DIV(global_table, _class="center")

    return dict(div=div)
Esempio n. 19
0
def trending():
    """
        Show trending problems globally and among friends
        @ToDo: Needs lot of comments explaining the code
    """

    stable = db.submission

    today = datetime.datetime.today()
    # Consider submissions only after PAST_DAYS(customizable)
    # for trending problems
    start_date = str(today - datetime.timedelta(days=current.PAST_DAYS))
    query = (stable.time_stamp >= start_date)
    last_submissions = db(query).select(stable.problem_name,
                                        stable.problem_link, stable.user_id,
                                        stable.custom_user_id)

    if auth.is_logged_in():
        friends, cusfriends = utilities.get_friends(session.user_id)

        # The Original IDs of duplicate custom_friends
        custom_friends = []
        for cus_id in cusfriends:
            if cus_id[1] is None:
                custom_friends.append(cus_id[0])
            else:
                custom_friends.append(cus_id[1])

        friends, custom_friends = set(friends), set(custom_friends)

    problems_dict = {}
    friends_problems_dict = {}
    for submission in last_submissions:
        plink = submission.problem_link
        pname = submission.problem_name
        uid = submission.user_id
        cid = submission.custom_user_id

        if plink not in problems_dict:
            problems_dict[plink] = {
                "name": pname,
                "total_submissions": 0,
                "users": set([]),
                "custom_users": set([])
            }

        pdict = problems_dict[plink]
        pdict["total_submissions"] += 1
        if uid:
            pdict["users"].add(uid)
        else:
            pdict["custom_users"].add(cid)

        if auth.is_logged_in() and \
           ((uid and uid in friends) or \
            (cid and cid in custom_friends)):

            if plink not in friends_problems_dict:
                friends_problems_dict[plink] = {
                    "name": pname,
                    "total_submissions": 0,
                    "users": set([]),
                    "custom_users": set([])
                }
            fproblems_dict = friends_problems_dict[plink]
            fproblems_dict["total_submissions"] += 1
            if uid:
                fproblems_dict["users"].add(uid)
            else:
                fproblems_dict["custom_users"].add(cid)

    # Sort the rows according to the number of users
    # who solved the problem in last PAST_DAYS
    custom_compare = lambda x: (len(x[1]["users"]) + \
                                len(x[1]["custom_users"]),
                                x[1]["total_submissions"])

    global_trending = sorted(problems_dict.items(),
                             key=custom_compare,
                             reverse=True)

    global_table = _render_trending(
        T("Trending Globally"), global_trending[:current.PROBLEMS_PER_PAGE],
        T("Users"))
    if auth.is_logged_in():
        # Show table with trending problems amongst friends
        friends_trending = sorted(friends_problems_dict.items(),
                                  key=custom_compare,
                                  reverse=True)

        friend_table = _render_trending(
            T("Trending among friends"),
            friends_trending[:current.PROBLEMS_PER_PAGE], T("Friends"))

        div = DIV(DIV(friend_table, _class="col offset-s1 s4 z-depth-2"),
                  DIV(global_table, _class="col offset-s2 s4 z-depth-2"),
                  _class="row col s12")
    else:
        # Show table with globally trending problems
        div = DIV(DIV(global_table, _class="col offset-s1 s10 z-depth-2"),
                  _class="row center")

    return dict(div=div)
def index():
    """
        The main problem page
    """

    if request.vars.has_key("pname") == False or \
       request.vars.has_key("plink") == False:

        # Disables direct entering of a URL
        session.flash = "Please click on a Problem Link"
        redirect(URL("default", "index"))

    stable = db.submission
    ptable = db.problem_tags
    problem_name = request.vars["pname"]
    problem_link = request.vars["plink"]

    query = (stable.problem_link == problem_link)
    # If a user is logged-in then show his/her friends' submissions
    if session.auth:
        friends, cusfriends = utilities.get_friends(session.user_id)
        query &= (stable.user_id.belongs(friends)) | \
                 (stable.custom_user_id.belongs(cusfriends)) | \
                 (stable.user_id == session.user_id)

    submissions = db(query).select(orderby=~stable.time_stamp)

    try:
        query = (ptable.problem_link == problem_link)
        all_tags = db(query).select(ptable.tags).first()
        if all_tags:
            all_tags = eval(all_tags["tags"])
        else:
            all_tags = []
        if all_tags != [] and all_tags != ['-']:
            tags = DIV(_class="center")
            for tag in all_tags:
                tags.append(
                    DIV(A(tag,
                          _href=URL("problems", "tag", vars={"q": tag}),
                          _style="color: white;",
                          _target="_blank"),
                        _class="chip"))
                tags.append(" ")
        else:
            tags = DIV("No tags available")
    except AttributeError:
        tags = DIV("No tags available")

    problem_details = TABLE(_style="font-size: 140%;")
    tbody = TBODY()
    tbody.append(
        TR(
            TD(), TD(STRONG("Problem Name:")),
            TD(problem_name, _id="problem_name"),
            TD(_id="chart_div",
               _style="width: 50%; height: 30%;",
               _rowspan="4")))
    tbody.append(
        TR(TD(), TD(STRONG("Site:")),
           TD(urltosite(problem_link).capitalize())))
    tbody.append(
        TR(
            TD(), TD(STRONG("Problem Link:")),
            TD(
                A(I(_class="fa fa-link"),
                  " Link",
                  _href=problem_link,
                  _target="_blank"))))
    tbody.append(TR(TD(), TD(STRONG("Tags:")), TD(tags)))
    problem_details.append(tbody)
    table = utilities.render_table(submissions)

    return dict(problem_details=problem_details,
                problem_name=problem_name,
                problem_link=problem_link,
                table=table)
Esempio n. 21
0
def leaderboard():
    """
        Get a table with users sorted by rating
    """

    specific_institute = False
    atable = db.auth_user
    cftable = db.custom_friend

    global_leaderboard = False
    if request.vars.has_key("global"):
        if request.vars["global"] == "True":
            global_leaderboard = True
        else:
            if not auth.is_logged_in():
                response.flash = "Login to see Friends Leaderboard"
                global_leaderboard = True
    else:
        if not auth.is_logged_in():
            global_leaderboard = True

    heading = "Global Leaderboard"
    afields = [
        "first_name", "last_name", "stopstalk_handle", "rating", "institute",
        "per_day", "prev_rating", "per_day_change"
    ]
    cfields = afields + ["duplicate_cu"]

    aquery = (atable.id > 0)
    cquery = (cftable.id > 0)
    if global_leaderboard is False:
        if auth.is_logged_in():
            heading = "Friends Leaderboard"
            friends, cusfriends = utilities.get_friends(session.user_id)
            custom_friends = [x[0] for x in cusfriends]

            # Add logged-in user to leaderboard
            friends.append(session.user_id)
            aquery &= (atable.id.belongs(friends))
            cquery &= (cftable.id.belongs(custom_friends))
        else:
            aquery &= (1 == 0)
            cquery &= (1 == 0)

    # Do not display unverified users in the leaderboard
    aquery &= (atable.registration_key == "")

    if request.vars.has_key("q"):
        heading = "Institute Leaderboard"
        institute = request.vars["q"]

        if institute != "":
            specific_institute = True
            aquery &= (atable.institute == institute)
            cquery &= (cftable.institute == institute)
            reg_users = db(aquery).select(*afields)
            custom_users = db(cquery).select(*cfields)

    if specific_institute is False:
        reg_users = db(aquery).select(*afields)
        custom_users = db(cquery).select(*cfields)

    users = []
    for user in reg_users:
        users.append(
            (user.first_name + " " + user.last_name, user.stopstalk_handle,
             user.institute, int(user.rating), float(user.per_day_change),
             False, int(user.rating) - int(user.prev_rating)))

    for user in custom_users:
        if user.duplicate_cu:
            record = cftable(user.duplicate_cu)
        else:
            record = user
        users.append(
            (user.first_name + " " + user.last_name, user.stopstalk_handle,
             user.institute, int(record.rating), float(record.per_day_change),
             True, int(record.rating) - int(record.prev_rating)))

    # Sort users according to the rating
    users = sorted(users, key=lambda x: x[3], reverse=True)

    table = TABLE(_class="centered striped")
    table.append(
        THEAD(
            TR(TH("Rank"), TH("Name"), TH("StopStalk Handle"), TH("Institute"),
               TH("StopStalk Rating"), TH("Rating Changes"),
               TH("Per Day Changes"))))

    tbody = TBODY()
    rank = 1
    for i in users:

        if i[5]:
            span = SPAN(_class="orange tooltipped",
                        data={"position": "right",
                              "delay": "50",
                              "tooltip": "Custom User"},
                        _style="cursor: pointer; " + \
                                "float:right; " + \
                                "height:10px; " + \
                                "width:10px; " + \
                                "border-radius: 50%;")
        else:
            span = SPAN()

        tr = TR()
        tr.append(TD(str(rank) + "."))
        tr.append(TD(DIV(span, DIV(i[0]))))
        tr.append(
            TD(
                A(i[1],
                  _href=URL("user", "profile", args=[i[1]]),
                  _target="_blank")))
        tr.append(
            TD(
                A(i[2],
                  _href=URL("default",
                            "leaderboard",
                            vars={
                                "q": i[2],
                                "global": global_leaderboard
                            }))))
        tr.append(TD(i[3]))
        if i[6] > 0:
            tr.append(
                TD(B("+%s" % str(i[6])), _class="green-text text-darken-2"))
        elif i[6] < 0:
            tr.append(TD(B(i[6]), _class="red-text text-darken-2"))
        else:
            tr.append(TD(i[6], _class="blue-text text-darken-2"))

        diff = "{:1.5f}".format(i[4])

        if float(diff) == 0.0:
            tr.append(TD("+" + diff, " ", I(_class="fa fa-minus")))
        elif i[4] > 0:
            tr.append(
                TD("+" + str(diff), " ",
                   I(_class="fa fa-chevron-circle-up", _style="color: #0f0;")))
        elif i[4] < 0:
            tr.append(
                TD(
                    diff, " ",
                    I(_class="fa fa-chevron-circle-down",
                      _style="color: #f00;")))

        tbody.append(tr)
        rank += 1

    table.append(tbody)
    switch = DIV(LABEL(
        H6("Friends' Submissions",
           INPUT(_type="checkbox", _id="submission-switch"),
           SPAN(_class="lever pink accent-3"), "Global Submissions")),
                 _class="switch")
    div = TAG[""](switch, table)
    return dict(div=div,
                heading=heading,
                global_leaderboard=global_leaderboard)
Esempio n. 22
0
def submissions():
    """
        Retrieve submissions of the logged-in user
    """

    if len(request.args) == 0:
        active = "1"
    else:
        active = request.args[0]

    cftable = db.custom_friend
    ftable = db.friends
    stable = db.submission
    atable = db.auth_user

    # Get all the friends/custom friends of the logged-in user
    friends, cusfriends = utilities.get_friends(session["user_id"])

    query = (stable.user_id.belongs(friends))
    query |= (stable.custom_user_id.belongs(cusfriends))
    total_count = db(query).count()

    PER_PAGE = current.PER_PAGE
    count = total_count / PER_PAGE
    if total_count % PER_PAGE:
        count += 1

    friend_query = (atable.id.belongs(friends))
    friends_list = db(friend_query).select(atable.id,
                                           atable.first_name,
                                           atable.last_name)
    all_friends = []
    for friend in friends_list:
        friend_name = friend["first_name"] + " " + friend["last_name"]
        all_friends.append([friend["id"],
                            friend_name])

    cusfriend_query = (cftable.id.belongs(cusfriends))
    cusfriends_list = db(cusfriend_query).select(cftable.id,
                                                 cftable.first_name,
                                                 cftable.last_name)
    all_custom_friends = []
    for friend in cusfriends_list:
        friend_name = friend["first_name"] + " " + friend["last_name"]
        all_custom_friends.append([friend["id"],
                                   friend_name])

    if request.extension == "json":
        return dict(count=count,
                    friends=all_friends,
                    cusfriends=all_custom_friends)

    offset = PER_PAGE * (int(active) - 1)
    # Retrieve only some number of submissions from the offset
    rows = db(query).select(orderby=~db.submission.time_stamp,
                            limitby=(offset, offset + PER_PAGE))

    table = utilities.render_table(rows)
    return dict(table=table,
                friends=friends,
                cusfriends=cusfriends)
Esempio n. 23
0
def index():
    """
        The main problem page
    """

    if request.vars.has_key("pname") == False or \
       request.vars.has_key("plink") == False:

        # Disables direct entering of a URL
        session.flash = "Please click on a Problem Link"
        redirect(URL("default", "index"))

    stable = db.submission
    ptable = db.problem_tags
    problem_name = request.vars["pname"]
    problem_link = request.vars["plink"]

    query = (stable.problem_link == problem_link)
    # If a user is logged-in then show his/her friends' submissions
    if session.auth:
        friends, cusfriends = utilities.get_friends(session.user_id)
        query &= (stable.user_id.belongs(friends)) | \
                 (stable.custom_user_id.belongs(cusfriends)) | \
                 (stable.user_id == session.user_id)

    submissions = db(query).select(orderby=~stable.time_stamp)

    try:
        query = (ptable.problem_link == problem_link)
        all_tags = db(query).select(ptable.tags).first()
        if all_tags:
            all_tags = eval(all_tags["tags"])
        else:
            all_tags = []
        if all_tags != [] and all_tags != ['-']:
            tags = DIV(_class="center")
            for tag in all_tags:
                tags.append(DIV(A(tag,
                                  _href=URL("problems",
                                            "tag",
                                            vars={"q": tag}),
                                  _style="color: white;",
                                  _target="_blank"),
                                _class="chip"))
                tags.append(" ")
        else:
            tags = DIV("No tags available")
    except AttributeError:
        tags = DIV("No tags available")

    problem_details = TABLE(_style="font-size: 140%;")
    tbody = TBODY()
    tbody.append(TR(TD(),
                    TD(STRONG("Problem Name:")),
                    TD(problem_name,
                       _id="problem_name"),
                    TD(_id="chart_div",
                       _style="width: 50%; height: 30%;",
                       _rowspan="4")))
    tbody.append(TR(TD(),
                    TD(STRONG("Site:")),
                    TD(urltosite(problem_link).capitalize())))
    tbody.append(TR(TD(),
                    TD(STRONG("Problem Link:")),
                    TD(A(I(_class="fa fa-link"), " Link",
                         _href=problem_link,
                         _target="_blank"))))
    tbody.append(TR(TD(),
                    TD(STRONG("Tags:")),
                    TD(tags)))
    problem_details.append(tbody)
    table = utilities.render_table(submissions)

    return dict(problem_details=problem_details,
                problem_name=problem_name,
                problem_link=problem_link,
                table=table)
Esempio n. 24
0
def trending():
    """
        Show trending problems globally and among friends
        @ToDo: Needs lot of comments explaining the code
    """

    stable = db.submission

    today = datetime.datetime.today()
    # Consider submissions only after PAST_DAYS(customizable)
    # for trending problems
    start_date = str(today - datetime.timedelta(days=current.PAST_DAYS))
    query = (stable.time_stamp >= start_date)
    last_submissions = db(query).select(stable.problem_name,
                                        stable.problem_link,
                                        stable.user_id,
                                        stable.custom_user_id)

    if auth.is_logged_in():
        friends, cusfriends = utilities.get_friends(session.user_id)

        # The Original IDs of duplicate custom_friends
        custom_friends = []
        for cus_id in cusfriends:
            if cus_id[1] is None:
                custom_friends.append(cus_id[0])
            else:
                custom_friends.append(cus_id[1])

    problems_dict = {}
    friends_problems_dict = {}
    for submission in last_submissions:
        plink = submission.problem_link
        pname = submission.problem_name
        uid = submission.user_id
        cid = submission.custom_user_id

        # @ToDo: Improve this code
        if problems_dict.has_key(plink):
            problems_dict[plink]["total_submissions"] += 1
        else:
            problems_dict[plink] = {"name": pname,
                                    "total_submissions": 1,
                                    "users": set([]),
                                    "custom_users": set([])}

        if auth.is_logged_in() and \
           ((uid and uid in friends) or \
            (cid and cid in custom_friends)):

            if friends_problems_dict.has_key(plink):
                friends_problems_dict[plink]["total_submissions"] += 1
            else:
                friends_problems_dict[plink] = {"name": pname,
                                                "total_submissions": 1,
                                                "users": set([]),
                                                "custom_users": set([])}
            if uid:
                friends_problems_dict[plink]["users"].add(uid)
            else:
                friends_problems_dict[plink]["custom_users"].add(cid)

        if uid:
            problems_dict[plink]["users"].add(uid)
        else:
            problems_dict[plink]["custom_users"].add(cid)

    # Sort the rows according to the number of users
    # who solved the problem in last PAST_DAYS
    custom_compare = lambda x: (len(x[1]["users"]) + \
                                len(x[1]["custom_users"]),
                                x[1]["total_submissions"])

    global_trending = sorted(problems_dict.items(),
                             key=custom_compare,
                             reverse=True)

    global_table = _render_trending("Trending Globally",
                                    global_trending[:current.PROBLEMS_PER_PAGE],
                                    "Users")
    if auth.is_logged_in():
        friends_trending = sorted(friends_problems_dict.items(),
                                  key=custom_compare,
                                  reverse=True)

        friend_table = _render_trending("Trending among friends",
                                        friends_trending[:current.PROBLEMS_PER_PAGE],
                                        "Friends")

        div = DIV(DIV(friend_table, _class="col s6"),
                  DIV(global_table, _class="col s6"),
                  _class="row col s12")
    else:
        div = DIV(global_table, _class="center")

    return dict(div=div)
Esempio n. 25
0
def index():
    """
        The main problem page
    """
    from json import dumps

    if request.vars.has_key("pname") is False or \
       request.vars.has_key("plink") is False:

        # Disables direct entering of a URL
        session.flash = T("Please click on a Problem Link")
        redirect(URL("default", "index"))

    submission_type = "friends"
    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False and submission_type != "global":
        response.flash = T("Login to view your/friends' submissions")
        submission_type = "global"

    stable = db.submission
    ptable = db.problem

    problem_name = request.vars["pname"]
    problem_link = request.vars["plink"]

    query = (stable.problem_link == problem_link)
    cusfriends = []

    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            response.flash = T("Login to view your/friends' submissions")

    submissions = db(query).select(orderby=~stable.time_stamp)
    problem_record = db(ptable.link == problem_link).select().first()
    try:
        all_tags = problem_record.tags
        if all_tags:
            all_tags = eval(all_tags)
        else:
            all_tags = ["-"]
    except AttributeError:
        all_tags = ["-"]

    site = utilities.urltosite(problem_link).capitalize()
    problem_details = DIV(_class="row")
    details_table = TABLE(_style="font-size: 140%; float: left; width: 50%;")
    problem_class = ""

    link_class = utilities.get_link_class(problem_link, session.user_id)
    link_title = (" ".join(link_class.split("-"))).capitalize()

    tbody = TBODY()
    tbody.append(
        TR(
            TD(), TD(STRONG(T("Problem Name") + ":")),
            TD(utilities.problem_widget(problem_name,
                                        problem_link,
                                        link_class,
                                        link_title,
                                        anchor=False),
               _id="problem_name")))
    tbody.append(TR(TD(), TD(STRONG(T("Site") + ":")), TD(site)))

    links = DIV(
        DIV(A(I(_class="fa fa-link"),
              " " + T("Problem"),
              _href=problem_link,
              _class="problem-page-site-link",
              _style="color: black;",
              _target="blank"),
            _class="chip lime accent-3"))

    row = db(ptable.link == problem_link).select().first()
    if row:
        links.append(" ")
        links.append(
            DIV(A(I(_class="fa fa-book"),
                  " " + T("Editorials"),
                  _href=URL("problems", "editorials", args=row.id),
                  _class="problem-page-editorials",
                  _style="color: white;",
                  _target="_blank"),
                _class="chip deep-purple darken-1"))

    tbody.append(TR(TD(), TD(STRONG(T("Links") + ":")), links))

    suggest_tags_class = "disabled btn chip tooltipped suggest-tags-plus-logged-out"
    suggest_tags_data = {
        "position": "right",
        "delay": "50",
        "tooltip": T("Login to suggest tags")
    }
    suggest_tags_id = "disabled-suggest-tags"
    if auth.is_logged_in():
        suggest_tags_class = "green chip waves-light waves-effect tooltipped suggest-tags-plus modal-trigger"
        suggest_tags_data["target"] = "suggest-tags-modal"
        suggest_tags_data["tooltip"] = T("Suggest tags")
        suggest_tags_id = "suggest-trigger"

    tbody.append(
        TR(
            TD(), TD(STRONG(T("Tags") + ":")),
            TD(
                DIV(
                    SPAN(A(I(_class="fa fa-tag"),
                           " Show Tags",
                           _id="show-tags",
                           _class="chip orange darken-1",
                           data={"tags": dumps(all_tags)}),
                         _id="tags-span"), " ",
                    BUTTON(I(_class="fa fa-plus"),
                           _style="color: white; margin-top: 7px;",
                           _class=suggest_tags_class,
                           _id=suggest_tags_id,
                           data=suggest_tags_data)))))

    details_table.append(tbody)
    problem_details.append(details_table)
    problem_details.append(
        DIV(_style="width: 50%; margin-top: 3%",
            _id="chart_div",
            _class="right"))

    table = utilities.render_table(submissions, cusfriends, session.user_id)

    return dict(site=site,
                problem_details=problem_details,
                problem_name=problem_name,
                problem_link=problem_link,
                submission_type=submission_type,
                table=table)
Esempio n. 26
0
def index():
    """
        The main problem page
    """

    if request.vars.has_key("pname") == False or \
       request.vars.has_key("plink") == False:

        # Disables direct entering of a URL
        session.flash = "Please click on a Problem Link"
        redirect(URL("default", "index"))

    global_submissions = False
    if request.vars.has_key("global"):
        if request.vars["global"] == "True":
            global_submissions = True

    stable = db.submission
    ptable = db.problem_tags
    problem_name = request.vars["pname"]
    problem_link = request.vars["plink"]

    query = (stable.problem_link == problem_link)

    cusfriends = []

    if global_submissions is False:
        if session.user_id:
            friends, cusfriends = utilities.get_friends(session.user_id)
            # The Original IDs of duplicate custom_friends
            custom_friends = []
            for cus_id in cusfriends:
                if cus_id[1] == None:
                    custom_friends.append(cus_id[0])
                else:
                    custom_friends.append(cus_id[1])

            query &= (stable.user_id.belongs(friends)) | \
                     (stable.custom_user_id.belongs(custom_friends)) | \
                     (stable.user_id == session.user_id)
        else:
            session.flash = "Login to view Friends' Submissions"
            new_vars = request.vars
            new_vars["global"] = True
            redirect(URL("problems", "index", vars=new_vars))

    submissions = db(query).select(orderby=~stable.time_stamp)
    try:
        query = (ptable.problem_link == problem_link)
        all_tags = db(query).select(ptable.tags).first()
        if all_tags:
            all_tags = eval(all_tags["tags"])
        else:
            all_tags = []
        if all_tags != [] and all_tags != ['-']:
            tags = DIV(_class="center")
            for tag in all_tags:
                tags.append(
                    DIV(A(tag,
                          _href=URL("problems",
                                    "tag",
                                    vars={
                                        "q": tag,
                                        "page": 1
                                    }),
                          _style="color: white;",
                          _target="_blank"),
                        _class="chip"))
                tags.append(" ")
        else:
            tags = DIV("No tags available")
    except AttributeError:
        tags = DIV("No tags available")

    problem_details = TABLE(_style="font-size: 140%;")
    tbody = TBODY()
    tbody.append(
        TR(
            TD(), TD(STRONG("Problem Name:")),
            TD(problem_name, _id="problem_name"),
            TD(_id="chart_div",
               _style="width: 50%; height: 30%;",
               _rowspan="4")))
    tbody.append(
        TR(TD(), TD(STRONG("Site:")),
           TD(utilities.urltosite(problem_link).capitalize())))
    tbody.append(
        TR(
            TD(), TD(STRONG("Problem Link:")),
            TD(
                A(I(_class="fa fa-link"),
                  " Link",
                  _href=problem_link,
                  _target="_blank"))))
    tbody.append(TR(TD(), TD(STRONG("Tags:")), TD(tags)))
    problem_details.append(tbody)

    table = utilities.render_table(submissions, cusfriends)
    switch = DIV(LABEL(
        H6("Friends' Submissions",
           INPUT(_type="checkbox", _id="submission-switch"),
           SPAN(_class="lever pink accent-3"), "Global Submissions")),
                 _class="switch")
    div = TAG[""](H4("Recent Submissions"), switch, table)

    return dict(problem_details=problem_details,
                problem_name=problem_name,
                problem_link=problem_link,
                global_submissions=global_submissions,
                div=div)
Esempio n. 27
0
def index():
    """
        The main problem page
    """
    from json import dumps

    if request.vars.has_key("problem_id") is False:
        # Disables direct entering of a URL
        session.flash = T("Please click on a Problem Link")
        redirect(URL("default", "index"))
        return

    try:
        problem_id = int(request.vars["problem_id"])
    except ValueError:
        session.flash = T("Invalid problem!")
        redirect(URL("default", "index"))
        return

    submission_type = "friends"
    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False and submission_type != "global":
        response.flash = T("Login to view your/friends' submissions")
        submission_type = "global"

    stable = db.submission
    ptable = db.problem
    pstable = db.problem_setters

    problem_record = ptable(problem_id)
    if problem_record is None:
        session.flash = T("Please click on a Problem Link")
        redirect(URL("default", "index"))

    setters = db(pstable.problem_id == problem_id).select(pstable.handle)
    setters = [x.handle for x in setters]
    query = (stable.problem_id == problem_id)
    cusfriends = []

    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            response.flash = T("Login to view your/friends' submissions")

    submissions = db(query).select(orderby=~stable.time_stamp,
                                   limitby=(0, 300))
    try:
        all_tags = problem_record.tags
        if all_tags:
            all_tags = eval(all_tags)
        else:
            all_tags = ["-"]
    except AttributeError:
        all_tags = ["-"]

    lower_site = utilities.urltosite(problem_record.link)
    site = utilities.get_actual_site(lower_site)
    problem_details = DIV(_class="row")
    details_table = TABLE(_style="font-size: 140%; float: left; width: 50%;")
    problem_class = ""

    link_class, link_title = utilities.get_link_class(problem_id, session.user_id)

    tbody = TBODY()
    tbody.append(TR(TD(),
                    TD(STRONG(T("Problem Name") + ":")),
                    TD(utilities.problem_widget(problem_record.name,
                                                problem_record.link,
                                                link_class,
                                                link_title,
                                                problem_id,
                                                anchor=False,
                                                disable_todo=True),
                       _id="problem_name")))
    tbody.append(TR(TD(),
                    TD(STRONG(T("Site") + ":")),
                    TD(site)))

    links = DIV(DIV(A(I(_class="fa fa-link"), " " + T("Problem"),
                      _href=problem_record.link,
                      _class="problem-page-site-link",
                      _style="color: black;",
                      _target="blank"),
                    _class="chip lime accent-3"),
                " ",
                DIV(A(I(_class="fa fa-book"), " " + T("Editorials"),
                      _href=URL("problems", "editorials", args=problem_record.id),
                      _class="problem-page-editorials",
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip deep-purple darken-1",
                    _id="problem-page-editorial-button"))

    if auth.is_logged_in():
        links.append(DIV(A(I(_class="fa fa-edit"), " " + T("Suggest Difficulty"),
                             _style="color: white;"),
                         _class="chip",
                         _style="background-color: #9b4da9; cursor: pointer;",
                         _id="problem-page-difficulty-button"))
    tbody.append(TR(TD(),
                    TD(STRONG(T("Links") + ":")),
                    links))

    suggest_tags_class = "disabled btn chip tooltipped suggest-tags-plus-logged-out"
    suggest_tags_data = {"position": "right",
                         "delay": "50",
                         "tooltip": T("Login to suggest tags")}
    suggest_tags_id = "disabled-suggest-tags"
    if auth.is_logged_in():
        suggest_tags_class = "green chip waves-light waves-effect tooltipped suggest-tags-plus modal-trigger"
        suggest_tags_data["target"] = "suggest-tags-modal"
        suggest_tags_data["tooltip"] = T("Suggest tags")
        suggest_tags_id = "suggest-trigger"

    tbody.append(TR(TD(),
                    TD(STRONG(T("Tags") + ":")),
                    TD(DIV(SPAN(A(I(_class="fa fa-tag"), " Show Tags",
                                 _id="show-tags",
                                 _class="chip orange darken-1",
                                 data={"tags": dumps(all_tags)}),
                                _id="tags-span"),
                           " ",
                           BUTTON(I(_class="fa fa-plus"),
                                  _style="color: white; margin-top: 7px;",
                                  _class=suggest_tags_class,
                                  _id=suggest_tags_id,
                                  data=suggest_tags_data)))))

    if len(setters) > 0:
        tbody.append(TR(TD(),
                        TD(STRONG(T("Problem setters") + ":")),
                        TD(DIV(utilities.problem_setters_widget(setters,
                                                                site)))))

    details_table.append(tbody)
    problem_details.append(details_table)
    problem_details.append(DIV(_style="width: 50%; height: 200px; margin-top: 3%",
                               _id="chart_div",
                               _class="right"))

    if len(submissions):
        table = utilities.render_table(submissions, cusfriends, session.user_id)
    else:
        table = DIV(T("No submissions found"))

    return dict(site=site,
                problem_details=problem_details,
                problem_name=problem_record.name,
                problem_link=problem_record.link,
                problem_id=problem_id,
                submission_type=submission_type,
                submission_length=len(submissions),
                table=table)
Esempio n. 28
0
def leaderboard():
    """
        Get a table with users sorted by rating
    """

    specific_institute = False
    atable = db.auth_user

    global_leaderboard = False
    if request.vars.has_key("global"):
        if request.vars["global"] == "True":
            global_leaderboard = True
        else:
            if not auth.is_logged_in():
                response.flash = T("Login to see Friends Leaderboard")
                global_leaderboard = True
    else:
        if not auth.is_logged_in():
            global_leaderboard = True

    heading = T("Global Leaderboard")
    afields = [
        "first_name", "last_name", "institute", "rating", "per_day",
        "stopstalk_handle", "prev_rating", "per_day_change", "country"
    ]

    aquery = (atable.id > 0)
    if global_leaderboard is False:
        if auth.is_logged_in():
            heading = T("Friends Leaderboard")
            friends, _ = utilities.get_friends(session.user_id, False)

            # Add logged-in user to leaderboard
            friends.append(session.user_id)
            aquery &= (atable.id.belongs(friends))
        else:
            aquery = False

    # Do not display unverified users in the leaderboard
    aquery &= (atable.registration_key == "")

    if request.vars.has_key("q"):
        heading = T("Institute Leaderboard")
        institute = request.vars["q"]

        if institute != "":
            specific_institute = True
            aquery &= (atable.institute == institute)
            reg_users = db(aquery).select(*afields)

    if specific_institute is False:
        reg_users = db(aquery).select(*afields)

    users = []

    def _update_users(user_list):

        for user in user_list:
            record = user
            users.append(
                (user.first_name + " " + user.last_name, user.stopstalk_handle,
                 user.institute, int(record.rating),
                 float(record.per_day_change),
                 int(record.rating) - int(record.prev_rating), record.country))

    _update_users(reg_users)

    # Sort users according to the rating
    users = sorted(users, key=lambda x: x[3], reverse=True)

    table = TABLE(_class="centered bordered")
    table.append(
        THEAD(
            TR(TH(T("Rank")), TH(T("Country")), TH(T("Name")),
               TH(T("StopStalk Handle")), TH(T("Institute")),
               TH(T("StopStalk Rating")), TH(T("Rating Changes")),
               TH(T("Per Day Changes")))))

    tbody = TBODY()
    rank = 1

    for i in users:
        tr = TR()
        append = tr.append
        append(TD(str(rank) + "."))
        if i[6]:
            append(TD(SPAN(_class="flag-icon flag-icon-" + \
                                  current.all_countries[i[6]].lower(),
                           _title=i[6])))
        else:
            append(TD())
        append(TD(DIV(DIV(i[0]))))
        append(
            TD(
                A(i[1],
                  _href=URL("user", "profile", args=[i[1]]),
                  _target="_blank")))
        append(
            TD(
                A(i[2],
                  _href=URL("default",
                            "leaderboard",
                            vars={
                                "q": i[2],
                                "global": global_leaderboard
                            }))))
        append(TD(i[3]))
        if i[5] > 0:
            append(TD(B("+" + str(i[5])), _class="green-text text-darken-2"))
        elif i[5] < 0:
            append(TD(B(i[5]), _class="red-text text-darken-2"))
        else:
            append(TD(i[5], _class="blue-text text-darken-2"))

        diff = "{:1.5f}".format(i[4])

        if float(diff) == 0.0:
            append(TD("+" + diff, " ", I(_class="fa fa-minus")))
        elif i[4] > 0:
            append(
                TD("+" + str(diff), " ",
                   I(_class="fa fa-chevron-circle-up", _style="color: #0f0;")))
        elif i[4] < 0:
            append(
                TD(
                    diff, " ",
                    I(_class="fa fa-chevron-circle-down",
                      _style="color: #f00;")))

        tbody.append(tr)
        rank += 1

    table.append(tbody)
    switch = DIV(LABEL(
        H6(T("Friends"), INPUT(_type="checkbox", _id="submission-switch"),
           SPAN(_class="lever pink accent-3"), T("Global"))),
                 _class="switch")
    div = TAG[""](switch, table)
    return dict(div=div,
                heading=heading,
                global_leaderboard=global_leaderboard)
Esempio n. 29
0
def leaderboard():
    """
        Get a table with users sorted by rating
    """

    specific_institute = False
    atable = db.auth_user
    cftable = db.custom_friend

    global_leaderboard = False
    if request.vars.has_key("global"):
        if request.vars["global"] == "True":
            global_leaderboard = True
        else:
            if not auth.is_logged_in():
                response.flash = "Login to see Friends Leaderboard"
                global_leaderboard = True
    else:
        if not auth.is_logged_in():
            global_leaderboard = True

    heading = "Global Leaderboard"
    afields = ["first_name", "last_name", "stopstalk_handle",
               "institute", "per_day", "rating"]
    cfields = afields + ["duplicate_cu"]

    aquery = (atable.id > 0)
    cquery = (cftable.id > 0)
    if global_leaderboard is False:
        if auth.is_logged_in():
            heading = "Friends Leaderboard"
            friends, cusfriends = utilities.get_friends(session.user_id)
            custom_friends = [x[0] for x in cusfriends]

            # Add logged-in user to leaderboard
            friends.append(session.user_id)
            aquery &= (atable.id.belongs(friends))
            cquery &= (cftable.id.belongs(custom_friends))
        else:
            aquery &= (1 == 0)
            cquery &= (1 == 0)

    if request.vars.has_key("q"):
        heading = "Institute Leaderboard"
        institute = request.vars["q"]

        if institute != "":
            specific_institute = True
            aquery &= (atable.institute == institute)
            cquery &= (cftable.institute == institute)
            reg_users = db(aquery).select(*afields)
            custom_users = db(cquery).select(*cfields)

    if specific_institute is False:
        reg_users = db(aquery).select(*afields)
        custom_users = db(cquery).select(*cfields)

    # Find the total solved problems(Lesser than total accepted)
    solved_count = {}
    sql = """
             SELECT stopstalk_handle, COUNT(DISTINCT(problem_name))
             FROM submission
             WHERE status = 'AC'
             GROUP BY user_id, custom_user_id;
          """
    tmplist = db.executesql(sql)
    for user in tmplist:
        solved_count[user[0]] = user[1]

    complete_dict = {}
    # Prepare a list of stopstalk_handles of the
    # users relevant to the requested leaderboard
    friends_stopstalk_handles = []
    for x in reg_users:
        friends_stopstalk_handles.append("'" + x.stopstalk_handle + "'")
        complete_dict[x.stopstalk_handle] = []

    for custom_user in custom_users:
        stopstalk_handle = custom_user.stopstalk_handle
        if custom_user.duplicate_cu:
            stopstalk_handle = cftable(custom_user.duplicate_cu).stopstalk_handle
        friends_stopstalk_handles.append("'" + stopstalk_handle + "'")
        complete_dict[stopstalk_handle] = []

    if friends_stopstalk_handles == []:
        friends_stopstalk_handles = ["-1"]

    # Build the complex SQL query
    sql_query = """
                    SELECT stopstalk_handle, DATE(time_stamp), COUNT(*) as cnt
                    FROM submission
                    WHERE stopstalk_handle in (%s)
                    GROUP BY stopstalk_handle, DATE(submission.time_stamp)
                    ORDER BY time_stamp;
                """ % (", ".join(friends_stopstalk_handles))

    user_rows = db.executesql(sql_query)
    for user in user_rows:
        if complete_dict[user[0]] != []:
            complete_dict[user[0]].append((user[1], user[2]))
        else:
            complete_dict[user[0]] = [(user[1], user[2])]

    users = []
    for user in reg_users:
        try:
            solved = solved_count[user.stopstalk_handle]
        except KeyError:
            solved = 0

        tup = utilities.compute_row(user, complete_dict, solved)
        if tup is not ():
            users.append(tup)

    for user in custom_users:
        try:
            if user.duplicate_cu:
                orig_user = cftable(user.duplicate_cu)
                solved = solved_count[orig_user.stopstalk_handle]
            else:
                solved = solved_count[user.stopstalk_handle]
        except KeyError:
            solved = 0
        tup = utilities.compute_row(user, complete_dict, solved, True)
        if tup is not ():
            users.append(tup)

    # Sort users according to the rating
    users = sorted(users, key=lambda x: x[3], reverse=True)

    table = TABLE(_class="centered striped")
    table.append(THEAD(TR(TH("Rank"),
                          TH("Name"),
                          TH("StopStalk Handle"),
                          TH("Institute"),
                          TH("StopStalk Rating"),
                          TH("Rating Changes"),
                          TH("Per Day Changes"))))

    tbody = TBODY()
    rank = 1
    for i in users:

        if i[5]:
            span = SPAN(_class="orange tooltipped",
                        data={"position": "right",
                              "delay": "50",
                              "tooltip": "Custom User"},
                        _style="cursor: pointer; " + \
                                "float:right; " + \
                                "height:10px; " + \
                                "width:10px; " + \
                                "border-radius: 50%;")
        else:
            span = SPAN()

        tr = TR()
        tr.append(TD(str(rank) + "."))
        tr.append(TD(DIV(span, DIV(i[0]))))
        tr.append(TD(A(i[1],
                       _href=URL("user", "profile", args=[i[1]]),
                       _target="_blank")))
        tr.append(TD(A(i[2],
                       _href=URL("default",
                                 "leaderboard",
                                 vars={"q": i[2],
                                       "global": global_leaderboard}))))
        tr.append(TD(i[3]))
        if i[6] > 0:
            tr.append(TD(B("+%s" % str(i[6])),
                         _class="green-text text-darken-2"))
        elif i[6] < 0:
            tr.append(TD(B(i[6]), _class="red-text text-darken-2"))
        else:
            tr.append(TD(i[6], _class="blue-text text-darken-2"))

        diff = "{:1.5f}".format(i[4])

        if float(diff) == 0.0:
            tr.append(TD("+" + diff, " ",
                         I(_class="fa fa-minus")))
        elif i[4] > 0:
            tr.append(TD("+" + str(diff), " ",
                         I(_class="fa fa-chevron-circle-up",
                           _style="color: #0f0;")))
        elif i[4] < 0:
            tr.append(TD(diff, " ",
                         I(_class="fa fa-chevron-circle-down",
                           _style="color: #f00;")))

        tbody.append(tr)
        rank += 1

    table.append(tbody)
    switch = DIV(LABEL(H6("Friends' Submissions",
                          INPUT(_type="checkbox", _id="submission-switch"),
                          SPAN(_class="lever pink accent-3"),
                          "Global Submissions")),
                 _class="switch")
    div = TAG[""](switch, table)
    return dict(div=div,
                heading=heading,
                global_leaderboard=global_leaderboard)
Esempio n. 30
0
def index():
    """
        The main problem page
    """
    from json import dumps

    if request.vars.has_key("pname") is False or \
       request.vars.has_key("plink") is False:

        # Disables direct entering of a URL
        session.flash = "Please click on a Problem Link"
        redirect(URL("default", "index"))

    submission_type = "friends"
    if request.vars.has_key("submission_type"):
        if request.vars["submission_type"] == "global":
            submission_type = "global"
        elif request.vars["submission_type"] == "my":
            submission_type = "my"

    if auth.is_logged_in() is False and submission_type != "global":
        response.flash = "Login to view your/friends' submissions"
        submission_type = "global"

    stable = db.submission
    ptable = db.problem

    problem_name = request.vars["pname"]
    problem_link = request.vars["plink"]

    query = (stable.problem_link == problem_link)
    cusfriends = []

    if submission_type in ("my", "friends"):
        if auth.is_logged_in():
            if submission_type == "friends":
                friends, cusfriends = utilities.get_friends(session.user_id)
                # The Original IDs of duplicate custom_friends
                custom_friends = []
                for cus_id in cusfriends:
                    if cus_id[1] is None:
                        custom_friends.append(cus_id[0])
                    else:
                        custom_friends.append(cus_id[1])

                query &= (stable.user_id.belongs(friends)) | \
                         (stable.custom_user_id.belongs(custom_friends))
            else:
                query &= (stable.user_id == session.user_id)
        else:
            response.flash = "Login to view your/friends' submissions"

    submissions = db(query).select(orderby=~stable.time_stamp)

    try:
        query = (ptable.link == problem_link)
        all_tags = db(query).select(ptable.tags).first()
        if all_tags:
            all_tags = eval(all_tags["tags"])
        else:
            all_tags = ["-"]
    except AttributeError:
        all_tags = ["-"]

    site = utilities.urltosite(problem_link).capitalize()
    problem_details = DIV(_class="row")
    details_table = TABLE(_style="font-size: 140%;", _class="col s7")
    tbody = TBODY()
    tbody.append(TR(TD(),
                    TD(STRONG("Problem Name:")),
                    TD(problem_name,
                       _id="problem_name")))
    tbody.append(TR(TD(),
                    TD(STRONG("Site:")),
                    TD(site)))

    links = DIV(DIV(A(I(_class="fa fa-link"), " Problem",
                      _href=problem_link,
                      _style="color: black;",
                      _target="blank"),
                    _class="chip lime accent-3"))

    row = db(ptable.link == problem_link).select().first()
    if row and row.editorial_link:
        links.append(" ")
        links.append(DIV(A(I(_class="fa fa-book"), " Editorial",
                           _href=row.editorial_link,
                           _style="color: white;",
                           _target="_blank"),
                         _class="chip deep-purple darken-1"))
    tbody.append(TR(TD(),
                    TD(STRONG("Links:")),
                    links))

    suggest_tags_class = "disabled btn chip tooltipped"
    suggest_tags_data = {"position": "right",
                         "delay": "50",
                         "tooltip": "Login to suggest tags"}
    suggest_tags_id = "disabled-suggest-tags"
    if auth.is_logged_in():
        suggest_tags_class = "green chip waves-light waves-effect tooltipped"
        suggest_tags_data["target"] = "suggest-tags-modal"
        suggest_tags_data["tooltip"] = "Suggest tags"
        suggest_tags_id = "suggest-trigger"

    tbody.append(TR(TD(),
                    TD(STRONG("Tags:")),
                    TD(DIV(SPAN(A(I(_class="fa fa-tag"), " Show Tags",
                                 _id="show-tags",
                                 _class="chip orange darken-1",
                                 data={"tags": dumps(all_tags)}),
                                _id="tags-span"),
                           " ",
                           A(I(_class="fa fa-plus"),
                             _style="color: white",
                             _class=suggest_tags_class,
                             _id=suggest_tags_id,
                             data=suggest_tags_data)))))

    details_table.append(tbody)
    problem_details.append(details_table)
    problem_details.append(DIV(_class="col s5", _id="chart_div"))

    table = utilities.render_table(submissions, cusfriends)

    return dict(site=site,
                problem_details=problem_details,
                problem_name=problem_name,
                problem_link=problem_link,
                submission_type=submission_type,
                table=table)
Esempio n. 31
0
def get_friend_list():
    """
        Gets the friend list of a specific user and compares with the friend
        list of the logged in user.
    """

    profile_user_id = int(request.vars["user_id"])
    user_friends, _ = utilities.get_friends(session.user_id)
    profile_friends, _ = utilities.get_friends(profile_user_id)

    if not profile_friends:
        return dict(table='No friends added yet.')

    atable = db.auth_user
    cftable = db.custom_friend

    table = TABLE(_class="bordered centered")
    tbody = TBODY()

    user_records = utilities.get_user_records(profile_friends, "id", "id",
                                              False)

    for friend_id in profile_friends:
        row = user_records[friend_id]

        friend_name = " ".join(
            [row.first_name.capitalize(),
             row.last_name.capitalize()])
        profile_url = URL("user",
                          "profile",
                          args=[row.stopstalk_handle],
                          extension=False)

        if friend_id == session.user_id:
            tr = TR(TD(
                A(friend_name + " (You)", _href=profile_url,
                  _target="_blank")),
                    TD(),
                    _style="height: 87px")
            tbody.append(tr)
            continue

        friend_button_data = {
            "user-id": str(friend_id),
            "position": "left",
            "delay": "100"
        }

        if friend_id in user_friends:
            button_color, fa_icon = ("black", "fa-user-times")
            friend_button_data["tooltip"] = T("Unriend")
            friend_button_data["type"] = "unfriend"
        else:
            button_color, fa_icon = ("green", "fa-user-plus")
            friend_button_data["tooltip"] = T("Add Friend")
            friend_button_data["type"] = "add-friend"

        tr = TR(
            TD(A(friend_name, _href=profile_url, _target="_blank")),
            TD(
                BUTTON(
                    I(_class="fa fa-3x " + fa_icon),
                    _class="tooltipped btn-floating btn-large waves-effect " +
                    "waves-light friends-button " + button_color,
                    data=friend_button_data)))
        tbody.append(tr)

    table.append(tbody)

    return dict(table=table)
Esempio n. 32
0
def trending():
    """
        Show trending problems globally and among friends
        @ToDo: Needs lot of comments explaining the code
    """

    stable = db.submission
    atable = db.auth_user
    cftable = db.custom_friend

    today = datetime.datetime.today()
    # Consider submissions only after PAST_DAYS(customisable)
    # for trending problems
    start_date = str(today - datetime.timedelta(days=current.PAST_DAYS))
    end_date = str(today)

    count = stable.id.count()

    if session.user_id:
        friends, cusfriends = utilities.get_friends(session.user_id)

        # The Original IDs of duplicate custom_friends
        custom_friends = []
        for cus_id in cusfriends:
            if cus_id[1] == None:
                custom_friends.append(cus_id[0])
            else:
                custom_friends.append(cus_id[1])

        first_query = (stable.user_id.belongs(friends))
        first_query |= (stable.custom_user_id.belongs(custom_friends))
        query = (stable.time_stamp >= start_date)
        query &= (stable.time_stamp <= end_date)
        query = first_query & query

        friend_trending = db(query).select(stable.problem_name,
                                           stable.problem_link,
                                           count,
                                           orderby=~count,
                                           groupby=stable.problem_link)

        friends = [str(x) for x in friends]
        custom_friends = [str(x) for x in custom_friends]
        friend_trending = _get_total_users(friend_trending.as_list(), friends,
                                           custom_friends, start_date,
                                           end_date)
        # Sort the rows according to the
        # number of users who solved the
        # problem in last PAST_DAYS
        rows = sorted(friend_trending, key=lambda k: k["unique"], reverse=True)
        rows = rows[:current.PROBLEMS_PER_PAGE]
        problems = []
        for problem in rows:
            submission = problem["submission"]
            problems.append([
                submission["problem_name"], submission["problem_link"],
                problem["_extra"]["COUNT(submission.id)"], problem["unique"]
            ])

        friend_table = _render_trending("Trending among friends", problems,
                                        "Friends")

    tptable = db.trending_problems
    rows = db(tptable).select()
    global_trending = []
    for problem in rows:
        global_trending.append([
            problem["problem_name"], problem["problem_link"],
            problem["submission_count"], problem["user_count"]
        ])

    global_table = _render_trending("Trending Globally", global_trending,
                                    "Users")

    if session.user_id:
        div = DIV(_class="row col s12")
        div.append(DIV(friend_table, _class="col s6"))
        div.append(DIV(global_table, _class="col s6"))
    else:
        div = DIV(global_table, _class="center")

    return dict(div=div)