def update_post(request, project_url_path, post_url_path): form = BlogPostForm(request.POST) post = get_object_or_404(BlogPost, url_path=post_url_path) # validate the form if form.is_valid(): # update the post html = markdown(request.POST['markdown'], safe_mode=True) post.title = request.POST['title'] post.markdown = request.POST['markdown'] post.summary = html post.content = html post.save() return HttpResponseRedirect( reverse(show_post, args=( post.blog.project.url_path, post.url_path, ))) else: return render_to_response('blogs/edit.html', { 'project': post.blog.project, 'form': form }, context_instance=RequestContext(request))
def textToENML(content, raise_ex=False): """ Create an ENML format of note. """ if not isinstance(content, str): content = "" try: content = unicode(content, "utf-8") # add 2 space before new line in paragraph for cteating br tags content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1 \n\3', content) contentHTML = markdown.markdown(content).encode("utf-8") # remove all new-lines characters in html contentHTML = re.sub(r'\n', r'', contentHTML) return wrapENML(contentHTML) except: if raise_ex: raise Exception( "Error while parsing text to html. Content must be an UTF-8 encode." ) logging.error( "Error while parsing text to html. Content must be an UTF-8 encode." ) out.failureMessage( "Error while parsing text to html. Content must be an UTF-8 encode." ) return tools.exit()
def create_post(request, project_id): form = BlogPostForm(request.POST) project = get_object_or_404(Project, id = int(project_id)) if request.user not in project.authors.all(): return HttpResponseRedirect(reverse(projects.show, args = (project.url_path,))) # validate the form if form.is_valid(): date = datetime.datetime.utcnow() html = markdown(request.POST['markdown'], safe_mode = "escape") post = BlogPost(title = request.POST['title'], markdown = request.POST['markdown'], summary = html, content = html, from_feed = False, author = request.user, project = project, date = date) post.blog = project.blog post.save() project.blog.most_recent_date = date project.blog.save() project.calculate_score() return HttpResponseRedirect(reverse(show_post, args = (post.blog.project.url_path, post.url_path,))) else: return render_to_response('blogs/edit.html', { 'project': project, 'form': form }, context_instance = RequestContext(request))
def submit_challenge_source(self): """updates a challenge's source """ if not users.is_current_user_admin(): self.error(status_code.StatusCode.unauth) return new_source = self.request.get('source') if not new_source: self.error(status_code.StatusCode.forbidden) return # retrieve the challenge challenge_key = self.request.get('challenge_key') if not challenge_key: self.error(status_code.StatusCode.forbidden) return challenge = None try: challenge = Challenge.get(challenge_key) finally: if not challenge: self.error(status_code.StatusCode.forbidden) return challenge.markdown = new_source challenge.content = markdown.markdown( challenge.markdown, ['codehilite', 'mathjax']) challenge.put()
def api_get_blogs(): format = ctx.request.get('format', '') blogs, page = _get_blogs_by_page() if format == 'html': for blog in blogs: blog.content = markdown.markdown(blog.content) return dict(blogs=blogs, page=page)
def create_share(request): form = ShareForm(request.POST) if form.is_valid(): if request.POST['title'] and not request.POST[ 'summary'] and not request.POST['external_link']: # Don't let people create posts with only a title return HttpResponseRedirect(reverse(feed.main)) tld = urlparse(request.POST['external_link'] ).netloc if request.POST['external_link'] else None date = datetime.datetime.utcnow() text = markdown(request.POST['summary'], safe_mode=True) share = Share(title=request.POST['title'], external_link=request.POST['external_link'], summary=text, from_feed=False, author=request.user, date=date) if tld: share.link_display = tld share.save() return HttpResponseRedirect(reverse(feed.main)) else: return render_to_response('shares/shareform.html', {'form': form}, context_instance=RequestContext(request))
def persistAttempt(self, challenge_key, solution): """persists new attempt.""" self.jeeqser, challenge = ndb.get_multi( [self.jeeqser.key, challenge_key]) jeeqser_challenge = get_jeeqser_challenge( self.jeeqser.key, challenge_key) previous_index = 0 if jeeqser_challenge: previous_index = jeeqser_challenge.active_attempt.get().index jeeqser_challenge.active_attempt.get().active = False jeeqser_challenge.active_attempt.get().put() if jeeqser_challenge.status == AttemptStatus.SUCCESS: challenge.num_jeeqsers_solved -= 1 else: course_code = None if challenge_key.get().exercise: course_code = challenge_key.get().exercise.get().course.get().code jeeqser_challenge = Jeeqser_Challenge( parent=self.jeeqser.key, jeeqser=self.jeeqser.key, challenge=challenge_key, course_code=course_code ) challenge.num_jeeqsers_submitted += 1 challenge.submissions_without_review += 1 challenge.put() attempt = Attempt( parent=self.jeeqser.key, author=self.jeeqser.key, challenge=challenge_key, content=markdown.markdown(solution, ['codehilite', 'mathjax']), markdown=solution, active=True, index=previous_index + 1) attempt.put() if jeeqser_challenge.status == AttemptStatus.SUCCESS: self.jeeqser.correct_submissions_count -= 1 jeeqser_challenge.active_attempt = attempt.key jeeqser_challenge.incorrect_count = jeeqser_challenge.flag_count = 0 jeeqser_challenge.correct_count = 0 jeeqser_challenge.status = None jeeqser_challenge.put() self.jeeqser.submissions_num += 1 self.jeeqser.put() Activity( type='submission', done_by=self.jeeqser.key, done_by_displayname=self.jeeqser.displayname, done_by_gravatar=self.jeeqser.profile_url, challenge=challenge.key, challenge_name=challenge.name).put() return self.jeeqser, attempt, jeeqser_challenge
def markup_text(text): content = text if '</textarea>' in content: content.replace('</textarea>', '') if '</div>' in content: content.replace('</div>', '') content.replace('\n', '<br>') return Markup(markdown.markdown(content))
def blog(blog_id): blog = Blogs.get(blog_id) if blog is None: raise HttpError.notfound() blog.html_content = markdown.markdown(blog.content) comments = Comments.find_by( 'where blog_id=? order by created_at desc limit 1000', blog_id) return dict(blog=blog, comments=comments, user=ctx.request.user)
def post(self, id): content = self.get_argument("content", None) content = markdown.markdown(content) if not content: self.redirect("/topic/"+id+"/") return self.reply_topic(id, content) self.redirect("/topic/"+id+"/?page=last#last")
def post(self): title = self.get_argument("title", None) content = self.get_argument("content", None) if not (title and content): self.render("topic/create.html", msg=None) title = markdown.escape(title) content = markdown.markdown(content) tid = self.insert_topic(0, title, content) self.redirect("/topic/%s/" % (tid,))
def post(self): title = self.get_argument("title", None) intro = self.get_argument("intro", None) if not (title and intro): self.render("room/create.html", msg=None) title = markdown.escape(title) intro = markdown.markdown(intro) private = self.get_argument("private")=="true" rid = self.create_room(title, intro, private, self.current_user) self.redirect("/room/%s/" % (rid,))
def smarttext(content): """ Replaces the String "{{ MEDIA_URL }}" and "{{ WEB_URL }}" in text and renders content with markdown: {{ content|smarttext }} """ content = content.replace("{{ MEDIA_URL }}", settings.MEDIA_URL) content = content.replace("{{ WEB_URL }}", settings.WEB_URL) content = markdown(content) return mark_safe(content)
def smarttext(content): ''' Replaces the String "{{ MEDIA_URL }}" and "{{ WEB_URL }}" in text and renders content with markdown: {{ content|smarttext }} ''' content = content.replace('{{ MEDIA_URL }}', settings.MEDIA_URL) content = content.replace('{{ WEB_URL }}', settings.WEB_URL) content = markdown(content) return mark_safe(content)
def persist_new_submission(): jeeqser_challenge = ns.jeeqser_challenge previous_index = 0 if len(jeeqser_challenge) == 1: jeeqser_challenge = jeeqser_challenge[0] jeeqser_challenge.active_attempt.active = False jeeqser_challenge.active_attempt.put() previous_index = jeeqser_challenge.active_attempt.index if jeeqser_challenge.status == 'correct' : if challenge.num_jeeqsers_solved > 0: challenge.num_jeeqsers_solved -=1 else: logging.error("Challenge %s can not have negative solvers! " % challenge.key()) else: #create one jeeqser_challenge = Jeeqser_Challenge( parent=self.jeeqser, jeeqser = self.jeeqser, challenge = challenge ) challenge.num_jeeqsers_submitted += 1 if challenge.last_solver and challenge.last_solver.key() == self.jeeqser.key(): challenge.last_solver = None challenge.put() attempt = Attempt( author=self.jeeqser.key(), challenge=challenge, content=markdown.markdown(solution, ['codehilite', 'mathjax']), markdown=solution, active=True, index=previous_index + 1) attempt.put() jeeqser_challenge.active_attempt = attempt jeeqser_challenge.correct_count = jeeqser_challenge.incorrect_count = jeeqser_challenge.flag_count = 0 jeeqser_challenge.status = None jeeqser_challenge.put() jeeqser = Jeeqser.get(ns.jeeqser.key()) jeeqser.submissions_num += 1 jeeqser.put() # Pass variables up ns.jeeqser = jeeqser ns.attempt = attempt ns.jeeqser_challenge = jeeqser_challenge
def post(self, id): title = self.get_argument("title", None) content = self.get_argument("content", None) if not (title and content): self.render("topic/edit.html", msg=None) topic = self.get_topic(int(id)) if not (self.current_user and (self.current_user["id"] == topic.uid or self.current_user.get("role")!=CONST.admin)): return title = markdown.escape(title) content = markdown.markdown(content) self.update_topic(id, title, content) self.redirect("/topic/%s/" % (id,))
def get(self, slug=None): # look up the article article = models.Article.get_by_slug(slug) if not article: return self.render_template('errors/default_error.html') # fetch the content from ourselves http = httplib2.Http(cache=None, timeout=None, proxy_info=None) uri = "http://%s/assets/blog/%s" % (self.request.host, article.filename) response, content = http.request(uri, method="GET", body=None, headers=None) # if the article wasn't found if response['status'] == '404': return self.render_template('errors/default_error.html') # fetch the user's info who wrote the article owner_info = models.User.get_by_id(article.owner.id()) if not owner_info.name: article_owner = owner_info.username else: article_owner = owner_info.name # build gravatar URL gravatar_hash = md5.new(owner_info.email.lower().strip()).hexdigest() article_gravatar_url = "https://www.gravatar.com/avatar/%s?s=100" % gravatar_hash # date format date_format = "%A, %d %b %Y" article_created = article.created.strftime(date_format) # create markdown and sanitize article_html = markdown.markdown(unicode(content, 'utf-8')) article_html = bleach.clean(article_html, config.bleach_tags, config.bleach_attributes) # load page content into params params = { 'article_created': article_created, 'article_html': article_html, 'article_slug': article.slug, 'article_title': article.title, 'article_type': article.article_type, 'article_owner': article_owner, 'article_gravatar_url': article_gravatar_url, 'article_host': self.request.host, } return self.render_template('blog/detail.html', **params)
def run_testcases(program, challenge, attempt, robot): """ Runs the challenge's test cases over the given program (persisted as attempt) and persists the results as a feedback # TODO remove robot parameter """ output = {"result": ""} success = True vote = "correct" try: program_module = compile_and_run(program, output) except: success = False vote = "incorrect" if success: test_num = 0 for test in challenge.testcases: test_num = test_num + 1 result = eval(test.statement, program_module.__dict__) if not str(result) == test.expected: success = False output["result"] += ( " Failed with the statement: \n ***** \n" + test.statement + " \n Expected result: \n" + test.expected + " \n Actual result: \n" + str(result) + " \n" ) if test_num == 0: output["result"] += "No test cases to run!" elif success: output["result"] += "Success! All tests ran successfully!" else: vote = "incorrect" feedback = Feedback( parent=attempt, attempt=attempt, author=robot, attempt_author=attempt.author, markdown=output["result"], content=markdown.markdown(output["result"], ["codehilite", "mathjax"]), vote=vote, ) return feedback
def persist_new_draft(): try: draft = Draft.query( ancestor=self.jeeqser.key)\ .filter(Draft.author == self.jeeqser.key)\ .filter(Draft.challenge == challenge_key).fetch(1)[0] except IndexError: draft = Draft( parent=self.jeeqser.key, author=self.jeeqser.key, challenge=challenge_key, ) draft.markdown = solution draft.content = markdown.markdown( solution, ['codehilite', 'mathjax']) draft.put()
def get(self, slug=None): # look up the article article = models.Article.get_by_slug(slug) if not article: return self.render_template("errors/default_error.html") # fetch the content from ourselves http = httplib2.Http(cache=None, timeout=None, proxy_info=None) uri = "http://%s/assets/blog/%s" % (self.request.host, article.filename) response, content = http.request(uri, method="GET", body=None, headers=None) # if the article wasn't found if response["status"] == "404": return self.render_template("errors/default_error.html") # fetch the user's info who wrote the article owner_info = models.User.get_by_id(article.owner.id()) if not owner_info.name: article_owner = owner_info.username else: article_owner = owner_info.name # build gravatar URL gravatar_hash = md5.new(owner_info.email.lower().strip()).hexdigest() article_gravatar_url = "https://www.gravatar.com/avatar/%s?s=100" % gravatar_hash # date format date_format = "%A, %d %b %Y" article_created = article.created.strftime(date_format) # create markdown and sanitize article_html = markdown.markdown(unicode(content, "utf-8")) article_html = bleach.clean(article_html, config.bleach_tags, config.bleach_attributes) # load page content into params params = { "article_created": article_created, "article_html": article_html, "article_slug": article.slug, "article_title": article.title, "article_type": article.article_type, "article_owner": article_owner, "article_gravatar_url": article_gravatar_url, "article_host": self.request.host, } return self.render_template("blog/detail.html", **params)
def get(self, page): # search for the wiki page in the DB version = self.request.get('v') wiki_page = self.get_wiki_page(page, version) # if doesn't exist, redirect to the edit page if wiki_page is None: self.redirect('/wiki/_edit/' + page) # if it already exist, render the wiki page else: content = markdown.markdown(wiki_page.content) params = {'page':page, 'version':version, 'title':wiki_page.title, 'content':content} self.render('/wiki/wiki-page.html', **params)
def submit_review(self): submission_key = self.getValueInQuery('submission_key') review = self.getValueInQuery('review') submission = ndb.Key(urlsafe=submission_key).get() self.verifyReviewerQualified(submission) jeeqser_challenge = get_jeeqser_challenge( submission.author, submission.challenge, create=True, submission_key=submission.key) feedback = Feedback( parent=submission.key, attempt=submission.key, author=self.jeeqser.key, attempt_author=submission.author, markdown=self.request.get('response'), content=markdown.markdown( self.request.get('response'), ['codehilite', 'mathjax']), review=review) sub_author = submission.author.get() if sub_author.review_email_subscribed: self.send_review_email(sub_author, submission.challenge) # check flagging limit if feedback.review == Review.FLAG: flags_left = spam_manager.SpamManager.check_and_update_flag_limit( self.jeeqser) response = {'flags_left_today': flags_left} out_json = json.dumps(response) self.response.write(out_json) if flags_left == -1: return self.persist_review( feedback, submission.key, jeeqser_challenge.key, self.jeeqser.key)
def update_post(request, project_url_path, post_url_path): form = BlogPostForm(request.POST) post = get_object_or_404(BlogPost, url_path=post_url_path) # validate the form if form.is_valid(): # update the post html = markdown(request.POST["markdown"], safe_mode=True) post.title = request.POST["title"] post.markdown = request.POST["markdown"] post.summary = html post.content = html post.save() return HttpResponseRedirect(reverse(show_post, args=(post.blog.project.url_path, post.url_path))) else: return render_to_response( "blogs/edit.html", {"project": post.blog.project, "form": form}, context_instance=RequestContext(request) )
def textToENML(content, raise_ex=False): """ Create an ENML format of note. """ if not isinstance(content, str): content = "" try: content = unicode(content,"utf-8") # add 2 space before new line in paragraph for cteating br tags content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1 \n\3', content) contentHTML = markdown.markdown(content).encode("utf-8") # remove all new-lines characters in html contentHTML = re.sub(r'\n', r'', contentHTML) return wrapENML(contentHTML) except: if raise_ex: raise Exception("Error while parsing text to html. Content must be an UTF-8 encode.") logging.error("Error while parsing text to html. Content must be an UTF-8 encode.") out.failureMessage("Error while parsing text to html. Content must be an UTF-8 encode.") return tools.exit()
def handle_automatic_review( attempt_key, challenge_key, jeeqser_challenge_key, program): """Handles submission review for automatic review challenges.""" attempt, challenge, jeeqser_challenge = ndb.get_multi( [ndb.Key(urlsafe=attempt_key), ndb.Key(urlsafe=challenge_key), ndb.Key(urlsafe=jeeqser_challenge_key)]) vote, output = program_tester.run_testcases( program, challenge) robot = core.get_jeeqs_robot() feedback = Feedback( parent=attempt.key, attempt=attempt.key, author=robot.key, attempt_author=attempt.author, markdown=output, content=markdown.markdown(output, ['codehilite', 'mathjax']), vote=vote) persist_testcase_results( attempt.key, jeeqser_challenge.key, feedback, robot.key)
def get(self, token = None): # lookup up bid bid = InstanceBid.get_by_token(token) if not bid: self.add_message("Instance reservation token %s has expired." % token, 'error') return self.redirect_to('projects') # grab the project from the bid project = Project.get_by_id(bid.wisp.get().project.id()) # grab the instance instance = Instance.get_by_token(token) if not instance: self.add_message("All available instance reservations are in use. Please try again in a few minutes.", 'error') return self.redirect_to('projects') # grab and render the README.md file content = urlfetch.fetch('http://10.0.1.80:8079/wisps/6048757061779456/README.md').content readme_html = bleach.clean( markdown.markdown( unicode(content, 'utf-8') ), config.bleach_tags, config.bleach_attributes ) # setup channel to do page refresh channel_token = token refresh_channel = channel.create_channel(channel_token) params = { 'instance': instance, 'bid': bid, 'project': project, 'readme_html': readme_html, 'refresh_channel': refresh_channel, 'channel_token': channel_token } return self.render_template('project/bid.html', **params)
def update_post(request, project_url_path, post_url_path): form = BlogPostForm(request.POST) post = get_object_or_404(BlogPost, url_path = post_url_path) # validate the form if form.is_valid(): # update the post html = markdown(request.POST['markdown'], safe_mode = "escape") post.title = request.POST['title'] post.markdown = request.POST['markdown'] post.summary = html post.content = html post.save() return HttpResponseRedirect(reverse(show_post, args = (post.blog.project.url_path, post.url_path,))) else: return render_to_response('blogs/edit.html', { 'project': post.blog.project, 'form': form }, context_instance = RequestContext(request))
def create_post(request, project_id): form = BlogPostForm(request.POST) project = get_object_or_404(Project, id=int(project_id)) if request.user not in project.authors.all(): return HttpResponseRedirect( reverse(projects.show, args=(project.url_path, ))) # validate the form if form.is_valid(): date = datetime.datetime.utcnow() html = markdown(request.POST['markdown'], safe_mode=True) post = BlogPost(title=request.POST['title'], markdown=request.POST['markdown'], summary=html, content=html, from_feed=False, author=request.user, project=project, date=date) post.blog = project.blog post.save() project.blog.most_recent_date = date project.blog.save() project.calculate_score() return HttpResponseRedirect( reverse(show_post, args=( post.blog.project.url_path, post.url_path, ))) else: return render_to_response('blogs/edit.html', { 'project': project, 'form': form }, context_instance=RequestContext(request))
def create_share(request): form = ShareForm(request.POST) if form.is_valid(): if request.POST['title'] and not request.POST['summary'] and not request.POST['external_link']: # Don't let people create posts with only a title return HttpResponseRedirect(reverse(feed.main)) tld = urlparse(request.POST['external_link']).netloc if request.POST['external_link'] else None date = datetime.datetime.utcnow() text = markdown(request.POST['summary'], safe_mode = True) share = Share(title = request.POST['title'], external_link = request.POST['external_link'], summary = text, from_feed = False, author = request.user, date = date) if tld: share.link_display = tld share.save() return HttpResponseRedirect(reverse(feed.main)) else: return render_to_response('shares/shareform.html', { 'form': form }, context_instance = RequestContext(request))
def get(self): # load articles in from db and then stuff them in an array date_format = "%A, %d %b %Y" articles = models.Article.get_all() # http connection start http = httplib2.Http(cache=None, timeout=None, proxy_info=None) blogposts = [] # loop through articles for article in articles: # fetch the content from ourselves uri = "http://%s/assets/blog/%s" % (self.request.host, article.filename) response, content = http.request(uri, method="GET", body=None, headers=None) if content: # create markdown and sanitize article_html = bleach.clean( markdown.markdown(unicode(content, 'utf-8')), config.bleach_tags, config.bleach_attributes) article_title = bleach.clean(article.title) # created when and by whom article_created = article.created.strftime(date_format) owner_info = models.User.get_by_id(article.owner.id()) # load name try: if not owner_info.name: article_owner = owner_info.username else: article_owner = owner_info.name except: article_owner = "StackMonkey" # build gravatar URL try: gravatar_hash = md5.new( owner_info.email.lower().strip()).hexdigest() except: gravatar_hash = md5.new( config.app_email.strip()).hexdigest() article_gravatar_url = "https://www.gravatar.com/avatar/%s?s=100" % gravatar_hash # build entry entry = { 'article_created': article_created, 'article_id': article.key.id(), 'article_title': article_title, 'article_type': article.article_type, 'article_html': article_html, 'article_slug': article.slug, 'article_owner': article_owner, 'article_gravatar_url': article_gravatar_url, 'article_host': self.request.host, } # append article if it's a post and not a draft if article.article_type == 'post' and not article.draft: blogposts.append(entry) # pack and stuff into template params = {'blogposts': blogposts} return self.render_template('blog/blog.html', **params)
def markdown(self): return markdown.markdown(self.content)
def get(self): # show this user's previous attempts attempts = None feedbacks = None submission = None # get the challenge ch_key = self.request.get('ch') if not ch_key: self.error(StatusCode.forbidden) return challenge = None try: challenge = Challenge.get(ch_key) finally: if not challenge: self.error(StatusCode.forbidden) return if not challenge.content and challenge.markdown: challenge.content = markdown.markdown(challenge.markdown, ['codehilite', 'mathjax']) challenge.put() attempt_key = self.request.get('att') if attempt_key: submission = Attempt.get(attempt_key) template_file = os.path.join(os.path.dirname(__file__), 'templates', 'solve_a_challenge.html') if (self.jeeqser): attempts_query = db.GqlQuery(" SELECT * " " FROM Attempt " " WHERE author = :1 " " AND challenge = :2 " " ORDER BY date DESC", self.jeeqser.key(), challenge) attempts = attempts_query.fetch(20) if not submission: # fetch user's active submission submission_query = db.GqlQuery(" SELECT * " " FROM Attempt " " WHERE author = :1 " " AND challenge = :2 " " AND active = True " " ORDER BY date DESC ", self.jeeqser.key(), challenge) submissions = submission_query.fetch(1) if (submissions): submission = submissions[0] else: submission = None if submission: feedbacks = Feedback.all()\ .filter('attempt = ', submission)\ .filter('flagged = ', False)\ .order('flag_count')\ .order('-date')\ .fetch(10) if feedbacks: prettify_injeeqs(feedbacks) vars = add_common_vars({ 'server_software': os.environ['SERVER_SOFTWARE'], 'python_version': sys.version, 'jeeqser': self.jeeqser, 'login_url': users.create_login_url(self.request.url), 'logout_url': users.create_logout_url(self.request.url), 'attempts': attempts, 'challenge' : challenge, 'challenge_key' : challenge.key(), 'template_code': challenge.template_code, 'submission' : submission, 'feedbacks' : feedbacks }) rendered = webapp.template.render(template_file, vars, debug=_DEBUG) self.response.out.write(rendered)
def submit_vote(self): class Namespace(object): pass ns = Namespace() submission_key = self.request.get('submission_key') vote = self.request.get('vote') submission = None try: submission = Attempt.get(submission_key) finally: if not submission: self.error(StatusCode.forbidden) return #Ensure non-admin user is qualified to vote if not users.is_current_user_admin(): voter_challenge = get_JC(self.jeeqser, submission.challenge) qualifield = voter_challenge and voter_challenge[0].status == 'correct' if not qualified: self.error(StatusCode.forbidden) return if not self.jeeqser.key() in submission.users_voted: jeeqser_challenge = get_JC(submission.author,submission.challenge) if len(jeeqser_challenge) == 0: # should never happen but let's guard against it! logging.error("Jeeqser_Challenge not available! for jeeqser : " + submission.author.user.email() + " and challenge : " + submission.challenge.name) jeeqser_challenge = Jeeqser_Challenge( parent = submission.author, jeeqser = submission.author, challenge = submission.challenge, active_attempt = submission) jeeqser_challenge.put() else: jeeqser_challenge = jeeqser_challenge[0] feedback = Feedback( parent=submission, attempt=submission, author=self.jeeqser, attempt_author=submission.author, markdown=self.request.get('response'), content=markdown.markdown(self.request.get('response'), ['codehilite', 'mathjax']), vote=vote) ns.submission = submission ns.jeeqser_challenge = jeeqser_challenge ns.jeeqser = self.jeeqser def persist_vote(): # get all the objects that will be updated submission = Attempt.get(ns.submission.key()) jeeqser_challenge = Jeeqser_Challenge.get(ns.jeeqser_challenge.key()) jeeqser = Jeeqser.get(ns.jeeqser.key()) submission.author = Jeeqser.get(ns.submission.author.key()) # check flagging limit if vote == 'flag': flags_left = spam_manager.check_and_update_flag_limit(jeeqser) response = {'flags_left_today':flags_left} out_json = json.dumps(response) self.response.out.write(out_json) if flags_left == -1: raise Rollback() submission.users_voted.append(jeeqser.key()) submission.vote_count += 1 submission.vote_sum += float(RPCHandler.get_vote_numeric_value(vote)) submission.vote_average = float(submission.vote_sum / submission.vote_count) RPCHandler.update_submission(submission, jeeqser_challenge, vote, jeeqser) # update stats jeeqser.reviews_out_num += 1 submission.author.reviews_in_num +=1 jeeqser_challenge.put() submission.put() submission.challenge.put() jeeqser.put() submission.author.put() feedback.put() xg_on = db.create_transaction_options(xg=True) db.run_in_transaction_options(xg_on, persist_vote) Activity( type='voting', done_by = self.jeeqser, done_by_displayname=self.jeeqser.displayname, done_by_gravatar = self.jeeqser.gravatar_url, challenge=submission.challenge, challenge_name=submission.challenge.name, submission=submission, submission_author=submission.author, submission_author_displayname=submission.author.displayname, submission_author_gravatar = submission.author.gravatar_url, feedback=feedback ).put() else: # should not happen! self.error(StatusCode.forbidden) return
def parse_markdown(self, contents): return markdown.markdown(contents, extras=["metadata"])
def get_wiki(self): wiki = list(model.WikiPage.get_all()) for i in range(len(wiki)): wiki[i].content = markdown.markdown(wiki[i].content) return wiki
def parse_commits(self): import Commit events = [] # if this is a cloned repository if not self.from_feed: repo_dir = os.path.join(settings.REPO_ROOT, self.project.url_path) # add the commits backend = get_backend(self.vcs if self.vcs != 'svn' else 'git') repository = backend.Repository(repo_dir) # inspect the last five days of commits for commit in repository.get_recent_commits(self.most_recent_date): date = commit.time try: date = (date - date.utcoffset()).replace(tzinfo=None) except: pass # process the diff of this commit try: diff, added, removed, changed = format_diff(commit.diff) except KeyError: diff, added, removed, changed = "", "Unknown", "Unknown", "Unknown" # extract the title of the commit try: commit_title = re.findall(r"^.*\.\s", commit.message)[0].strip() except IndexError: commit_title = commit.message.split("\n")[0] # format the commit message commit.message = re.sub( r"<p>\s+</p>", "", markdown(commit.message.replace(commit_title, "").decode('utf-8'), safe_mode=True)) append_unsanitized = ( "<div class=\"light-bar\">{0} file{1} changed," + " {2} line{3} added, {4} line{5} removed</div>").format( changed, 's' if changed != 1 else '', added, 's' if added != 1 else '', removed, 's' if removed != 1 else '') events.append( self.add_event(Commit.Commit, title=commit_title, summary=commit.message, date=date, author_name=commit.author, from_feed=False, append_unsanitized=append_unsanitized, extra_args={ "diff": diff, "repository_id": self.id, })) # this is a feed-driven repository else: for commit in feedparser.parse(self.repo_rss).entries: date = dateutil.parser.parse(commit.date) try: date = (date - date.utcoffset()).replace(tzinfo=None) except: pass events.append( self.add_event(Commit.Commit, title=commit.title, summary=commit.description, date=date, author_name=commit.author_detail['name'], from_feed=True, extra_args={"repository_id": self.id})) # find the new most recent date dates = [event.date for event in events if event is not None] dates.append(self.most_recent_date) self.most_recent_date = max(dates) self.save()
def get(self): # load articles in from db and then stuff them in an array date_format = "%A, %d %b %Y" articles = models.Article.get_all() # http connection start http = httplib2.Http(cache=None, timeout=None, proxy_info=None) blogposts = [] # loop through articles for article in articles: # fetch the content from ourselves uri = "http://%s/assets/blog/%s" % (self.request.host, article.filename) response, content = http.request(uri, method="GET", body=None, headers=None) if content: # create markdown and sanitize article_html = bleach.clean( markdown.markdown(unicode(content, "utf-8")), config.bleach_tags, config.bleach_attributes ) article_title = bleach.clean(article.title) # created when and by whom article_created = article.created.strftime(date_format) owner_info = models.User.get_by_id(article.owner.id()) # load name try: if not owner_info.name: article_owner = owner_info.username else: article_owner = owner_info.name except: article_owner = "StackMonkey" # build gravatar URL try: gravatar_hash = md5.new(owner_info.email.lower().strip()).hexdigest() except: gravatar_hash = md5.new(config.app_email.strip()).hexdigest() article_gravatar_url = "https://www.gravatar.com/avatar/%s?s=100" % gravatar_hash # build entry entry = { "article_created": article_created, "article_id": article.key.id(), "article_title": article_title, "article_type": article.article_type, "article_html": article_html, "article_slug": article.slug, "article_owner": article_owner, "article_gravatar_url": article_gravatar_url, "article_host": self.request.host, } # append article if it's a post and not a draft if article.article_type == "post" and not article.draft: blogposts.append(entry) # pack and stuff into template params = {"blogposts": blogposts} return self.render_template("blog/blog.html", **params)
def parse_commits(self): import Commit events = [] # if this is a cloned repository if not self.from_feed: repo_dir = os.path.join(settings.REPO_ROOT, self.project.url_path) # add the commits backend = get_backend(self.vcs if self.vcs != 'svn' else 'git') repository = backend.Repository(repo_dir) # inspect the last five days of commits for commit in repository.get_recent_commits(self.most_recent_date): date = commit.time try: date = (date - date.utcoffset()).replace(tzinfo=None) except: pass # process the diff of this commit try: diff, added, removed, changed = format_diff(commit.diff) except KeyError: diff, added, removed, changed = "", "Unknown", "Unknown", "Unknown" # extract the title of the commit try: commit_title = re.findall(r"^.*\.\s", commit.message)[0].strip() except IndexError: commit_title = commit.message.split("\n")[0] # format the commit message commit.message = re.sub(r"<p>\s+</p>", "", markdown(commit.message.replace(commit_title, "").decode('utf-8'), safe_mode = True)) append_unsanitized = ("<div class=\"light-bar\">{0} file{1} changed," + " {2} line{3} added, {4} line{5} removed</div>").format( changed, 's' if changed != 1 else '', added, 's' if added != 1 else '', removed, 's' if removed != 1 else '' ) events.append(self.add_event(Commit.Commit, title = commit_title, summary = commit.message, date = date, author_name = commit.author, from_feed = False, append_unsanitized = append_unsanitized, extra_args = { "diff": diff, "repository_id": self.id, })) # this is a feed-driven repository else: for commit in feedparser.parse(self.repo_rss).entries: date = dateutil.parser.parse(commit.date) try: date = (date - date.utcoffset()).replace(tzinfo=None) except: pass events.append(self.add_event(Commit.Commit, title = commit.title, summary = commit.description, date = date, author_name = commit.author_detail['name'], from_feed = True, extra_args = { "repository_id": self.id } )) # find the new most recent date dates = [event.date for event in events if event is not None] dates.append(self.most_recent_date) self.most_recent_date = max(dates) self.save()
def get(self): # show this user's previous attempts attempts = None feedbacks = None submission = None feedbacks_cursor = None draft = None # get the challenge ch_key = self.request.get('ch') if not ch_key: self.error(StatusCode.forbidden) return challenge = None try: challenge = ndb.Key(urlsafe=ch_key).get() finally: if not challenge: self.error(StatusCode.forbidden) return if not challenge.content and challenge.markdown: challenge.content = markdown.markdown(challenge.markdown, ['codehilite', 'mathjax']) challenge.put() attempt = None attempt_key = self.request.get('att') if attempt_key: attempt = submission = ndb.Key(urlsafe=attempt_key).get() if (self.jeeqser): if not submission: # fetch user's active submission submissions = Attempt.query()\ .filter(Attempt.author == self.jeeqser.key)\ .filter(Attempt.challenge == challenge.key)\ .filter(Attempt.active == True)\ .order(-Attempt.date)\ .fetch(1) if submissions: submission = submissions[0] else: submission = None if submission: fph = paging_handler.FeedbacksPagingHandler(self.request) feedbacks, feedbacks_cursor, has_newer = \ fph.get_feedbacks_for_submission(self.jeeqser.key, submission.key) # Fetch saved draft try: if self.jeeqser: draft = Draft.query().filter( Draft.author == self.jeeqser.key, Draft.challenge == challenge.key).fetch(1)[0] except IndexError: draft = None vars = core.add_common_vars({ 'server_software': os.environ['SERVER_SOFTWARE'], 'python_version': sys.version, 'jeeqser': self.jeeqser, 'login_url': users.create_login_url(self.request.url), 'logout_url': users.create_logout_url(self.request.url), 'challenge': challenge, 'challenge_key': challenge.key, 'template_code': challenge.template_code, 'submission': submission, 'feedbacks': feedbacks, 'feedbacks_cursor': feedbacks_cursor, 'draft': draft, 'attempt': attempt, 'user_is_admin': users.is_current_user_admin(), }) template = core.jinja_environment.get_template( 'solve_a_challenge.html') rendered = template.render(vars) self.response.write(rendered)
def get(self): # show this user's previous attempts attempts = None feedbacks = None submission = None feedbacks_cursor = None draft = None # get the challenge ch_key = self.request.get("ch") if not ch_key: self.error(StatusCode.forbidden) return challenge = None try: challenge = ndb.Key(urlsafe=ch_key).get() finally: if not challenge: self.error(StatusCode.forbidden) return if not challenge.content and challenge.markdown: challenge.content = markdown.markdown(challenge.markdown, ["codehilite", "mathjax"]) challenge.put() attempt = None attempt_key = self.request.get("att") if attempt_key: attempt = submission = ndb.Key(urlsafe=attempt_key).get() if self.jeeqser: if not submission: # fetch user's active submission submissions = ( Attempt.query() .filter(Attempt.author == self.jeeqser.key) .filter(Attempt.challenge == challenge.key) .filter(Attempt.active == True) .order(-Attempt.date) .fetch(1) ) if submissions: submission = submissions[0] else: submission = None if submission: fph = paging_handler.FeedbacksPagingHandler(self.request) feedbacks, feedbacks_cursor, has_newer = fph.get_feedbacks_for_submission( self.jeeqser.key, submission.key ) # Fetch saved draft try: if self.jeeqser: draft = ( Draft.query().filter(Draft.author == self.jeeqser.key, Draft.challenge == challenge.key).fetch(1)[0] ) except IndexError: draft = None vars = core.add_common_vars( { "server_software": os.environ["SERVER_SOFTWARE"], "python_version": sys.version, "jeeqser": self.jeeqser, "login_url": users.create_login_url(self.request.url), "logout_url": users.create_logout_url(self.request.url), "challenge": challenge, "challenge_key": challenge.key, "template_code": challenge.template_code, "submission": submission, "feedbacks": feedbacks, "feedbacks_cursor": feedbacks_cursor, "draft": draft, "attempt": attempt, "user_is_admin": users.is_current_user_admin(), } ) template = core.jinja_environment.get_template("solve_a_challenge.html") rendered = template.render(vars) self.response.write(rendered)