Ejemplo n.º 1
0
    def post(self, post_subject):
        # If any user does not logged in redirect to homepage
        if not self.user:
            self.redirect('/')

        # Post page contains a form to post comments,
        # so a post request comes, lets put that comment into database
        post_to_comment = Post.find_by_subject(post_subject)
        # If post couldn't find redirect 404 page
        if not post_to_comment:
            self.error(404)
            return self.render('404.html')

        content = self.request.get('content').strip()

        if content:
            comment = Comment(
                content=content,
                post=post_to_comment,
                user=self.user)
            comment.put()
            self.redirect(post_to_comment.link_to('show'))
        else:
            errors = {'content': "can't be blank"}
            self.render(
                "/posts/post.html", post=post_to_comment,
                errors=errors)
Ejemplo n.º 2
0
 def comment_an_answer(self, answer, content):
     """Make a :class:`Comment` about an :class:`Answer`.""" 
     c = Comment(content=content)
     c.answer = answer 
     c.owner = self
     db.session.add(c)
     db.session.commit()
     return c
Ejemplo n.º 3
0
 def post(self):
     if not self.user:
         self.redirect('/blog')
     post_id = self.request.get('post_id')
     content = self.request.get('commment-content')
     created_by = self.user.key().id()
     create_time = datetime.datetime.now()
     Comment.create(created_by=created_by,create_time=create_time,
                    content=content,post_id=post_id)
     self.redirect('/blog/%s' % post_id);
Ejemplo n.º 4
0
	def __init__(self, fname):
		data = load_json(open(fname).read())

		topic = Comment(data[0]['data']['children'][0])

		comments = [Comment(c) for c in data[1]['data']['children'] if 'body' in c['data']]

		topic.children = comments

		self.comment_tree = topic
		self.comment_list = flatten_comment_tree(self.comment_tree)
Ejemplo n.º 5
0
 def get(self):
     if not self.user:
         self.redirect('/blog')
     comment_id = self.request.get('comment_id')
     comment = Comment.by_id(comment_id)
     if comment.created_by == self.user.key().id():
         post_id = comment.post_id
         Comment.delete(comment_id)
         self.redirect('/blog/%s' % post_id)
     else:
         self.redirect('/blog')
Ejemplo n.º 6
0
 def post(self):
     if not self.user:
         self.redirect('/blog')
     comment_id = self.request.get('comment_id')
     content = self.request.get('comment-content')
     comment = Comment.by_id(comment_id)
     if comment.created_by == self.user.key().id():
         Comment.update(comment_id,content)
         self.redirect('/blog/%s' % comment.post_id)
     else:
         self.redirect('/blog')
    def post(self, post_id):
        key = db.Key.from_path('Post', int(post_id), parent=blog_key())
        post = db.get(key)

        if not post:
            self.error(404)
            return

        c = ''
        if self.user:

            # On clicking like, post-like value increases.

            if self.request.get('like') and self.request.get('like') \
                == 'update':
                likes = \
                    db.GqlQuery('select * from Like where post_id = '
                                + post_id + ' and user_id = '
                                + str(self.user.key().id()))

                if self.user.key().id() == post.user_id:
                    self.redirect('/blog/' + post_id
                                  + '?error=You cannot like your '
                                  + 'post.!!')
                    return
                elif likes.count() == 0:
                    l = Like(parent=blog_key(),
                             user_id=self.user.key().id(),
                             post_id=int(post_id))
                    l.put()

            # On commenting, it creates new comment tuple

            if self.request.get('comment'):
                c = Comment(parent=blog_key(),
                            user_id=self.user.key().id(),
                            post_id=int(post_id),
                            comment=self.request.get('comment'))
                c.put()
        else:
            self.redirect('/login?error=You need to login before '
                          + 'performing edit, like or commenting.!!')
            return

        comments = db.GqlQuery('select * from Comment where post_id = '
                               + post_id + 'order by created desc')

        likes = db.GqlQuery('select * from Like where post_id='
                            + post_id)

        self.render('full-post.html', post=post, comments=comments,
                    noOfLikes=likes.count(), new=c)
Ejemplo n.º 8
0
class CommentController(MasterController):

    _comment = None
    
    def __init__(self, comments = None):
        self._comment = Comment()
        super(CommentController, self).__init__()

    def create(self, args):
        self._comment.attach(PostController)

        self._comment.user_id(args['user_id'])
        self._comment.post_id(args['post_id'])
        self._comment.comment(args['comment'])
        self._comment.save()
Ejemplo n.º 9
0
    def get(self):

        # Get all the comments, sorted by date
        comment_query = Comment.query(ancestor=DEFAULT_KEY).order(-Comment.date)
        comments = comment_query.fetch()

        self.render("main.html", comments=comments, invalid=PageHandler.invalid)
