コード例 #1
0
def todo():

    ptable = db.problem
    tltable = db.todo_list

    res = db(tltable.user_id == session.user_id).select(tltable.problem_link)
    table = TABLE(_class="bordered centered")
    table.append(
        THEAD(
            TR(TH(T("Problem")), TH(T("Site")), TH(T("Total submissions")),
               TH(T("Users solved")), TH(T("Remove")))))

    plinks = [x.problem_link for x in res]
    tbody = TBODY()

    rows = db(ptable.link.belongs(plinks)).select(ptable.name, ptable.link,
                                                  ptable.total_submissions,
                                                  ptable.user_ids,
                                                  ptable.custom_user_ids)
    link_class = ""

    def _get_ids(ids):
        ids = ids.split(",")
        return [] if ids[0] == "" else ids

    for row in rows:
        if row.link in current.solved_problems:
            link_class = "solved-problem"
        elif row.link in current.unsolved_problems:
            link_class = "unsolved-problem"
        else:
            link_class = "unattempted-problem"

        uids, cuids = _get_ids(row.user_ids), _get_ids(row.custom_user_ids)

        link_title = (" ".join(link_class.split("-"))).capitalize()
        tbody.append(TR(TD(utilities.problem_widget(row.name,
                                                    row.link,
                                                    link_class,
                                                    link_title,
                                                    disable_todo=True)),
                        TD(IMG(_src=URL("static",
                                        "images/" + \
                                        utilities.urltosite(row.link) + \
                                        "_small.png"),
                               _style="height: 30px; weight: 30px;")),
                        TD(row.total_submissions),
                        TD(len(uids) + len(cuids)),
                        TD(I(_class="red-text text-accent-4 fa fa-times remove-from-todo",
                             data={"link": row.link}))))
    table.append(tbody)
    div = DIV(DIV(H2(T("ToDo List")),
                  HR(),
                  BR(),
                  table,
                  BR(),
                  _class="col offset-s2 s8 z-depth-2"),
              _class="row")

    return dict(div=div)
コード例 #2
0
def get_problem_details(problem_record):
    link = problem_record.link

    update_things = []
    for genre in genre_classes:
        this_class = genre_classes[genre]
        if this_class.conditional(problem_record):
            update_things.append(this_class.column_value())

    site = utilities.urltosite(link)
    Site = getattr(sites, site.lower()).Profile

    try:
        details = Site.get_problem_details(problem_link=link,
                                           update_things=update_things)
    except AttributeError:
        # get_problem_details not implemented for this site
        print "get_problem_details not implemented for", link
        return

    for column_value in update_things:
        this_class = genre_classes[column_value]
        this_class.update_database(problem_record, details[column_value])

    return
コード例 #3
0
def editorials():
    if len(request.args) < 1:
        redirect(URL("default", "index"))
    record = db.problem(int(request.args[0]))
    if record is None:
        redirect(URL("default", "index"))

    uetable = db.user_editorials
    atable = db.auth_user
    query = (uetable.problem_id == record.id)
    user_editorials = db(query).select(orderby=~uetable.added_on)
    accepted_count = len(
        filter(
            lambda x:
            (x.verification == "accepted" or
             (auth.is_logged_in() and
              (x.user_id == session.user_id or session.user_id == 1))),
            user_editorials))
    if accepted_count == 0:
        if auth.is_logged_in():
            table_contents = T(
                "No editorials found! Please contribute to the community by writing an editorial if you've solved the problem."
            )
        else:
            table_contents = T(
                "No editorials found! Please login if you want to write an editorial."
            )

        return dict(name=record.name,
                    link=record.link,
                    editorial_link=record.editorial_link,
                    table=DIV(BR(), H6(table_contents)),
                    problem_id=record.id,
                    site=utilities.urltosite(record.link))

    user_id = session.user_id if auth.is_logged_in() else None
    table = utilities.render_user_editorials_table(
        user_editorials, user_id, user_id,
        "read-editorial-problem-editorials-page")

    return dict(name=record.name,
                link=record.link,
                editorial_link=record.editorial_link,
                table=table,
                problem_id=record.id,
                site=utilities.urltosite(record.link))
