def _render_trending(caption, problems, flag):
    """
        Create trending table from the rows
    """

    table = TABLE(_class="bordered centered")
    thead = THEAD(TR(TH(T("Problem")), TH(T("Recent Submissions")), TH(flag)))
    table.append(thead)
    tbody = TBODY()

    for problem in problems:
        tr = TR()
        link_class = utilities.get_link_class(problem[0], session.user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(
            TD(
                utilities.problem_widget(problem[1]["name"], problem[0],
                                         link_class, link_title)))
        tr.append(TD(problem[1]["total_submissions"]))
        tr.append(TD(len(problem[1]["users"]) + \
                     len(problem[1]["custom_users"])))
        tbody.append(tr)

    table.append(tbody)
    table = DIV(H5(caption, _class="center"), HR(), table)

    return table
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)
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)
def tag():
    """
        Tag search page
    """

    table = TABLE(_class="bordered centered")
    thead = THEAD(
        TR(TH(T("Problem Name")), TH(T("Problem URL")), TH(T("Site")),
           TH(T("Accuracy")), TH(T("Users solved")), TH(T("Tags"))))
    table.append(thead)

    ttable = db.tag
    generalized_tags = db(ttable).select(ttable.value, orderby=ttable.value)
    generalized_tags = [x.value for x in generalized_tags]

    # If URL does not have vars containing q
    # then remain at the search page and return
    # an empty table
    q = request.vars.get("q", None)
    clubbed_tags = request.vars.get("generalized_tags", None)
    clubbed_tags = None if clubbed_tags == "" else clubbed_tags
    if q is None and not clubbed_tags:
        return dict(table=table, generalized_tags=generalized_tags)

    try:
        sites = request.vars.get("site", "")
        if sites == "":
            sites = []
        elif isinstance(sites, str):
            sites = [sites]
    except:
        sites = []

    orderby = request.vars.get("orderby", None)
    if orderby not in ("accuracy-asc", "accuracy-desc", "solved-count-asc",
                       "solved-count-desc"):
        orderby = None

    try:
        curr_page = int(request.vars["page"])
    except:
        curr_page = 1
    PER_PAGE = current.PER_PAGE

    ptable = db.problem
    query = True

    if q is not None and not clubbed_tags:
        # Enables multiple space seperated tag search
        q = q.split(" ")
        for tag in q:
            if tag == "":
                continue
            # Decision to make & or |
            # & => Search for problem containing all these tags
            # | => Search for problem containing one of the tags
            query &= ptable.tags.contains(tag)
    else:
        clubbed_tags = [clubbed_tags] if isinstance(clubbed_tags,
                                                    str) else clubbed_tags
        ttable = db.tag
        sttable = db.suggested_tags

        tag_ids = db(ttable.value.belongs(clubbed_tags)).select(ttable.id)
        tag_ids = [x.id for x in tag_ids]

        problem_ids = db(sttable.tag_id.belongs(tag_ids)).select(
            sttable.problem_id)
        problem_ids = [x.problem_id for x in problem_ids]

        query &= ptable.id.belongs(problem_ids)

    site_query = None
    for site in sites:
        if site_query is not None:
            site_query |= ptable.link.contains(current.SITES[site])
        else:
            site_query = ptable.link.contains(current.SITES[site])
    if site_query:
        query &= site_query

    accuracy_column = (ptable.solved_submissions * 1.0 /
                       ptable.total_submissions)
    kwargs = dict(distinct=True,
                  limitby=((curr_page - 1) * PER_PAGE, curr_page * PER_PAGE))
    if orderby and orderby.__contains__("accuracy"):
        query &= ~(ptable.link.contains("hackerrank.com"))
        kwargs[
            "orderby"] = ~accuracy_column if orderby == "accuracy-desc" else accuracy_column

    if orderby and orderby.__contains__("solved-count"):
        kwargs["reverse"] = True if orderby == "solved-count-desc" else False

    query &= (ptable.solved_submissions != None)
    query &= (ptable.total_submissions != None) & (ptable.total_submissions !=
                                                   0)
    query &= (ptable.user_ids != None)
    query &= (ptable.custom_user_ids != None)

    total_problems = db(query).count()
    total_pages = total_problems / PER_PAGE
    if total_problems % PER_PAGE != 0:
        total_pages = total_problems / PER_PAGE + 1

    if request.extension == "json":
        return dict(total_pages=total_pages)

    if orderby and orderby.__contains__("solved-count"):
        all_problems = db(query).select(cache=(cache.ram, 3600),
                                        cacheable=True).as_list()
        all_problems.sort(key=lambda x: x["user_count"] + \
                                        x["custom_user_count"],
                          reverse=kwargs["reverse"])
        all_problems = all_problems[kwargs["limitby"][0]:kwargs["limitby"][1]]
    else:
        # No need of caching here
        all_problems = db(query).select(**kwargs)

    tbody = TBODY()
    for problem in all_problems:
        tr = TR()
        link_class = utilities.get_link_class(problem["link"], session.user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(
            TD(
                utilities.problem_widget(problem["name"], problem["link"],
                                         link_class, link_title)))
        tr.append(
            TD(
                A(I(_class="fa fa-link"),
                  _href=problem["link"],
                  _class="tag-problem-link",
                  _target="_blank")))
        tr.append(TD(IMG(_src=get_static_url("images/" + \
                                             utilities.urltosite(problem["link"]) + \
                                             "_small.png"),
                         _style="height: 30px; width: 30px;")))
        tr.append(TD("%.2f" % (problem["solved_submissions"]  * 100.0 / \
                               problem["total_submissions"])))
        tr.append(TD(problem["user_count"] + problem["custom_user_count"]))

        td = TD()
        all_tags = eval(problem["tags"])
        for tag in all_tags:
            td.append(
                DIV(A(tag,
                      _href=URL("problems",
                                "tag",
                                vars={
                                    "q": tag.encode("utf8"),
                                    "page": 1
                                }),
                      _class="tags-chip",
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)

    return dict(table=table, generalized_tags=generalized_tags)
Beispiel #5
0
def search():
    """
        Search page for problems
    """

    table = TABLE(_class="bordered centered")
    thead = THEAD(
        TR(TH(T("Problem Name")), TH(T("Problem URL")), TH(T("Site")),
           TH(T("Accuracy")), TH(T("Users solved")), TH(T("Editorial")),
           TH(T("Tags"))))
    table.append(thead)

    ttable = db.tag
    uetable = db.user_editorials

    problem_name = request.vars.get("name", None)
    orderby = request.vars.get("orderby", None)
    clubbed_tags = request.vars.get("generalized_tags", None)
    q = request.vars.get("q", None)
    sites = request.vars.get("site", None)

    generalized_tags = db(ttable).select(ttable.value, orderby=ttable.value)
    generalized_tags = [x.value for x in generalized_tags]

    if any([problem_name, orderby, clubbed_tags, q, sites]) is False:
        if request.extension == "json":
            return dict(total_pages=0)
        else:
            if len(request.get_vars):
                # No filter is applied
                response.flash = "No filter is applied"
            return dict(table=DIV(), generalized_tags=generalized_tags)

    include_editorials = request.vars.get("include_editorials", "")

    clubbed_tags = None if clubbed_tags == "" else clubbed_tags

    try:
        if sites == None or sites == "":
            sites = []
        elif isinstance(sites, str):
            sites = [sites]
    except:
        sites = []

    if orderby not in ("accuracy-asc", "accuracy-desc", "solved-count-asc",
                       "solved-count-desc"):
        orderby = None

    try:
        curr_page = int(request.vars["page"])
    except:
        curr_page = 1
    PER_PAGE = current.PER_PAGE

    ptable = db.problem
    query = True

    rows = db(uetable.verification == "accepted").select(uetable.problem_id)
    problem_with_user_editorials = set([x["problem_id"] for x in rows])

    if q is not None and not clubbed_tags:
        # Enables multiple space seperated tag search
        q = q.split(" ")
        for tag in q:
            if tag == "":
                continue
            # Decision to make & or |
            # & => Search for problem containing all these tags
            # | => Search for problem containing one of the tags
            query &= ptable.tags.contains(tag)
    elif clubbed_tags:
        clubbed_tags = [clubbed_tags] if isinstance(clubbed_tags,
                                                    str) else clubbed_tags
        ttable = db.tag
        sttable = db.suggested_tags

        tag_ids = db(ttable.value.belongs(clubbed_tags)).select(ttable.id)
        tag_ids = [x.id for x in tag_ids]

        problem_ids = db(sttable.tag_id.belongs(tag_ids)).select(
            sttable.problem_id)
        problem_ids = [x.problem_id for x in problem_ids]

        query &= ptable.id.belongs(problem_ids)

    if problem_name:
        query &= ptable.name.contains(problem_name)

    if include_editorials:
        # Check if the site editorial link is present or the problem id exists
        # in user_editorials table with accepted status
        query &= (((ptable.editorial_link != None) & \
                   (ptable.editorial_link != "")) | \
                  (ptable.id.belongs(problem_with_user_editorials)))

    site_query = None
    for site in sites:
        if site_query is not None:
            site_query |= ptable.link.contains(current.SITES[site])
        else:
            site_query = ptable.link.contains(current.SITES[site])
    if site_query:
        query &= site_query

    accuracy_column = (ptable.solved_submissions * 1.0 /
                       ptable.total_submissions)
    kwargs = dict(distinct=True,
                  limitby=((curr_page - 1) * PER_PAGE, curr_page * PER_PAGE))
    if orderby and orderby.__contains__("accuracy"):
        query &= ~(ptable.link.contains("hackerrank.com"))
        kwargs[
            "orderby"] = ~accuracy_column if orderby == "accuracy-desc" else accuracy_column

    if orderby and orderby.__contains__("solved-count"):
        kwargs["reverse"] = True if orderby == "solved-count-desc" else False

    query &= (ptable.solved_submissions != None)
    query &= (ptable.total_submissions != None) & (ptable.total_submissions !=
                                                   0)
    query &= (ptable.user_ids != None)
    query &= (ptable.custom_user_ids != None)

    if request.extension == "json":
        total_problems = db(query).count()

        total_pages = total_problems / PER_PAGE
        if total_problems % PER_PAGE != 0:
            total_pages = total_problems / PER_PAGE + 1

        return dict(total_pages=total_pages)

    if orderby and orderby.__contains__("solved-count"):
        all_problems = db(query).select().as_list()
        all_problems.sort(key=lambda x: x["user_count"] + \
                                        x["custom_user_count"],
                          reverse=kwargs["reverse"])
        all_problems = all_problems[kwargs["limitby"][0]:kwargs["limitby"][1]]
    else:
        # No need of caching here
        all_problems = db(query).select(**kwargs)

    tbody = TBODY()
    for problem in all_problems:
        tr = TR()

        link_class = utilities.get_link_class(problem["id"], session.user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(
            TD(
                utilities.problem_widget(problem["name"], problem["link"],
                                         link_class, link_title,
                                         problem["id"])))
        tr.append(
            TD(
                A(I(_class="fa fa-link"),
                  _href=problem["link"],
                  _class="tag-problem-link",
                  _target="_blank")))
        tr.append(TD(IMG(_src=get_static_url("images/" + \
                                             utilities.urltosite(problem["link"]) + \
                                             "_small.png"),
                         _style="height: 30px; width: 30px;")))
        tr.append(TD("%.2f" % (problem["solved_submissions"]  * 100.0 / \
                               problem["total_submissions"])))
        tr.append(TD(problem["user_count"] + problem["custom_user_count"]))

        if problem["id"] in problem_with_user_editorials or \
           problem["editorial_link"] not in ("", None):
            tr.append(
                TD(
                    A(I(_class="fa fa-book"),
                      _href=URL("problems", "editorials", args=problem["id"]),
                      _target="_blank",
                      _class="problem-search-editorial-link")))
        else:
            tr.append(TD())

        td = TD()
        all_tags = eval(problem["tags"])
        for tag in all_tags:
            td.append(
                DIV(A(tag,
                      _href=URL("problems",
                                "tag",
                                vars={
                                    "q": tag.encode("utf8"),
                                    "page": 1
                                }),
                      _class="tags-chip",
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)

    return dict(table=table, generalized_tags=generalized_tags)