Ejemplo n.º 10
0
 def getter(self):
     from comment import Comment
     tmp = self.lib.comment_list.load_all()
     ans = Comment.by_ids(tmp)
     tmp_a = [each._id for each in ans]
     self.lib.comment_list.pull(*tuple(set(tmp) - set(tmp_a)))
     #pull ids not exist
     return ans
Ejemplo n.º 11
0
 def get_users(conf):
     with dbapi2.connect(conf) as connection:
         cursor = connection.cursor()
         query = "SELECT COMMENT_ID, USER_ID, COMMENT FROM COMMENTS ORDER BY COMMENT_ID DESC"
         cursor.execute(query)
         users = [(key, Comment(user_id, product_id, comment))
                  for key, user_id, product_id, comment in cursor]
     return users
Ejemplo n.º 12
0
    def update_leaderboard(self, score, scoreText="Score", ascending=False, 
        leaderboard_indicator = ".leaderboard.data.donot.remove\n",):
    
        pr_number = self.comment.pr.number 
        pr_sender = self.comment.pr.user.login 

        entry = "#" + str(pr_number) + " by " + str(pr_sender)
    
        leaderboard_content = None

        comment_pr1 = Comment(pr_number=1)
        values = comment_pr1.get_comment(leaderboard_indicator)

        if comment_pr1 is None or len(values) is 0:
                    leaderboard_content = scoreText + ", Entity"
        else:
            leaderboard_content = values[0]

        # Delete the csv comment
        comment_pr1.del_comment(leaderboard_indicator)

        df = pd.read_csv(StringIO(leaderboard_content))
        df.loc[len(df.index)] =  [score, entry] 
        df = df.sort_values(by=df.columns[0], ascending=ascending)
        new_leaderbord_content = df.to_csv(index=False)

        comment_pr1.add_comment(leaderboard_indicator + new_leaderbord_content)

        # Add new leaderboard results as a comment
        leaderboard_md = "## New Leaderboard\n" + df.to_markdown()
        self.comment.add_comment(leaderboard_md)
Ejemplo n.º 13
0
    def get_video_comments(self, video_id):
        """Method to return list of video comments
		Args: 
		    video_id (str): Youtube video unique id from url

		Returns: 
			list: comment objects including replies 
		"""
        try:

            parameters = {
                'textFormat': 'plainText',
                'part': "snippet,replies",
                'videoId': video_id,
                'maxResults': 100
            }
            comments = []
            service = self.get_endpoint()
            results = self.service.commentThreads().list(
                **parameters).execute()
            next_page_token = results.get('nextPageToken')
            while next_page_token:
                for item in results['items']:
                    comment_text = item['snippet']['topLevelComment'][
                        'snippet']['textDisplay']
                    comment_id = item['id']
                    comment = Comment(comment_text, comment_id, video_id)
                    comments.append(comment)

                    # get replies to each comment
                    if 'replies' in item.keys():
                        for reply_item in item['replies']['comments']:
                            reply_text = reply_item['snippet']['textDisplay']
                            reply_id = reply_item['id']
                            reply = Comment(reply_text, reply_id, video_id)
                            comments.append(reply)
                next_page_token = results.get('nextPageToken')
                parameters['pageToken'] = next_page_token
                results = self.service.commentThreads().list(
                    **parameters).execute()
            return comments
        except KeyError as key_error:
            raise
        except Exception as e:
            raise
Ejemplo n.º 14
0
    def post(self, post_id):
        key = db.Key.from_path('Post', int(post_id), parent=blog_key())
        post = db.get(key)

        if not post:
            self.error(404)
            return

        c = ""
        if (self.user):
            likes = db.GqlQuery("select * from Like where post_id = " +
                                post_id + " and user_id = " +
                                str(self.user.key().id()))

            if (self.request.get('like')
                    and self.request.get('like') == "update"):

                if (self.user.key().id() == post.user_id):
                    self.redirect("/blog/" + post_id +
                                  "?error=You cannot Like your" + "post.!!")
                    return
                elif likes.count() == 0:
                    l = Like(parent=blog_key(),
                             user_id=self.user.key().id(),
                             post_id=int(post_id))
                    l.put()

            if (self.request.get('comment')):
                c = Comment(parent=blog_key(),
                            user_id=self.user.key().id(),
                            post_id=int(post_id),
                            comment=self.request.get('comment'))
                c.put()
        else:
            self.redirect("/login?error= Login before " +
                          "edit or comment or like.!!")
            return

        comments = db.GqlQuery("select * from Comment where post_id = " +
                               post_id + "order by created desc")
        self.render("postDetails.html",
                    post=post,
                    noOfLikes=likes.count(),
                    comments=comments,
                    new=c)