コード例 #4
0
def get_tag(link, name, today):

    global total_inserted
    global total_updated
    global not_updated

    ptable = db.problem
    site = utilities.urltosite(link)

    try:
        Site = getattr(sites, site.lower())
        P = Site.Profile
        if P.is_website_down():
            all_tags = ["-"]
        else:
            tags_func = P.get_tags
            all_tags = tags_func(link)
            if all_tags == []:
                all_tags = ["-"]
    except AttributeError:
        all_tags = ["-"]

    # If record already exists only update
    # name and tags not problem_added_on
    row = db(ptable.link == link).select().first()

    if row:
        prev_tags = row.tags
        if prev_tags != str(all_tags) and prev_tags == "['-']":
            row.update_record(tags=str(all_tags),
                              name=name,
                              tags_added_on=today,
                              editorial_added_on=today)
            print "Updated", link, prev_tags, "->", all_tags
            total_updated += 1
        else:
            not_updated += 1
            print "No-change", link
    else:
        total_inserted += 1
        print "Inserted ", link, all_tags
        # Insert tags in problem table
        # Note: Tags are stored in a stringified list
        #       so that they can be used directly by eval
        row = [link, name, str(all_tags), today]
        ptable.insert(link=link,
                      tags=str(all_tags),
                      name=name,
                      tags_added_on=today,
                      editorial_added_on=today)
コード例 #5
0
def get_editorial(problem_id, today):

    global total_inserted
    global total_updated
    global not_updated

    ptable = db.problem
    row = ptable(problem_id)
    link = row.link
    site = utilities.urltosite(link)

    try:
        Site = getattr(sites, site.lower())
        P = Site.Profile
        if P.is_website_down():
            editorial_link = None
        else:
            editorial_func = P.get_editorial_link
            editorial_link = editorial_func(link)
    except AttributeError:
        editorial_link = None

    if row:
        if editorial_link:
            row.update_record(editorial_link=editorial_link,
                              editorial_added_on=today)
            print("Updated", link, "->", editorial_link)
            total_updated += 1
        else:
            not_updated += 1
            print("No-change", link)
    else:
        print("****************Should not be here****************")
        total_inserted += 1
        print("Inserted", link, editorial_link)
        # Intentional raising error to fix the issue
        1 / 0
        # Insert editorial_link in problem table
        ptable.insert(link=link,
                      editorial_link=editorial_link,
                      editorial_added_on=today,
                      tags_added_on=today)
コード例 #6
0
ファイル: user.py プロジェクト: nobi1007/stopstalk-deployment
def get_solved_counts():
    """
        Get the number of solved and attempted problems
    """

    if request.extension != "json" or \
       request.vars.user_id is None or \
       request.vars.custom is None:
        raise HTTP(400, "Bad request")
        return

    user_id = int(request.vars.user_id)
    custom = (request.vars.custom == "True")
    stopstalk_handle = utilities.get_stopstalk_handle(user_id, custom)
    redis_cache_key = "get_solved_counts_" + stopstalk_handle

    # Check if data is present in REDIS
    data = current.REDIS_CLIENT.get(redis_cache_key)
    if data:
        return json.loads(data)

    stable = db.submission
    query = (stable["custom_user_id" if custom else "user_id"] == user_id)

    total_problems = db(query).count(distinct=stable.problem_link)
    query &= (stable.status == "AC")
    solved_problems = db(query).select(stable.problem_link, distinct=True)
    site_counts = {}
    for site in current.SITES:
        site_counts[site.lower()] = 0
    for problem in solved_problems:
        site_counts[utilities.urltosite(problem.problem_link)] += 1

    data = dict(total_problems=total_problems,
                solved_problems=len(solved_problems),
                site_counts=site_counts)

    current.REDIS_CLIENT.set(redis_cache_key,
                             json.dumps(data, separators=(",", ":")),
                             ex=24 * 60 * 60)
    return data
コード例 #7
0
ファイル: user.py プロジェクト: GSri30/stopstalk-deployment
 def _get_categorized_json(problem_ids):
     result = dict([(category, []) for category in ordered_categories])
     for pid in problem_ids:
         this_category = None
         if pid not in problem_tags:
             this_category = "Miscellaneous"
         else:
             ptags = problem_tags[pid]
             category_found = False
             for category in ordered_categories:
                 if len(categories[category].intersection(ptags)) > 0:
                     this_category = category
                     category_found = True
                     break
             if not category_found:
                 this_category = "Miscellaneous"
         pdetails = problem_details[pid]
         plink, pname, _, _ = pdetails
         psite = utilities.urltosite(plink)
         if (pname, psite) not in displayed_problems:
             displayed_problems.add((pname, psite))
             result[this_category].append(problem_details[pid])
     return result
