示例#1
0
def tag_view(tag_name):
    tag = Tag(tag_name)
    posts = True
    # existance of the attributes _ORIGINAL_ATTR denotes the model instance
    # is not new and interfaces an entry in table
    if not hasattr(tag, '_ORIGINAL_ATTR'):
        error_context = {
            'error_name':
            "404 Not Found",
            'error_info':
            "The tag you tried to access does not exist, but you can create this tag."
        }
        return render_template('error.html', **error_context)

    # TODO: Implement tag page and pagination

    page_index = int(request.args.get('page') or 1)
    if not isinstance(page_index, int):
        page_index = 1
    if page_index <= 0:
        page_index = 1

    context = {
        'tag_info': {
            'title': tag.title,
            'rules': tag.rules,
            'description': tag.description
        }
    }
    context['pagination'] = tag.paginate(page_index)
    return render_template('tag.html', **context)
 def test_deletes_tip(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     tip = self.repository.get_tips(self.user, "all")[0]
     self.repository.delete_tip(tip)
     self.assertEqual(self.repository.get_tips(self.user, "all"), [])
示例#3
0
def tag_moderate_remove_mod(tag_name):
    """Form processor for removing existing moderators
    """
    try:
        tag = Tag(tag_name)
    except:
        error_context = {
            'error_name':
            "404 Not Found",
            'error_info':
            "The tag you tried to access does not exist, but you can create this tag."
        }
        return render_template('error.html', **error_context)

    if not check.logged_in():
        error_context = {
            'error_name': "Forbidden",
            'error_info': "You may not access this page without logging in"
        }
        return render_template('error.html', **error_context)

    if not TagModerator.is_mod(session['user_id'], tag.id):
        error_context = {
            'error_name': "Access Denied",
            'error_info': "You are not a moderator of this tag"
        }
        return render_template('error.html', **error_context)

    form = TagModForm(csrf_enabled=False)
    if form.validate_on_submit():
        username_to_remove = form.user.data
        if username_to_remove:
            try:
                user = User.get_from_username(username_to_remove)
            except:
                flash('User does not exist')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            if not user:
                flash('User does not exist')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            if not TagModerator.is_mod(user.id, tag.id):
                flash('Specified user is not a mod')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            if user.id == session['user_id']:
                flash('You may not delete yourself as a mod')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            tag.mod_remove_user(user.id)
            flash('User removed as mod successfully')
            return redirect(
                url_for('tag_pages.tag_moderate', tag_name=tag_name))
        else:
            flash('Invalid Input')
            return redirect(
                url_for('tag_pages.tag_moderate', tag_name=tag_name))

    return redirect(url_for('tag_pages.tag_moderate', tag_name=tag_name))
示例#4
0
    async def create(
        self,
        ctx,
        name: clean_content,
        tag_type: TagTypeConverter,
        *content: clean_content,
    ):
        """create tag content"""
        with self.bot.session_scope() as session:
            if Tag.exists(name, ctx.guild.id, session):
                raise NerpyException("tag already exists!")

        async with ctx.typing():
            with self.bot.session_scope() as session:
                self.bot.log.info(
                    f"creating tag {ctx.guild.name}/{name} started")
                _tag = Tag(
                    Name=name,
                    Author=str(ctx.author),
                    Type=tag_type,
                    CreateDate=datetime.utcnow(),
                    Count=0,
                    Volume=100,
                    GuildId=ctx.guild.id,
                )

                Tag.add(_tag, session)
                session.flush()

                self._add_tag_entries(session, _tag, content)

            self.bot.log.info(f"creating tag {ctx.guild.name}/{name} finished")
        await self.bot.sendc(ctx, f"tag {name} created!")
示例#5
0
    def parse(self):
        results = []
        for x, tag in enumerate(self.html.descendants):

            if str(type(tag)) == "<class 'bs4.element.Tag'>":

                if tag.name == 'script':
                    continue

                # Find tags with no children (base tags)
                if tag.contents:
                    if sum(1 for _ in tag.descendants) == 1:
                        t = Tag(tag.name.lower())

                        # Because it might be None (<i class="fa fa-icon"></i>)
                        if tag.string:
                            t.add_content(tag.string)

                        if tag.attrs:
                            for a in tag.attrs:
                                t.add_attribute(a, tag[a])

                        results.append(t.get_data())

                # Self enclosed tags (hr, meta, img, etc...)
                else:
                    t = Tag(tag.name.lower())

                    if tag.attrs:
                        for a in tag.attrs:
                            t.add_attribute(a, tag[a])

                    results.append(t.get_data())

        return results
示例#6
0
 def test_constructor_sets_fields_correctly(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     readingtip = ReadingTip("Hyvä kirja", "https://kirjakauppa.fi/123",
                             self.user, tags)
     self.assertEqual(readingtip.title, "Hyvä kirja")
     self.assertEqual(readingtip.link, "https://kirjakauppa.fi/123")
     self.assertEqual(readingtip.tags[0].name, "kirjat")
     self.assertEqual(readingtip.tags[1].name, "maksulliset")
示例#7
0
    def setUp(self):
        self.company_1 = Company("RailScot")
        self.tag_1 = Tag("travel")
        self.company_2 = Company("Pilot Beer")
        self.tag_2 = Tag("food")

        self.transaction_1 = Transaction(10.00, self.company_1, self.tag_1)
        self.transaction_2 = Transaction(6.50, self.company_2, self.tag_2)
示例#8
0
def post(tag_name):
    if Tag.exists(tag_name):
        return error_view(500, "tag already exists")

    new_tag = Tag.new(tag_name)
    new_tag.insert()

    return tag_created_view(new_tag)
示例#9
0
    def test_get_reactions_per_tag(self):
        tag = Tag("tagname1")
        tag.register_article(Article('t', 0, 6, 0, None, ["tagname1"]))
        tag.register_article(Article('t', 0, 8, 0, None, ["tagname1"]))

        self.assertEqual({tag: 7},
                         tag_analytics.get_reactions_per_article_for_each_tag(
                             [tag]))
    def test_cannot_see_others_tip(self):
        tags = [Tag("kirjat"), Tag("maksulliset")]
        second_user = self.user_repository.register("mikko", "oko7Aeko")
        self.repository.create_tip(
            ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", second_user, tags))

        assert not self.repository.contains_title(self.user, "Hyvä kirja")
        self.assertEqual(self.repository.get_tips(self.user, "all"), [])
示例#11
0
    def test_get_views_per_tag(self):
        tag = Tag("tagname1")
        tag.register_article(Article('t', 300, 0, 0, None, ["tagname1"]))
        tag.register_article(Article('t', 500, 0, 0, None, ["tagname1"]))

        self.assertEqual({tag: 400},
                         tag_analytics.get_views_per_article_for_each_tag(
                             [tag]))
 def test_marks_tip_as_read(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     assert self.repository.get_tips(self.user)[0].read is None
     self.repository.read_tip(
         self.repository.get_tips(self.user)[0], "2021")
     assert self.repository.get_tips(self.user)[0].read is not None
示例#13
0
    def test_get_comments_per_tag(self):
        tag = Tag("tagname1")
        tag.register_article(Article('t', 0, 0, 0, None, ["tagname1"]))
        tag.register_article(Article('t', 0, 0, 2, None, ["tagname1"]))

        self.assertEqual({tag: 1},
                         tag_analytics.get_comments_per_article_for_each_tag(
                             [tag]))
示例#14
0
def update_tag(tag_id, meta):
    tag = Tag.get(id=tag_id)
    if (tag.meta or {}).get("admin", False):
        api_assert(current_user.is_admin, "Tag can only be modified by admin")

    return Tag.update(id=tag_id,
                      fields={"meta": meta},
                      skip_if_value_none=True)
 def test_create_tip(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     tips = self.repository.get_tips(self.user, "all")
     self.assertEqual(tips[0].title, "Hyvä kirja")
     self.assertEqual(tips[0].tags[0].name, "kirjat")
     self.assertEqual(tips[0].tags[1].name, "maksulliset")
示例#16
0
    async def delete(self, ctx, name: clean_content):
        """delete a tag?"""
        self.bot.log.info(f"trying to delete {name} from {ctx.guild.id}")
        with self.bot.session_scope() as session:
            if not Tag.exists(name, ctx.guild.id, session):
                raise NerpyException("tag doesn't exist!")

            Tag.delete(name, ctx.guild.id, session)
        await self.bot.sendc(ctx, "tag deleted!")
示例#17
0
 def post(self):
     iKwargs = request.form.to_dict()
     tag = TagModel()
     # data = {
     #     'name': iKwargs['name'],
     #     'articleList': {}
     # }
     iKwargs["articleList"] = {}
     tag.create(iKwargs)
     return {}
 def test_can_get_tips_based_on_tags(self):
     tags = [Tag("Hyvä")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     second_tags = [Tag("Huono")]
     self.repository.create_tip(
         ReadingTip("Huono kirja", "kirjakauppa.fi/123", self.user,
                    second_tags))
     self.assertEqual(len(self.repository.get_tips(self.user, "all")), 2)
     self.assertEqual(len(self.repository.get_tips(self.user, "Hyvä")), 1)
 def test_update_tip(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     tags.append(Tag("uusi"))
     self.repository.update_tip(1, "Muutettu kirja", "kirjakauppa.fi/123",
                                tags)
     self.assertEqual(
         self.repository.get_tips(self.user)[0].title, "Muutettu kirja")
     self.assertEqual(
         self.repository.get_tips(self.user)[0].tags[2].name, "uusi")
def create_or_update_tag(tag_name, commit=True, session=None):
    tag = Tag.get(name=tag_name, session=session)

    if not tag:
        tag = Tag.create({"name": tag_name, "count": 1}, commit=commit, session=session)
    else:
        tag = Tag.update(
            id=tag.id, fields={"count": tag.count + 1}, commit=commit, session=session,
        )

    return tag
示例#21
0
    async def volume(self, ctx, name: clean_content, vol):
        """adjust the volume of a sound tag (WIP)"""
        self.bot.log.info(f"set volume of {name} to {vol} from {ctx.guild.id}")
        with self.bot.session_scope() as session:
            if not Tag.exists(name, ctx.guild.id, session):
                raise NerpyException("tag doesn't exist!")

        with self.bot.session_scope() as session:
            _tag = Tag.get(name, ctx.guild.id, session)
            _tag.Volume = vol
        await self.bot.sendc(ctx, f"changed volume of {name} to {vol}")
示例#22
0
def delete(tag_name):
    if not Tag.exists(tag_name):
        return error_view(404, "tag not found")

    tag = Tag.get(tag_name)
    tag.delete()

    tag_links = TagDnIP.list_from_tag(tag.name)
    for t in tag_links:
        t.delete()

    return tag_deleted_view(tag)
示例#23
0
 def post(self):
     tag_id = int(self.get_argument('id'))
     if not tag_id:
         tag = Tag()
         tag.father_id = self.get_argument('father_id')
     else:
         tag = self.orm_session.query(Tag).filter_by(id=tag_id).first()
     if tag:
         tag.active = self.get_argument('active')
         tag.name = self.get_argument('name')
         self.orm_session.add(tag)
         self.orm_session.commit()
     self.write(dict(ret=0))
示例#24
0
    async def add(self, ctx, name: clean_content, *content: clean_content):
        """add an entry to an existing tag"""
        with self.bot.session_scope() as session:
            if not Tag.exists(name, ctx.guild.id, session):
                raise NerpyException("tag doesn't exists!")

        async with ctx.typing():
            with self.bot.session_scope() as session:
                _tag = Tag.get(name, ctx.guild.id, session)
                self._add_tag_entries(session, _tag, content)

            self.bot.log.info(f"added entry to tag {ctx.guild.name}/{name}.")
        await self.bot.sendc(ctx, f"Entry added to tag {name}!")
示例#25
0
    def action_update_tags(self, slug=None):
        for tag in Tag.all():
            tag.delete()
        for entry in Entry.all().filter('entrytype =', 'post'):
            if entry.tags:
                for t in entry.tags:
                    try:
                        logging.info('sss:' + t)
                        Tag.add(t)
                    except:
                        traceback.print_exc()

        self.write('"All tags for entry have been updated."')
示例#26
0
文件: image.py 项目: aleung013/DWAI
 def add_tag(self, label):
     tags = Tag()
     t = tags.find_one(label=label)
     if not t:
         t = tags.insert(label=label)
     if not any(d['label'] == label for d in self.tags):
         t.count += 1
         t.save()
         t._obj.pop('count')
         self.tags.append(t._obj)
         self.save()
         return True
     return False
示例#27
0
    def __init__(self, anchors, database, isMaster):
        # init the Drone as inactive
        self.active = False

        # init drone as Master or Worker
        self.isMaster = isMaster

        # init the database
        self.database = database

        # init the tag, that tracks the Drone (pozyx)
        try:
            self.tag = Tag(anchors)
        except PozyxConnectionError:
            print("No Pozyx Tag found - will mock up position for tests.")
            # if no tag found, set it to None
            self.tag = None

        if self.tag is not None:
            # setup for the Tag
            self.tag.setup()

        # init anchors
        self.anchors = anchors

        try:
            from models.yaw_detection import YawDetection
            # import yawDetection class
            self.yaw_detector = YawDetection()
        except ImportError:
            print("couldn't start camera and opencv")
            # if opencv fails, set detector None
            self.yaw_detector = None

        # class, that communicates with the flight controller
        self.control = None

        # current position of the drone (x, y, z)
        self.position = None

        # current orientation of the drone (yaw, roll, pitch)
        self.orientation = None

        # create a Tag in the database and saves the id of the drone tag objects entity
        self.tag_id = database.tag.put(TagModel())

        # create the Tag entity - easy read and write
        self.tag_object = database.tag.get(self.tag_id)

        # init LED-Stick
        self.led_sticks = LedStick(self.tag_id, database)
示例#28
0
 def post(self):
     from models.tag import Tag
     from app import db
     try:
         t = Tag()
         t.name = request.json.get('name')
         t.type = request.json.get('type')
         db.session.add(t)
         db.session.commit()
     except Exception as e:
         print(e)
         db.session.rollback()
         return 'ERROR', 500
     return 'success', 200
示例#29
0
    def updatePosition(self):
        if self.tag is not None:
            # update position & orientation from the Tag
            self.position = self.tag.getPosition()
            # ToDo: merge OpenCV and Pozyx orientation
            self.orientation = self.tag.getOrientation()
        else:
            # load mocked classes for testing
            self.position = Tag.mockedPosition()
            self.orientation = Tag.mockedOrientation()

        if self.yaw_detector is not None and self.yaw_detector.initVideocapture():
            # Merge detected Angle with pozyx Angle
            print("yaw detector angle: ", self.yaw_detector.getAngle())
示例#30
0
    def test_get_most_comments_per_article_tag(self):
        most_popular_tag = Tag("tagname1")
        most_popular_tag.register_article(
            Article('t', 0, 0, 3, None, ["tagname1"]))
        most_popular_tag.register_article(
            Article('t', 0, 0, 3, None, ["tagname1"]))

        other_tag = Tag("tagname2")
        other_tag.register_article(Article('t', 0, 0, 3, None, ["tagname2"]))
        other_tag.register_article(Article('t', 0, 0, 1, None, ["tagname2"]))

        self.assertEqual(
            most_popular_tag,
            tag_analytics.get_most_comments_per_article_tag(
                [most_popular_tag, other_tag]))
示例#31
0
    def test_get_most_reactions_per_article_tag(self):
        most_popular_tag = Tag("tagname1")
        most_popular_tag.register_article(
            Article('t', 0, 6, 0, None, ["tagname1"]))
        most_popular_tag.register_article(
            Article('t', 0, 8, 0, None, ["tagname1"]))

        other_tag = Tag("tagname2")
        other_tag.register_article(Article('t', 0, 2, 0, None, ["tagname2"]))
        other_tag.register_article(Article('t', 0, 8, 0, None, ["tagname2"]))

        self.assertEqual(
            most_popular_tag,
            tag_analytics.get_most_reactions_per_article_tag(
                [most_popular_tag, other_tag]))
示例#32
0
 def setUp(self):
     db.create_all()
     author1 = Author('Matt')
     author2 = Author('Elie')
     tag1 = Tag('Sci Fi')
     tag2 = Tag('Horror')
     tag3 = Tag('Biography')
     db.session.add_all([author1, author2, tag1, tag2, tag3])
     db.session.commit()
     book1 = Book('Night of the Living Decorator', author2.id)
     book1.tags = [tag2]
     book2 = Book("Matt's Scary Sci Fi book", author1.id)
     book2.tags = [tag1, tag2]
     db.session.add_all([book1, book2])
     db.session.commit()
示例#33
0
def admin_add_problem():
    """
    Add problem, input and tag view.
    :return: HTTP Response
    """
    if request.method == 'POST':

        problem = Problems(problem_name=request.form['problem_name'],
                           statement=request.form['statement'],
                           contest_id=request.form['contest_id'],
                           max_score=request.form['max_score'])
        problem.save()

        inp = Input(problem_id=problem.problem_id,
                    testcase=request.form['sample'],
                    expected_output=request.form['sampleout'])
        inp.save()

        for i in range(1, 30):
            if request.form.get('addinp' + str(i), '') and request.form.get(
                    'expout' + str(i), ''):
                inp = Input(problem_id=problem.problem_id,
                            testcase=request.form['addinp' + str(i)],
                            expected_output=request.form['expout' + str(i)])
                inp.save()

        tags = []
        for i in range(1, 30):
            if request.form.get('tagin' + str(i), ''):

                tag_name = request.form['tagin' + str(i)]
                tag = Tag.get(tag_name=tag_name)

                if tag:
                    tag = tag[0]
                else:
                    tag = Tag(tag_name=tag_name)
                    tag.save()

                tags.append(tag)

        if tags:
            ProblemTag.save_tags_to_problem(problem, tags)

        return redirect(url_for('admin.admin_home'))
    else:
        contests = Contest.get_all()
        return render_template('admin_add_problem.html', contests=contests)
示例#34
0
    def top(cls, tag=None, **kwargs):
        if tag is not None:
            kwargs['tag_id'] = Tag.get(name=tag)['_id']

        expenses = sorted(cls.all(**kwargs), key=lambda x: float(x['cost']), reverse=True)

        return [ x.json for x in expenses[:5] ]
示例#35
0
    def get(self):

        urls = []

        def addurl(loc, lastmod=None, changefreq=None, priority=None):
            url_info = {
                'location': loc,
                'lastmod': lastmod,
                'changefreq': changefreq,
                'priority': priority,
            }
            urls.append(url_info)

        addurl(g_blog.baseurl, changefreq='daily', priority=1)

        entries = Entry.all().filter('published =', True).order('-date').fetch(g_blog.sitemap_entries)

        for item in entries:
            loc = '%s/%s' % (g_blog.baseurl, item.link)
            addurl(loc, item.date, 'daily', 0.9)

        if g_blog.sitemap_include_category:
            cats = Category.all()
            for cat in cats:
                loc = '%s/category/%s' % (g_blog.baseurl, cat.slug)
                addurl(loc, None, 'weekly', 0.8)

        if g_blog.sitemap_include_tag:
            tags = Tag.all()
            for tag in tags:
                loc = '%s/tag/%s' % (g_blog.baseurl, urlencode(tag.tag))
                addurl(loc, None, 'weekly', 0.8)

        self.response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        self.render2('views/sitemap.xml', {'urlset': urls})
示例#36
0
    def get(self, tags=None):
        entries = Entry.all().order('-date')
        cates = Category.all()
        tags = Tag.all()

        self.response.headers['Content-Type'] = 'binary/octet-stream'  # 'application/atom+xml'
        self.render2('views/wordpress.xml', {'entries': entries, 'cates': cates, 'tags': tags})
示例#37
0
    def get(self, request, tag_id):
        try:
            tag = Tag.objects(id = ObjectId(tag_id)).first()
            message = tag.to_json()
        except:
            message = {"error": "Tag not found"}

        return HttpResponse(dumps(message))
示例#38
0
    def get_last_twelve_months_tag_expenses(self):
        last_year = date_helper.get_last_year_date()
        logging.info("last year = %d" % last_year.year)
        month_year = last_year.year * 12 + last_year.month
        logging.info("month year = %d" % month_year)
        self.compute_labels(last_year)
        q = Tag.query(ancestor=Tag.get_tag_parent_key(self.category))
        tags = q.fetch(1000)
        amounts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        for tag in tags:
            if tag.amount is not None:
                index = tag.monthyear - month_year
                if index not in range(0, 12):
                    continue
                logging.info("tag=%s amount=%f index=%d" % (tag.name, tag.amount, index))
                amounts[index] += tag.amount
                self.totalamount += tag.amount

        self.compute_max_amount(amounts)
示例#39
0
 def addtag(self, args):
     tag = args['tag']
     if tag != '':
         response = Tag.add_tag(tag);
         if not response:                
             return json.dumps({"succes": False})
         else:
             return json.dumps({"succes": True, "id":response})
     else:
         return json.dumps({"succes": False})
示例#40
0
    def json_get_tags():
        # create json file of all tags
        tags = Tag.get_all()
        # list of dicytionaries
        data = []
        for tag in tags:
            data.append({"id": tag.id, "name": tag.name})

        # Qreturn "Test return"
        return json.dumps(data)
示例#41
0
    def progress(self):
        from models.expense import Expense
        from models.expectation import Expectation

        expenses = Expense.all(user_id=self['_id'])
        savings = [ x for x in expenses if Tag.get(_id=x['tag_id'])['name'] == 'saving' ]
        expectation = Expectation.get(user_id=self['_id'])

        total_savings = sum(float(x['cost']) for x in savings)

        return int((float(expectation['cost']) - total_savings * 100) / float(expectation['cost']))
示例#42
0
 def save_profile_image(uid,owner,image,callback=None):
         image = cStringIO.StringIO(base64.b64decode(image))
         cur_img = ProfileImage.objects(owner=uid).first()
         if cur_img != None:
             if image != None:
                 cur_img.image.replace(image,filename=owner.username)
                 cur_img.save()
                 user = Tag.objects(id=uid).first()
                 user.profile_img = cur_img
                 user.save()
         else:
             if image != None:
                 cur_img = ProfileImage(owner=uid)
                 cur_img.image.put(image,filename=owner.username)
                 cur_img.save()
                 user = Tag.objects(id=uid).first()
                 user.profile_img = cur_img
                 user.save()
         if callback != None:
             return callback(cur_img)
         return cur_img
示例#43
0
    def review():
        answer = Schedule.get_answer(g.lti.get_user_id())
        if answer == None:
            return "No answers to review."

        fsession['reviewanswer'] = answer.id

        enabledtags = AnswerTag.get_tag_ids(answer.id)
        reviews = Review.get_list(answer.id)

        return render_template('reviewanswer.html', answer=answer,
                               tags=Tag.get_all(), enabledtags=enabledtags,
                               reviews=reviews)
示例#44
0
 def get(self):
     # query = db.GqlQuery('SELECT * FROM Tag')
     query = Tag.query()
     tags = query.fetch(5000)
     jsonData = dict()
     tagnames = []
     for tag in tags:
         if tag == "":
             continue
         if tag.name not in tagnames:
             tagnames.append(tag.name)
     jsonData["source"] = tagnames
     self.response.out.write(simplejson.dumps(jsonData))
示例#45
0
 def retrieve(self, tagname, monthyear):
     query = Tag.query(Tag.monthyear == monthyear, ancestor=Tag.get_tag_parent_key(tagname))
     tagmodels = query.fetch(1)
     if len(tagmodels) == 0:
         tag = Tag(parent=Tag.get_tag_parent_key(tagname))
         tag.name = tagname
         tag.monthyear = monthyear
     else:
         tag = tagmodels[0]
     return tag
示例#46
0
    def review():
        answer = Schedule.get_answer(g.lti.get_user_id())
        if answer == None:
            return "No answers to review."

        fsession['reviewanswer'] = answer.id

        enabledtags = AnswerTag.get_tag_ids(answer.id)
        reviews = Review.get_list(answer.id)
        question = Question.by_id(answer.questionID)
        if question is None:
            return "Question was not found."

        return render_template('reviewanswer.html', answer=answer,
                               tags=Tag.get_all(), enabledtags=enabledtags,
                               reviews=reviews, question=question)
示例#47
0
    def initialize(self, request, response):
        try:
            BaseRequestHandler.initialize(self, request, response)

            m_pages = (
                Entry.all()
                .filter("entrytype =", "page")
                .filter("published =", True)
                .filter("entry_parent =", 0)
                .order("menu_order")
            )
            blogroll = Link.all().filter("linktype =", "blogroll")

            query = Entry.gql("WHERE entrytype = 'post' AND published = TRUE ORDER BY date")
            entries = query.fetch(1)
            start_date = end_date = None
            if entries:
                start_date = entries[0].date

            query = Entry.gql("WHERE entrytype = 'post' AND published = TRUE ORDER BY date DESC")
            entries = query.fetch(1)
            if entries:
                end_date = entries[0].date

            end_year = 0
            if end_date:
                end_year = end_date.year

            self.template_vals.update(
                {
                    "dates": self.build_dates(start_date, end_date),
                    "end_year": end_year,
                    "menu_pages": m_pages,
                    "tags": Tag.all().order("tag"),
                    "blogroll": blogroll,
                    "recent_comments": Comment.all().order("-date").fetch(5),
                }
            )
            logging.info("base public page initialized")
        except:
            logging.error(traceback.format_exc())
            return self.error(404)
示例#48
0
    def render_filtered_tbl(self,limit,offset,**kwargs):
        (answers, curpage, maxpages, startpage, pagecount) = \
                self.get_filtered(limit=limit, offset=offset)

        hasqid = ('questionID'in kwargs)
        course = g.lti.get_course_id()
        
        for a in answers:
            a.tags = ''
            tag_ids = AnswerTag.get_tag_ids(a.id)
            if tag_ids != []:           
                for id in tag_ids:
                    tag_name = Tag.get_tag(id)                     
                    a.tags += tag_name + ', ' 
                a.tags = a.tags[:-2]            

        return render_template('answer_filter_tbl.html',
                answers=answers,currentpage=curpage,
                maxpages=maxpages,startpage=startpage,pagecount=pagecount,
                hasQuestionID=hasqid,
                users=user.UserModel.get_all(),
                questions = [] if hasqid else Question.by_course_id(course))
示例#49
0
文件: issue.py 项目: leeccong/code
def delete_tag(request):
    # FIXME: ugly
    if request.method == "POST":
        user = request.user
        if not user:
            return {'r': 0, 'msg': '未登录,请先登录'}
        tag_name = request.get_form_var('tag_name', '').decode('utf-8')
        tag_type = request.get_form_var('tag_type', '')
        tag_target_id = request.get_form_var('tag_target_id', '')

        if not tag_name:
            return {'r': 0, 'msg': 'tag不能为空'}
        try:
            tag_type, tag_target_id = int(tag_type), int(tag_target_id)
        except:
            return {'r': 0, 'msg': '错误的数据类型'}

        if tag_type == TAG_TYPE_PROJECT_ISSUE:
            target = CodeDoubanProject.get(tag_target_id)
        elif tag_type == TAG_TYPE_TEAM_ISSUE:
            target = Team.get(tag_target_id)
        else:
            return {'r': 0, 'msg': '错误的数据类型'}

        if not target.is_admin(user.name):
            return {'r': 0, 'msg': '没有操作权限'}

        tname = TagName.get_by_name_and_target_id(tag_name, tag_type, target.id)
        if not tname:
            return {'r': 0, 'msg': 'tag不存在'}

        tags = Tag.gets_by_tag_id(tname.id)
        for tag in tags:
            tag.delete()
        tname.delete()
        return {'r': 1, 'msg': '删除成功'}
示例#50
0
 def addtag(self, request):
     Tag.add_tag(request.form['newTag'])
示例#51
0
 def render(self):
     enabledtags = AnswerTag.get_tag_ids(self.answer_id)
     return render_template('assigntag.html', answer=self.answer,
                            tags=Tag.get_all(), enabledtags=enabledtags)
示例#52
0
 def json_get_tags(q):    
    tags = Tag.get_searched_tags(q)
    data = []
    for tag in tags:
        data.append( {"id":str(tag.id), "name":tag.name} )
    return json.dumps(data)
示例#53
0
 def render(self):
     self.taglist = Tag.get_all()
     return render_template('modifytags.html',tags=self.taglist)        
示例#54
0
 def delete_tag_question(self, id):
     if g.lti.is_instructor():
         Tag.remove_tag(id)
     return json.dumps({'deleted': g.lti.is_instructor()})
示例#55
0
 def deletetag(self, request):
     for tid in request.form.getlist('tags'):
         Tag.remove_tag(tid)
示例#56
0
 def addtag(self, request):
     Tag.add_tag(request.form["newTag"])