Ejemplo n.º 15
0
	def post(self):
		self.response.headers['Content-Type'] = 'text/html'
		user = users.get_current_user()
		myuser_key = ndb.Key('User',  user.user_id())

		if self.request.get('button') == 'Submit':
			if len(self.request.get('comment').strip()) > 0:
				comment_text = self.request.get('comment')
				post_id = ndb.Key('Post',  int(self.request.get('postid')))
				commented_post = post_id.get()

				comment = Comment()
				comment.comment_text = comment_text
				comment.owner_user = myuser_key
				comment_key = comment.put()
				commented_post.comments.insert(0,comment_key)
				commented_post.put()
			self.redirect('/')
Ejemplo n.º 16
0
    def handle(cls, url):
        article = Article(url)
        article.download()
        article.parse()

        title = article.title
        body = article.text

        return Comment(title, body)
Ejemplo n.º 17
0
        def getter(self):
            from comment import Comment

            tmp = self.lib.comment_list.load_all()
            ans = Comment.by_ids(tmp)
            tmp_a = [each._id for each in ans]
            self.lib.comment_list.pull(*tuple(set(tmp) - set(tmp_a)))
            # pull ids not exist
            return ans
Ejemplo n.º 18
0
    def handleNonPremium(cls):
        body = ""
        amp_url = cls.soup.find("link", {"rel": "amphtml"})["href"]
        article_html = requests.get(amp_url).text
        article_soup = BeautifulSoup(article_html, "html.parser")
        for line in article_soup.select("div.article-body > p"):
            body += line.get_text() + "\n\n"

        return Comment(cls.title, body.strip())
Ejemplo n.º 19
0
def get_user_comments(user):
    comments = Comment.get_comments_by_user(repository, user)
    results = []
    for comment in comments:
        votes = UserCommentVoted.get_votes_of_a_comment(comment.id, repository)
        comment.votes = votes
        result = parse_comment(comment)
        results.append(result)
    return results
Ejemplo n.º 20
0
def comment_iter(cursor):
    while True:
        row = cursor.fetchone()
        if row is None:
            cursor.close()
            raise StopIteration

        d = row_to_dict(cursor, row)
        yield Comment(d)
Ejemplo n.º 21
0
    def retrieveCommentsHelper(self, praw_comment_forest, depth=0):
        for praw_comment in list(praw_comment_forest):
            if isinstance(praw_comment, praw.models.MoreComments):
                continue

            comment = Comment(praw_comment, depth)
            self.addComment(comment)

            self.retrieveCommentsHelper(praw_comment.replies, depth + 1)