コード例 #8
0
def get_editorial(link, today):

    global total_inserted
    global total_updated
    global not_updated

    ptable = db.problem
    site = utilities.urltosite(link)

    try:
        Site = globals()[site]
        editorial_func = Site.Profile().get_editorial_link
        editorial_link = editorial_func(link)
    except AttributeError:
        editorial_link = None

    row = db(ptable.link == link).select().first()
    if row:
        if editorial_link:
            row.update_record(editorial_link=editorial_link,
                              editorial_added_on=today)
            print "Updated", link, "->", editorial_link
            total_updated += 1
        else:
            not_updated += 1
            print "No-change", link
    else:
        print "****************Should not be here****************"
        total_inserted += 1
        print "Inserted", link, editorial_link
        # Intentional raising error to fix the issue
        1 / 0
        # Insert editorial_link in problem table
        ptable.insert(link=link,
                      editorial_link=editorial_link,
                      editorial_added_on=today,
                      tags_added_on=today)
コード例 #9
0
def get_editorial(link, today):

    global total_inserted
    global total_updated
    global not_updated

    ptable = db.problem
    site = utilities.urltosite(link)

    try:
        Site = globals()[site]
        editorial_func = Site.Profile().get_editorial_link
        editorial_link = editorial_func(link)
    except AttributeError:
        editorial_link = None

    row = db(ptable.link == link).select().first()
    if row:
        if editorial_link:
            row.update_record(editorial_link=editorial_link,
                              editorial_added_on=today)
            print "Updated", link, "->", editorial_link
            total_updated += 1
        else:
            not_updated += 1
            print "No-change", link
    else:
        print "****************Should not be here****************"
        total_inserted += 1
        print "Inserted", link, editorial_link
        # Intentional raising error to fix the issue
        1 / 0
        # Insert editorial_link in problem table
        ptable.insert(link=link,
                      editorial_link=editorial_link,
                      editorial_added_on=today,
                      tags_added_on=today)
コード例 #10
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)
コード例 #11
0
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)
コード例 #12
0
def editorials():
    if len(request.args) < 1:
        redirect(URL("default", "index"))
    record = db.problem(int(request.args[0]))
    if record is None:
        redirect(URL("default", "index"))

    uetable = db.user_editorials
    atable = db.auth_user
    query = (uetable.problem_id == record.id)
    if auth.is_logged_in():
        # Show only accepted editorials not made by the logged-in user and
        # all the editorials submitted by the logged-in user
        query &= (((uetable.verification == "accepted") & \
                   (uetable.user_id != session.user_id)) | \
                  (uetable.user_id == session.user_id))
    else:
        query &= (uetable.verification == "accepted")
    user_editorials = db(query).select(orderby=~uetable.added_on)
    table = TABLE(_class="centered")
    thead = THEAD(
        TR(TH(T("Problem")), TH(T("Editorial By")), TH(T("Added on")),
           TH(T("Votes")), TH(T("Actions"))))
    color_mapping = {"accepted": "green", "rejected": "red", "pending": "blue"}

    tbody = TBODY()
    for editorial in user_editorials:
        user = atable(editorial.user_id)
        number_of_votes = len(
            editorial.votes.split(",")) if editorial.votes else 0
        tr = TR(
            TD(
                A(record.name,
                  _href=URL("problems",
                            "index",
                            vars={
                                "pname": record.name,
                                "plink": record.link
                            },
                            extension=False))))
        if auth.is_logged_in() and user.id == session.user_id:
            tr.append(TD(A(user.first_name + " " + user.last_name,
                         _href=URL("user",
                                   "profile",
                                   args=user.stopstalk_handle)),
                         " ",
                         DIV(editorial.verification.capitalize(),
                             _class="verification-badge " + \
                                    color_mapping[editorial.verification])))
        else:
            tr.append(
                TD(
                    A(user.first_name + " " + user.last_name,
                      _href=URL("user", "profile",
                                args=user.stopstalk_handle))))

        tr.append(TD(editorial.added_on))
        vote_class = ""
        if auth.is_logged_in() and str(session.user_id) in set(
                editorial.votes.split(",")):
            vote_class = "red-text"
        tr.append(
            TD(
                DIV(SPAN(I(_class="fa fa-heart " + vote_class),
                         _class="love-editorial",
                         data={"id": editorial.id}),
                    " ",
                    DIV(number_of_votes,
                        _class="love-count",
                        _style="margin-left: 5px;"),
                    _style="display: inline-flex;")))

        actions_td = TD(
            A(I(_class="fa fa-eye fa-2x"),
              _href=URL("problems", "read_editorial", args=editorial.id),
              _class="btn btn-primary tooltipped",
              _style="background-color: #13AA5F;",
              data={
                  "position": "bottom",
                  "delay": 40,
                  "tooltip": T("Read Editorial")
              }))
        if auth.is_logged_in() and user.id == session.user_id:
            actions_td.append(
                BUTTON(I(_class="fa fa-trash fa-2x"),
                       _style="margin-left: 2%;",
                       _class="red tooltipped delete-editorial",
                       data={
                           "position": "bottom",
                           "delay": 40,
                           "tooltip": T("Delete Editorial"),
                           "id": editorial.id
                       }))
        tr.append(actions_td)
        tbody.append(tr)

    table.append(thead)
    table.append(tbody)

    return dict(name=record.name,
                link=record.link,
                editorial_link=record.editorial_link,
                table=table,
                problem_id=record.id,
                site=utilities.urltosite(record.link))
コード例 #13
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)
コード例 #14
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)
コード例 #15
0
def tag():
    """
        Tag search page
    """

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

    # If URL does not have vars containing q
    # then remain at the search page and return
    # an empty table
    if request.vars.has_key("q") is False:
        return dict(table=table)

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

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

    # Enables multiple space seperated tag search
    q = q.split(" ")
    ptable = db.problem

    query = None
    for tag in q:
        if query is not None:
            # 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:
            query = ptable.tags.contains(tag)

    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

    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)

    all_problems = db(query).select(ptable.name,
                                    ptable.link,
                                    ptable.tags,
                                    distinct=True,
                                    limitby=((curr_page - 1) * PER_PAGE,
                                             curr_page * PER_PAGE))

    tbody = TBODY()
    for problem in all_problems:

        tr = TR()

        if problem.link in current.solved_problems:
            link_class = "solved-problem"
        elif problem.link in current.unsolved_problems:
            link_class = "unsolved-problem"
        else:
            link_class = "unattempted-problem"

        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(TD(A(problem.name,
                       _href=URL("problems",
                                 "index",
                                 vars={"pname": problem.name,
                                       "plink": problem.link}),
                       _class=link_class,
                       _title=link_title,
                       _target="_blank")))
        tr.append(TD(A(I(_class="fa fa-link"),
                       _href=problem.link,
                       _target="_blank")))
        tr.append(TD(IMG(_src=URL("static",
                                  "images/" + \
                                  utilities.urltosite(problem.link) + \
                                  "_small.png"),
                         _style="height: 30px; width: 30px;")))
        all_tags = eval(problem.tags)
        td = TD()
        for tag in all_tags:
            td.append(DIV(A(tag,
                            _href=URL("problems",
                                      "tag",
                                      vars={"q": tag, "page": 1}),
                            _style="color: white;",
                            _target="_blank"),
                          _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)
    return dict(table=table)
コード例 #16
0
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("Tags"))))
    table.append(thead)

    # If URL does not have vars containing q
    # then remain at the search page and return
    # an empty table
    if request.vars.has_key("q") is False:
        return dict(table=table)

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

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

    # Enables multiple space seperated tag search
    q = q.split(" ")
    ptable = db.problem

    query = None
    for tag in q:
        if query is not None:
            # 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:
            query = ptable.tags.contains(tag)

    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

    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)

    all_problems = db(query).select(ptable.name,
                                    ptable.link,
                                    ptable.tags,
                                    distinct=True,
                                    limitby=((curr_page - 1) * PER_PAGE,
                                             curr_page * PER_PAGE))

    tbody = TBODY()
    for problem in all_problems:

        tr = TR()
        link_class = ""

        if problem.link in current.solved_problems:
            link_class = "solved-problem"
        elif problem.link in current.unsolved_problems:
            link_class = "unsolved-problem"
        else:
            link_class = "unattempted-problem"

        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,
                 _target="_blank")))
        tr.append(TD(IMG(_src=URL("static",
                                  "images/" + \
                                  utilities.urltosite(problem.link) + \
                                  "_small.png"),
                         _style="height: 30px; width: 30px;")))
        all_tags = eval(problem.tags)
        td = TD()
        for tag in all_tags:
            td.append(
                DIV(A(tag,
                      _href=URL("problems", "tag", vars={
                          "q": tag,
                          "page": 1
                      }),
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)
    return dict(table=table)
コード例 #17
0
def get_request(url,
                headers={},
                timeout=current.TIMEOUT,
                params={},
                is_daily_retrieval=False):
    """
        Make a HTTP GET request to a url

        @param url (String): URL to make get request to
        @param headers (Dict): Headers to be passed along
                               with the request headers
        @param timeout (Number): Number of seconds after which client will close
                                 the request
        @param params (Dict): Dictionary of get request parms
        @param is_daily_retrieval (Boolean): Consider the function call to get_request
                                      for health report or not

        @return: Response object or one of REQUEST_FAILURES
    """

    if current.environment == "test":
        timeout = 20

    site = utilities.urltosite(url).lower()
    request_metric_handler = MetricHandler("request_stats", "success_failure",
                                           site, is_daily_retrieval)
    request_time_metric_handler = MetricHandler("request_times", "average",
                                                site, is_daily_retrieval)

    headers.update({"User-Agent": user_agent})

    i = 0
    while i < current.MAX_TRIES_ALLOWED:
        try:
            start_request_time = time.time()
            response = requests.get(url,
                                    headers=headers,
                                    params=params,
                                    proxies=current.PROXY,
                                    timeout=timeout,
                                    verify=False)
        except Exception as e:
            print e, url
            request_metric_handler.increment_count("failure", 1)
            log_time_things(request_time_metric_handler, start_request_time,
                            site)
            return SERVER_FAILURE

        if response.status_code == 200:
            log_time_things(request_time_metric_handler, start_request_time,
                            site)
            request_metric_handler.increment_count("success", 1)
            return response
        elif response.status_code == 404 or response.status_code == 400:
            log_time_things(request_time_metric_handler, start_request_time,
                            site)
            # User not found
            # 400 for CodeForces users
            return NOT_FOUND
        elif response.status_code == 429 or response.status_code == 401:
            log_time_things(request_time_metric_handler, start_request_time,
                            site)
            request_metric_handler.increment_count("failure", 1)
            # For CodeChef API rate limiting, don't retry
            # 401 is raised when a newer access token is generated
            print response.status_code
            if url.__contains__(
                    "codechef.com") and response.status_code == 401:
                current.REDIS_CLIENT.delete("codechef_access_token")
            return OTHER_FAILURE
        else:
            log_time_things(request_time_metric_handler, start_request_time,
                            site)
            request_metric_handler.increment_count("failure", 1)

        i += 1

    # Request unsuccessful even after MAX_TRIES_ALLOWED
    return OTHER_FAILURE
コード例 #18
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)
コード例 #19
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)
コード例 #20
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)
コード例 #21
0
def tag():
    """
        Tag search page
    """

    table = TABLE(_class="striped centered")
    thead = THEAD(
        TR(TH("Problem Name"), TH("Problem URL"), TH("Site"), TH("Tags")))
    table.append(thead)

    # If URL does not have vars containing q
    # then remain at the search page and return
    # an empty table
    if request.vars.has_key("q") is False:
        return dict(table=table)

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

    # Enables multiple space seperated tag search
    q = q.split(" ")
    stable = db.submission
    ptable = db.problem_tags
    atable = db.auth_user
    cftable = db.custom_friend
    ftable = db.friends

    query = None
    for tag in q:
        if query is not None:
            # 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:
            query = ptable.tags.contains(tag)

    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)

    all_problems = db(query).select(ptable.problem_name,
                                    ptable.problem_link,
                                    ptable.tags,
                                    distinct=True,
                                    limitby=((curr_page - 1) * PER_PAGE,
                                             curr_page * PER_PAGE))

    tbody = TBODY()
    for problem in all_problems:

        tr = TR()

        tr.append(
            TD(
                A(problem["problem_name"],
                  _href=URL("problems",
                            "index",
                            vars={
                                "pname": problem["problem_name"],
                                "plink": problem["problem_link"]
                            }),
                  _target="_blank")))
        tr.append(
            TD(
                A(I(_class="fa fa-link"),
                  _href=problem["problem_link"],
                  _target="_blank")))
        tr.append(TD(
            utilities.urltosite(problem["problem_link"]).capitalize()))
        all_tags = eval(problem["tags"])
        td = TD()
        for tag in all_tags:
            td.append(
                DIV(A(tag,
                      _href=URL("problems", "tag", vars={
                          "q": tag,
                          "page": 1
                      }),
                      _style="color: white;",
                      _target="_blank"),
                    _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)
    return dict(table=table)
コード例 #22
0
def get_submissions(user_id, handle, stopstalk_handle, submissions, site,
                    custom):
    """
        Get the submissions and populate the database
    """

    submission_count = len(submissions)

    if submission_count == 0:
        return submission_count

    for submission in submissions:
        try:
            pname = submission[2].encode("utf-8", "ignore")
        except UnicodeDecodeError:
            pname = str(submission[2])

        pname = pname.replace("\"", "").replace("'", "")
        plink = submission[1]
        pid = None
        if plink not in plink_to_id:
            is_codechef_url = utilities.urltosite(plink) == "codechef"
            if is_codechef_url:
                slug = sites.codechef.Profile.get_slug(plink)
                if slug in codechef_slugs:
                    pid = codechef_slugs[slug]
                else:
                    pid = None

            if pid is None:
                pid = ptable.insert(name=pname,
                                    link=plink,
                                    editorial_link=None,
                                    tags="['-']",
                                    editorial_added_on=todays_date_string,
                                    tags_added_on=todays_date_string,
                                    user_ids="",
                                    custom_user_ids="")
                plink_to_id[plink] = pid

            if is_codechef_url and pid is not None:
                codechef_slugs[slug] = pid
        else:
            pid = plink_to_id[plink]

        utilities.add_language_to_cache(submission[5])

        submission_insert_dict = {
            "user_id": user_id if not custom else None,
            "custom_user_id": user_id if custom else None,
            "stopstalk_handle": stopstalk_handle,
            "site_handle": handle,
            "site": site,
            "time_stamp": submission[0],
            "problem_id": pid,
            "lang": submission[5],
            "status": submission[3],
            "points": submission[4],
            "view_link": submission[6]
        }
        stable.insert(**submission_insert_dict)
        process_solved_counts(pid, plink, pname, submission[3], user_id,
                              custom)

    return submission_count
コード例 #23
0
def tag():
    """
        Tag search page
    """

    table = TABLE(_class="striped centered")
    thead = THEAD(TR(TH("Problem Name"),
                     TH("Problem URL"),
                     TH("Site"),
                     TH("Tags")))
    table.append(thead)

    # If URL does not have vars containing q
    # then remain at the search page and return
    # an empty table
    if request.vars.has_key("q") is False:
        return dict(table=table)

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

    # Enables multiple space seperated tag search
    q = q.split(" ")
    stable = db.submission
    ptable = db.problem_tags
    atable = db.auth_user
    cftable = db.custom_friend
    ftable = db.friends

    query = None
    for tag in q:
        if query is not None:
            # 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:
            query = ptable.tags.contains(tag)

    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)

    all_problems = db(query).select(ptable.problem_name,
                                    ptable.problem_link,
                                    ptable.tags,
                                    distinct=True,
                                    limitby=((curr_page - 1) * PER_PAGE,
                                             curr_page * PER_PAGE))

    tbody = TBODY()
    for problem in all_problems:

        tr = TR()

        tr.append(TD(A(problem["problem_name"],
                       _href=URL("problems",
                                 "index",
                                 vars={"pname": problem["problem_name"],
                                       "plink": problem["problem_link"]}),
                       _target="_blank")))
        tr.append(TD(A(I(_class="fa fa-link"),
                       _href=problem["problem_link"],
                       _target="_blank")))
        tr.append(TD(utilities.urltosite(problem["problem_link"]).capitalize()))
        all_tags = eval(problem["tags"])
        td = TD()
        for tag in all_tags:
            td.append(DIV(A(tag,
                            _href=URL("problems",
                                      "tag",
                                      vars={"q": tag, "page": 1}),
                            _style="color: white;",
                            _target="_blank"),
                          _class="chip"))
            td.append(" ")
        tr.append(td)
        tbody.append(tr)

    table.append(tbody)
    return dict(table=table)