Ejemplo n.º 22
0
    def handle(cls, url):
        html = requests.get(url).text
        soup = BeautifulSoup(html, "html.parser")
        article_info = soup.find("meta", {"name":"cXenseParse:mdc-targeturl"})["content"].split('/')
        category_id = article_info[1]
        article_id = article_info[2]

        CNALIFESTYLE_API_URL = (
            f"https://cnalifestyle.channelnewsasia.com/graphql?query=query"
            f"%20article(%24articleId%3A%20String!%2C%20%24categoryId%3A%"
            f"20String!)%20%7B%0A%20%20article(articleId%3A%20%24articleId%2C"
            f"%20categoryId%3A%20%24categoryId)%20%7B%0A%20%20%20%20id%0A"
            f"%20%20%20%20title%0A%20%20%20%20metaTitle%0A%20%20%20%20image%0A"
            f"%20%20%20%20imageWidth%0A%20%20%20%20imageHeight%0A"
            f"%20%20%20%20category%0A%20%20%20%20date%0A%20%20%20%20sharing%0A"
            f"%20%20%20%20exclusive%0A%20%20%20%20link%0A"
            f"%20%20%20%20hasSubjectTaxonomy%0A%20%20%20%20currentContext%20"
            f"%7B%0A%20%20%20%20%20%20title%0A%20%20%20%20%20%20link%0A"
            f"%20%20%20%20%20%20__typename%0A%20%20%20%20%7D%0A"
            f"%20%20%20%20author%20%7B%0A%20%20%20%20%20%20title%0A"
            f"%20%20%20%20%20%20__typename%0A%20%20%20%20%7D%0A"
            f"%20%20%20%20contexts%20%7B%0A%20%20%20%20%20%20title%0A"
            f"%20%20%20%20%20%20link%0A%20%20%20%20%20%20__typename%0A"
            f"%20%20%20%20%7D%0A%20%20%20%20defaultPhoto%20%7B%0A"
            f"%20%20%20%20%20%20link%0A%20%20%20%20%20%20__typename%0A"
            f"%20%20%20%20%7D%0A%20%20%20%20photos%20%7B%0A"
            f"%20%20%20%20%20%20teaserText%0A%20%20%20%20%20%20detailText%0A"
            f"%20%20%20%20%20%20photo%20%7B%0A%20%20%20%20%20%20%20%20link%0A"
            f"%20%20%20%20%20%20%20%20__typename%0A%20%20%20%20%20%20%7D%0A"
            f"%20%20%20%20%20%20__typename%0A%20%20%20%20%7D%0A"
            f"%20%20%20%20video%20%7B%0A%20%20%20%20%20%20id%0A"
            f"%20%20%20%20%20%20ooyalaId%0A%20%20%20%20%20%20duration%0A"
            f"%20%20%20%20%20%20playerId%0A%20%20%20%20%20%20category%0A"
            f"%20%20%20%20%20%20sk%20%7B%0A%20%20%20%20%20%20%20%20name%0A"
            f"%20%20%20%20%20%20%20%20__typename%0A%20%20%20%20%20%20%7D%0A"
            f"%20%20%20%20%20%20ner%20%7B%0A%20%20%20%20%20%20%20%20name%0A"
            f"%20%20%20%20%20%20%20%20__typename%0A%20%20%20%20%20%20%7D%0A"
            f"%20%20%20%20%20%20__typename%0A%20%20%20%20%7D%0A"
            f"%20%20%20%20audio%20%7B%0A%20%20%20%20%20%20duration%0A"
            f"%20%20%20%20%20%20__typename%0A%20%20%20%20%7D%0A"
            f"%20%20%20%20html%0A%20%20%20%20teaserText%0A"
            f"%20%20%20%20contentLength%0A%20%20%20%20postedDate%0A"
            f"%20%20%20%20__typename%0A%20%20%7D%0A%7D%0A"
            f"&operationName=article&variables=%7B%22categoryId%22%3A"
            f"%22{category_id}%22%2C%22articleId%22%3A%22{article_id}%22%7D"
        )

        article = json.loads(requests.get(CNALIFESTYLE_API_URL).content)["data"]["article"]

        title = article["title"]
        body = ""

        article_soup = BeautifulSoup(article["html"], "html.parser")
        for line in article_soup.find_all(cls.is_p_tag_without_figure_or_picture):
            body += line.get_text() + "\n\n"

        return Comment(title, body.strip())
Ejemplo n.º 23
0
 def post(self, post_id, user_id):
     content = self.request.get("content")
     username = self.isLoggedIn()
     post_key = db.Key.from_path('Post', int(post_id), parent=blog_key())
     key = db.Key.from_path('Post', int(post_id), parent=blog_key())
     post = db.get(post_key)
     if content:
         if username and post:
             comment = Comment(parent=key,
                               user_id=int(user_id),
                               content=content)
             comment.put()
             self.redirect('/blog/' + post_id)
         else:
             self.redirect("/login")
     else:
         error = "Comment must have content!"
         self.render("addcomment.html", content=content, error=error)
Ejemplo n.º 24
0
	def generate_f_data():
		"""Generates fictional data to load the program."""
		ch = Channel("Life","This channel is made to talk about life")
		ch2 = Channel("None", "none")
		u = User.users[random.choice(list(User.users.keys()))]
		u2 = User.users[random.choice(list(User.users.keys()))]
		while u == u2:
			u2 = User.users[random.choice(list(User.users.keys()))]
		a = Admin("Valentina", "Vvasquez", "*****@*****.**", "V123")
		q = Question(u, ch, "What is life?")
		c = Comment(u2, q, "That is; in fact, a hard question, what would it be?")
		r = Rating(u2, q, "like")
		r1 = Rating(a, c, "dislike")
		q2 = Question(u2, ch, "What is love?")
		c2 = Comment(u, q2, "The affection you feel for someone; or even, something.")
		r2 = Rating(a, q2, "dislike")
		q3 = Question(a, ch, "What is Death?")
		n = New(a, "The hollow has come!", "That witch has taken my daughthers body.", "Niklaus.", "Drama")
Ejemplo n.º 25
0
    def post(self, post_id):
        if not self.user:
            self.render("login-form.html",
                        alert = "Please login to comment")

        content = self.request.get('content')
        uid = self.read_secure_cookie('user_id')
        user_name = self.user.name

        if content:
            post = Comment(parent = blog_key(),
                   content = content, user_id = uid, parent_id = post_id,
                   user_name = user_name)
            post.put()
            self.redirect('/blog/%s' % post_id)
        else:
            error = "Subject and content can't be blank"
            self.render("post.html", content = content,
                error = error)
Ejemplo n.º 26
0
    def handle_non_premium(cls):
        """Handle a non-premium article."""
        article = Article(cls.url)
        article.download()
        article.parse()

        title = article.title
        body = article.text

        return Comment(title, body)
Ejemplo n.º 27
0
 def get(self, post_id):
     post = Post.by_id(post_id)
     comments = Comment.comments_by_post_id(post.key().id())
     if not post:
         self.redirect('/blog')
         return
     if self.user:
         self.render("permalink.html", post = post, username = self.user.name,comments=comments,user_id=self.user.key().id())
     else:
         self.render("permalink.html", post = post,comments=comments)
Ejemplo n.º 28
0
def get_contribution_comments(contribution_id):
    comments = Comment.get_comments_by_contribution(repository, contribution_id)
    results = []
    for comment in comments:
        votes = UserCommentVoted.get_votes_of_a_comment(comment.id, repository)
        comment.votes = votes
        if comment.parent_id is None:
            result = parse_comment(comment)
            results.append(result)
    return results
Ejemplo n.º 29
0
 def get(self, post_id):
     # post_id is the blog id
     blog = Blog.get_by_id(int(post_id))
     if blog:
         # Fetch all comments that are tied to the blog.
         comments = Comment.by_blog(post_id)
         self.render('blogpost.html', blog=blog, user_id=self.user_id,
                     comments=comments)
     else:
         self.redirect('/blog/permissionerror/')
Ejemplo n.º 30
0
    def handle(cls, url):
        html = requests.get(url).text
        soup = BeautifulSoup(html, "html.parser")
        title = soup.find("meta", {"property": "og:title"})["content"]
        body = ""
        for line in soup.select(
                "div.body-copy > p, div.body-copy > h2, div.substory h2"):
            body += line.get_text() + "\n\n"

        return Comment(title, body.strip())
Ejemplo n.º 31
0
 def get_all_comments(self):
     (status, result) = self._send_template_request('getAllComments',
                                                    {'task_id': self.id})
     if status and result:
         comments = []
         for comment_info in result:
             comments.append(Comment(self, comment_info))
         return comments
     else:
         return []
Ejemplo n.º 32
0
 def handle(cls, url):
     html = requests.get(url).text
     soup = BeautifulSoup(html, "html.parser")
     article_id = soup.find("meta", {"name":"cXenseParse:recs:articleid"})["content"]
     TODAY_API_URL = f"https://www.todayonline.com/api/v3/article/{article_id}"
     article = json.loads(requests.get(TODAY_API_URL).content)["node"]
     title = article["title"]
     body = BeautifulSoup(article["body"], "html.parser").get_text()
     body = body.replace("\n", "\n\n")  # Markdown requires 2 \n to create a new paragraph
     return Comment(title, body)
Ejemplo n.º 33
0
    def test_command_sorter(self):
        Labels = ["外部放電", "內部放電", "雜訊干擾"]

        input_comment = [
            "受DS-TIE外部放電影響。",
            "外部放電。",
            "經現場定位雷丘內部放電",
            "內部放電皮卡皮卡。",
            "受雜訊干擾。",
            "雜訊干擾。",
        ]

        c = Comment()
        c.input_comment = input_comment
        c.ground_truth = [0, 0, 1, 1, 2, 2]
        s = Sorter(c)
        s.command_sort(Labels)

        self.assertEqual(s.c.prediction, [0, 0, 1, 1, 2, 2])
Ejemplo n.º 34
0
    def handleNonPremium(cls):

        article = Article(cls.url)
        article.download()
        article.parse()

        title = article.title
        body = article.text

        return Comment(title, body)
    def load_comments_and_gender_and_comment_likes_from_mysql(self):
        """
        Function to load in comments, gender and comment likes from SQL dump
        Returns a list that contain gender of the commenter, comment body,
        male comment likes, female comment likes, total 
        likes and male/female ratio comment like
        """
        cnx = self.establish_new_mysql_connection()
        cursor = cnx.cursor()
        query = ("""
            SELECT u.u_name, c.c_body, group_concat(cf.f_uid)
            As like_ids FROM Information.inf_dtu_user u,
            Information.inf_dtu_comment c,
            Information.inf_dtu_comment_flag cf where u.u_uid=c.c_uid
            and c.c_cid = cf.f_cid group by c.c_cid;
            """)
        cursor.execute(query)

        # Makes a list that for each row contains name,
        # comments and name of the persons who liked the comment
        for c in cursor:
            if c[0] is not None:
                _male_likes = 0
                _female_likes = 0
                comment = Comment(c[1])
                comment.author = c[0].split()[0].lower()
                # Determines if the commenter is a male or female
                comment.gender = self.gh.get_gender_by_name(comment.author)
                like_ids = c[2].split(",")
                # Determines what gender the comment likes are
                # and count the number of male, female and total comment likes
                for like_id in like_ids:
                    if int(like_id) in self.firstnames_and_ids.keys():
                        lname = self.firstnames_and_ids[int(like_id)]
                        gender = self.gh.get_gender_by_name(lname)
                        if gender == "male":
                            _male_likes += 1
                        elif gender == "female":
                            _female_likes += 1
                comment.male_likes = _male_likes
                comment.female_likes = _female_likes
                self.comments.append(comment)
Ejemplo n.º 36
0
 def get(self, post_id):
     comment = Comment.by_id(int(post_id))
     if comment:
         # Only the commentor can edit the comment.
         if comment.user_id == self.user_id:
             self.render('editcomment.html', comment=comment)
         else:
             comment_error = """Only the Commenter
                             can edit this comment."""
             blog_id = comment.blog_id
             blog = Blog.by_id(blog_id)
             comments = Comment.by_blog(blog_id)
             self.render('blogpost.html', blog=blog,
                         user_id=self.user_id,
                         comments=comments,
                         comment_error_id=int(post_id),
                         comment_error=comment_error)
     else:
         self.render('permissionerror.html',
                     error="Comment doesn't exist")
Ejemplo n.º 37
0
def edit_user_username():
    if request.method == 'POST':
        username = User.find_by_id(session['USERNAME'])
        user = User.find_by_username(username)
        edit_username = request.form['username']
        if User.find_by_username(edit_username):
            flash('This username is already registered!')
            return redirect('/user_info')
        edit_oldpassword = request.form['oldpassword']
        if not user or not user.verify_password(edit_oldpassword):
            flash('Incorrect password!')
            return redirect('/user_info')
        user.username = edit_username
        logging.info('%s with id: %s changed his username to %s',
                     User.find_by_id(session['USERNAME']), session['USERNAME'],
                     edit_username)

        User.save_username(user)
        Comment.update_username(user.username, session['USERNAME'])
        return redirect('/user_info')
Ejemplo n.º 38
0
def return_newest_contributions():
    contributions = Contribution.get_contributions_new(repository)
    for c in contributions:
        aux = Comment.get_number_comments_by_contribution(repository, str(c['id']))
        c['n_comments'] = aux[0]['n_comments']
        aux = UserContributionVoted.get_votes_contribution(repository, str(c['id']))
        contribution_votes = []
        for aux_v in aux:
            contribution_votes.append(aux_v['username'])
        c['contribution_votes'] = contribution_votes
    return Response(json.dumps(contributions), mimetype='application/json')
Ejemplo n.º 39
0
def create_comment(request):
    time = datetime.strptime(str(datetime.now().replace(microsecond=0)),
                             '%Y-%m-%d %H:%M:%S')
    text = request.form['comment']
    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        url = request.environ['REMOTE_ADDR']
    else:
        url = request.environ['HTTP_X_FORWARDED_FOR']
    comment = Comment(time, 'anonymous', url, text, 'no', 'no')
    #print(comment)
    return comment
Ejemplo n.º 40
0
def split_set_in_parts(xml_file, parts_size):
    parts = [[] for _ in range(parts_size)]
    # Init the random seed in order to produce the same split of a set every time
    rand = random.Random(0)

    tree = ET.parse(xml_file)
    root = tree.getroot()
    for thread in root:
        question_tag = thread[0]
        question_id = question_tag.attrib['RELQ_ID']
        question_subject = question_tag[0].text
        question_text = question_tag[1].text
        question_category = question_tag.attrib['RELQ_CATEGORY']
        question_user = question_tag.attrib['RELQ_USERID']
        question_date = question_tag.attrib['RELQ_DATE']
        question_subject = ignore_non_utf8(question_subject)
        question_text = ignore_non_utf8(question_text)
        question_fact_label = question_tag.attrib['RELQ_FACT_LABEL']

        if question_fact_label == 'Single Question - Factual':
            parts_index = -1
            for index, comment_tag in enumerate(thread):
                if index > 0:  # the 0 index was processed above - it is the question
                    comment_id = comment_tag.attrib['RELC_ID']
                    comment_text = comment_tag[0].text
                    comment_user = comment_tag.attrib['RELC_USERID']
                    comment_date = comment_tag.attrib['RELC_DATE']
                    comment_fact_label = comment_tag.attrib['RELC_FACT_LABEL']
                    comment = Comment(question_id, comment_id,
                                      question_category, question_subject,
                                      question_text, comment_text,
                                      comment_user, comment_date)

                    label = get_label(comment_fact_label)
                    if label > -1:
                        # if any of the comments is in the labels, add it to the subset part
                        comment.label = label
                        if parts_index == -1:
                            parts_index = rand.randint(0, parts_size - 1)
                        parts[parts_index].append(comment)
    return parts
Ejemplo n.º 41
0
    def post(self, post_id):
        key = db.Key.from_path('Post', int(post_id), parent=blog_key())
        post = db.get(key)
        likes = post.likes
        likers = post.likers
        error = ""

        if (self.user):
            if (self.request.get('like') == post_id):
                if post.author == self.user.name:
                    error = "The author of a post cannot like their own post"
                elif self.user.name in post.likers:
                    post.likes -= 1
                    post.likers.remove(self.user.name)
                    post.put()
                else:
                    post.likes = post.likes + 1
                    post.likers.append(self.user.name)
                    post.put()

            if (self.request.get('comment')):
                c = Comment(parent=blog_key(),
                            content=self.request.get('comment'),
                            post_id=int(post_id),
                            user_id=self.user.key().id())
                post.comment_count = post.comment_count + 1
                post.put()
                c.put()

            comments = db.GqlQuery("select * from Comment where post_id = " +
                                   post_id + " order by created desc")

            time.sleep(0.2)

            self.render("permalink.html",
                        post=post,
                        user=self.user,
                        error=error,
                        comments=comments)
        else:
            self.redirect("/login")
Ejemplo n.º 42
0
def main(argv):  # type: (list[str]) -> int
    try:
        Debug.make_python_warnings_show_stack_traces()
        options = parse_args(argv[1:])
        print(options)

        if options.windows_path:
            if options.prefix:
                options.prefix = options.prefix.lower().replace('\\', '/')

        repo = github_connection.Repo(options)
        pr = repo.get_pull_request(options.pull_request)

        if options.sarif_file:
            modified_ranges = pr.get_modified_ranges()
            print modified_ranges

            comments = get_comments(options, modified_ranges)

            adjust_comment_paths(options, comments)

            removed = filter_comments(options, modified_ranges, comments)

            adjust_formatters(comments, AnnotateFormatter(options))

            sort_comments(options, comments)

            comments.insert(
                0,
                Comment(
                    'CodeSonar has detected the following warnings in files modified by this pull request.\n%d comments were not in files in this pull request.'
                    % removed, 0, '', '', '', LeadFormatter(options)))

            num_comments = cut_down_to_byte_size(options, comments,
                                                 modified_ranges)
            comments[
                0].body += '\n%d comments were redacted due to space constraints.\n' % (
                    len(comments) - num_comments)
            comments = comments[:num_comments]

            pr.make_review(modified_ranges, comments)
        if options.dump_pr_to_file:
            import json
            with open(options.dump_pr_to_file, 'w') as f:
                json.dump(pr.dump_last_review(),
                          f,
                          sort_keys=True,
                          indent=4,
                          separators=(',', ': '))
        return 0
    except UserError, e:
        print str(e)
        return 1
Ejemplo n.º 43
0
    def post(self):
        message = self.request.get("message")
        name = self.request.get("name")

        
        # Check if message or name is invalid
        if len(name.strip()) == 0 or len(message.strip()) == 0:
            PageHandler.invalid = True
        else:
            PageHandler.invalid = False

            # create a new comment object
            # set a message and name to it

            new_comment = Comment(parent=DEFAULT_KEY)
            new_comment.message = message
            new_comment.name = name

            # Save in the data-store
            new_comment.put()
            
        self.redirect("/#comments")
Ejemplo n.º 44
0
    def __init__(self, parentIssue, commentelem, mapToBE={}, dontprocess=set(), mapFromBE=None):
        """Initialises a new comment taken from an XML backing. mapToBE should be a dictionary
        mapping the source XML element tags to BE element names and outputs if necessary i.e
        mapToBE={'xmltag':('befield', lambda xmlelem:xmlelem.text)}
        Current BE comment fields:

        uuid: UUID
        [Alt-id]: string
        [short-name]: string
        [In-reply-to]: UUID
        Author: string
        Date: datetime string
        Content-type: mimetype string
        body: string
        """
        if mapFromBE is None: mapFromBE={v[0]:(k, v[1]) for k, v in mapToBE.iteritems()}
        CommentBase.__init__(self, parentIssue)
        self.__element=commentelem
        self.__elementhash=0
        self.__mapToBE=mapToBE
        self.__dontprocess=dontprocess
        self.__mapFromBE=mapFromBE
        self.__setUUID()
Ejemplo n.º 45
0
def comment(id=None):
    if request.method == 'POST':
        setting = request.form.get('setting')
        comment_id = request.form.get('value_0')

        if not setting or not comment_id:
            abort(400)
        try:
            comment_id = int(comment_id)
        except:
            abort(400)

        comment = Comment(comment_id)

        if not comment.id:
            abort(400)

        if setting == 'delete':
            comment.delete()
            flash(messages.comment_deleted)
            return redirect(url_for('admin_comment'))

        else:
            abort(404)

    else:
        if id:
            comment = Comment(id)
            comment = comment.get_comment()

            if not comment:
                flash(messages.comment_not_found)
        else:
            comment = None

        return render_template('admin/comment.html', comment=comment)
Ejemplo n.º 46
0
    def get(self, comment_id):
        # If any user does not logged in redirect to homepage
        if not self.user:
            self.redirect("/login")

        comment_to_update = Comment.find_by_id(comment_id)
        if not comment_to_update:
            self.error(404)
            return self.render('404.html')
        if not self.user.owner_of(comment_to_update):
            self.redirect("/")

        values = {'content': comment_to_update.content}
        self.render(
            "/comments/edit.html", comment=comment_to_update,
            values=values, errors=None)
Ejemplo n.º 47
0
    def post(self, comment_id):
        # If any user does not logged in redirect to homepage
        if not self.user:
            self.redirect("/login")

        comment_to_update = Comment.find_by_id(comment_id)
        if not comment_to_update:
            self.error(404)
            return self.render('404.html')
        if not self.user.owner_of(comment_to_update):
            self.redirect("/")

        values = {'content': self.request.get('content').strip()}
        if values['content']:
            comment_to_update.content = values['content']
            comment_to_update.put()
            self.redirect(comment_to_update.post.link_to('show'))
Ejemplo n.º 48
0
    def post(self, comment_id):
        # If any user does not logged in redirect to homepage
        if not self.user:
            self.redirect("/login")

        comment_to_dislike = Comment.find_by_id(comment_id)
        # If comment couldn't find redirect 404 page
        if not comment_to_dislike:
            self.error(404)
            return self.render('404.html')

        if not self.user.liked_comment_before(comment_to_dislike):
            self.redirect(comment_to_dislike.post.link_to('show'))
        else:
            for like in comment_to_dislike.commentlike_set:
                if like.user.key() == self.user.key():
                    like.delete()
                    break
        self.redirect(comment_to_dislike.post.link_to('show'))
Ejemplo n.º 49
0
    def post(self, comment_id):
        # If any user does not logged in redirect to homepage
        if not self.user:
            self.redirect("/login")

        comment_to_like = Comment.find_by_id(comment_id)
        # If comment couldn't find redirect 404 page
        if not comment_to_like:
            self.error(404)
            return self.render('404.html')
        # If user is owner of the comment, redirect with an error
        if self.user.owner_of(comment_to_like):
            self.redirect("/")
        # If user is liked this post before, redirect with an error
        elif self.user.liked_comment_before(comment_to_like):
            self.redirect(comment_to_like.post.link_to('show'))
        else:
            new_like = CommentLike(comment=comment_to_like, user=self.user)
            new_like.put()
        self.redirect(comment_to_like.post.link_to('show'))
Ejemplo n.º 50
0
    def post(self, comment_id):
        # If any user does not logged in redirect to homepage
        if not self.user:
            self.redirect("/login")

        comment_to_delete = Comment.find_by_id(comment_id)
        if not comment_to_delete:
            self.error(404)
            return self.render('404.html')
        if not self.user.owner_of(comment_to_delete):
            self.redirect("/")

        # Save post to use after delete
        parent_post = comment_to_delete.post

        # delete comment likes before
        for like in comment_to_delete.commentlike_set:
            like.delete()
        # then delete the comment
        comment_to_delete.delete()
        self.redirect(parent_post.link_to('show'))
Ejemplo n.º 51
0
    def pull(self):
        """
        Download page with blogpost. Parse text, comments and everything else.

        Until this is called, following attributes are not known/parsed:

            - :attr:`text`
            - :attr:`tags`
            - :attr:`has_tux`
            - :attr:`comments`
            - :attr:`last_modified_ts`
        """
        data = download(url=self.url)

        # this is because of f***s who forgot to close elements like in this
        # blogpost: https://www.abclinuxu.cz/blog/EmentuX/2005/10/all-in-one
        blog_data, comments_data = data.split('<p class="page_tools">')

        self._dom = dhtmlparser.parseString(blog_data)
        self._content_tag = None
        dhtmlparser.makeDoubleLinked(self._dom)

        self._parse_uid()
        self._parse_title()
        self._parse_text()
        self._parse_rating()
        self._parse_meta()

        self._tags = self._get_tags()

        # there are blogs with f****d up HTML which is basically unparsable
        if self.relative_url not in COMMENT_BANLIST:
            self.comments = Comment.comments_from_html(comments_data)
            self.comments_n = len(self.comments)

        # memory cleanup - this saves a LOT of memory
        self._dom = None
        self._content_tag = None
Ejemplo n.º 52
0
 def comments(self):
     return Comment.find(article_id=self.id)
Ejemplo n.º 53
0
 def __init__(self, comments = None):
     self._comment = Comment()
     super(CommentController, self).__init__()