示例#1
0
文件: result.py 项目: isuker/snippets
 def validate_link(self, field):
     results = Result.query.filter(
         Result.access == Result.PUBLIC).filter_by(link=field.data)
     if self.result:
         results = results.filter(db.not_(Result.id == self.result.id))
     if results.count():
         raise ValidationError, "This Test Link has been existed"
示例#2
0
文件: news.py 项目: viaict/viaduct
def list(page_nr=1):
    items = News.query.filter(News.publish_date <= date.today(),
                              db.or_(News.archive_date >= date.today(),
                                     News.archive_date == None),  # noqa
                              db.or_(current_user.has_paid,
                                     db.not_(News.needs_paid))) \
        .order_by(desc(News.publish_date))

    can_write = role_service.user_has_role(current_user, Roles.NEWS_WRITE)
    return render_template('news/list.htm',
                           items=items.paginate(page_nr, 10, False),
                           archive=False, can_write=can_write)
示例#3
0
def update_tags():
    """ Updates taxonomy tags from gbif backbone and deletes unused ones """
    print('Updating tags:')
    for scan in Scan.query.filter(Scan.gbif_id).all():
        tags = [db.session.merge(tag) for tag in pull_tags(scan.gbif_id)]
        scan.taxonomy = tags
        print(' - ', scan.scientific_name)

    print('Deleting tags:')
    for tax in Taxonomy.query.filter(db.not_(Taxonomy.scans.any())):
        print(' - ', tax.name)
        db.session.delete(tax)
    db.session.commit()
示例#4
0
文件: home.py 项目: viaict/viaduct
def home():
    data = ['activities',
            'contact']

    revisions = get_revisions(data)
    news = News.query.filter(News.publish_date <= date.today(),
                             db.or_(News.archive_date >= date.today(),
                                    News.archive_date == None),  # noqa
                             db.or_(current_user.has_paid,
                                    db.not_(News.needs_paid)))\
                     .order_by(desc(News.publish_date)).limit(8).all()

    return render_template('home/home.htm', revisions=revisions,
                           title='Homepage', news=news)
示例#5
0
文件: news.py 项目: viaict/viaduct
def rss(locale='en'):
    name = 'via nieuws' if locale == 'nl' else 'via news'
    feed = AtomFeed(name, feed_url=request.url, url=request.url_root)
    items = News.query.filter(News.publish_date <= date.today(),
                              db.or_(News.archive_date >= date.today(),
                                     News.archive_date == None),  # noqa
                              db.or_(db.not_(News.needs_paid))) \
        .order_by(News.publish_date.desc()).limit(20)

    for item in items:
        published = datetime.combine(item.publish_date, datetime.min.time())
        title, content = item.get_localized_title_content(locale)
        feed.add(title, content, id=item.id, content_type='markdown',
                 published=published, updated=published,
                 url=url_for('news.view', news_id=item.id),
                 author=item.user.name)

    return feed.get_response()
示例#6
0
def display_bookmarks():
    # check if logged in w/ google
    if not google_auth.is_logged_in():
        return (redirect(url_for("google_auth.login")))

    form = TeamSearchForm()

    user_info = google_auth.get_user_info()
    user = User.query.filter(User.user_id == user_info["id"]).first()

    all_bookmarks = Bookmark.query.filter(
        db.not_(Bookmark.user_id == user.id)).join(User).all()
    user_bookmarks = Bookmark.query.filter(
        Bookmark.user_id == user.id).join(User).all()

    return (render_template("bookmarks/display_bookmarks.html",
                            all_bookmarks=all_bookmarks,
                            user_bookmarks=user_bookmarks,
                            form=form))
示例#7
0
def nominate():
    if not can_nominate():
        return redirect(url_for('elections.main'))

    nominated_ids = [n.nominee.id for n in current_user.nominations.all()]

    nominees = Nominee.query\
        .filter(db.or_(Nominee.valid == True, Nominee.valid == None))\
        .filter(db.not_(Nominee.id.in_(nominated_ids)))\
        .order_by(Nominee.name).all()  # noqa

    return render_template('elections/nominate.htm',
                           title='Docent van het jaar IW/Nomineren',
                           nominations=current_user.nominations,
                           data={'nominees': nominees,
                                 'nominate_url': url_for('elections.'
                                                         'submit_nomination'),
                                 'remove_url': url_for('elections.'
                                                       'remove_nomination')})
示例#8
0
文件: case.py 项目: beachmg/raychen
 def validate_link(self, field):
     cases = Case.query.public().filter_by(link=field.data)
     if self.case:
         cases = cases.filter(db.not_(Case.id==self.case.id))
     if cases.count():
         raise ValidationError, u"这个链接已经有人提交了"
示例#9
0
文件: cycle.py 项目: crook/snippets
 def validate_link(self, field):
     cycles = Cycle.query.filter_by(link=field.data)
     if self.cycle:
         cycles = cycles.filter(db.not_(Cycle.id==self.cycle.id))
     if cycles.count():
         raise ValidationError, "This Test Link has been existed"
示例#10
0
文件: post.py 项目: yxm0513/7topdig
 def validate_link(self, field):
     posts = Post.query.public().filter_by(link=field.data)
     if self.post:
         posts = posts.filter(db.not_(Post.id == self.post.id))
     if posts.count():
         raise ValidationError, u"这个链接已经有人提交了"
示例#11
0
文件: post.py 项目: yxm0513/7topdig
 def validate_link(self, field):
     posts = Post.query.public().filter_by(link=field.data)
     if self.post:
         posts = posts.filter(db.not_(Post.id==self.post.id))
     if posts.count():
         raise ValidationError, u"这个链接已经有人提交了"
示例#12
0
def register():
    """Register new constituent account

    .. note::

        The email address will be added to :class:`~app.models.Email` and
        :attr:`~app.models.ContactEmail.cp` will be enabled.

    **Example request**:

    .. sourcecode:: http

        POST /api/1.0/auth/register HTTP/1.1
        Host: do.cert.europa.eu
        Accept: application/json

        {
          "organization_id": 317,
          "name": "BEREC ([email protected])",
          "email": "*****@*****.**"
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.0 201 CREATED
        Content-Type: application/json

        {
          "message": "User registered. An activation email was sent to ..."
        }

    :reqheader Accept: Content type(s) accepted by the client
    :resheader Content-Type: this depends on `Accept` header or request

    :>json integer organization_id: Organization unique ID
    :>json string name: Name of account
    :>json string email: E-mail address

    :status 201: Account created.
    """
    org = Organization.query.filter_by(id=request.json['organization_id']).\
        first_or_404()
    eml = ContactEmail.query.filter_by(
        email=request.json['email'],
        organization_id=request.json['organization_id']).first()
    if not eml:
        eml = ContactEmail.fromdict(request.json)
    eml.cp = True

    user = User.fromdict(request.json)
    user.password = _random_ascii()
    user.api_key = user.generate_api_key()
    if org.is_sla:
        roles = Role.query.filter(db.not_(Role.permissions == 0xff)).all()
        for role in roles:
            if ((role.permissions
                 & Permission.SLAACTIONS) == Permission.SLAACTIONS):
                user.role = role
                break
    db.session.add(user)
    db.session.add(eml)
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        raise e
    expiry = 72 * 3600
    activation_token = user.generate_reset_token(expiry)
    send_email('Your account details', [user.email],
               'auth/email/activate_account',
               user=user,
               webroot=current_app.config['CP_WEB_ROOT'],
               token=activation_token,
               expiry=expiry / 60)
    msg = 'User registered. An activation email was sent to {}'
    return ApiResponse({'message': msg.format(user.email)}, 201)
    def next_question(self):

        previously_seen_examples = set()
        for q in self.answered_questions():
            previously_seen_examples.add(q.example)
        previously_seen_examples = list(previously_seen_examples)

        # Choose in priority questions that might have been left unanswered by current_user
        now = datetime.datetime.utcnow()
        candidate = Question.query.filter(
            db.and_(Question.ongoing_since > now - LOCK_TIME,
                    Question.ongoing_user == current_user.id)).first()
        # candidate = None
        if candidate is None:

            # Only consider questions that are not being answered right now
            now = datetime.datetime.utcnow()
            candidates = Question.query.filter(
                db.or_(Question.ongoing_since < now - LOCK_TIME,
                       Question.ongoing_user == current_user.id))

            # Choose a question whose example was never seen by the user
            candidates = candidates.filter(
                db.not_(Question.example.in_(
                    previously_seen_examples)))  #.order_by(func.random())

            if FILL_QUESTIONS:
                # Simply choose the question that has most answers so far
                questions_to_fill = candidates.filter(
                    db.and_(Question.n_answers > 0,
                            Question.n_answers < MAX_ANSWERS))
                candidate = questions_to_fill.order_by(
                    Question.n_answers.desc()).first()
            else:
                # Among these, rank the examples by number of answers (there is probably a better way to do that in SQL...)
                questions_not_empty = candidates.filter(
                    Question.n_answers > 0).all()
                examples_not_empty = set()
                for q in questions_not_empty:
                    examples_not_empty.add(q.example)
                examples_not_empty = list(examples_not_empty)
                examples_n_answers = []
                for example in examples_not_empty:
                    sum_answers = Question.query.filter(
                        Question.example == example).with_entities(
                            func.sum(Question.n_answers)).scalar()
                    # Do not add examples that have been fully answered
                    if not sum_answers == MAX_ANSWERS * (N_MODELS *
                                                         (N_MODELS - 1) / 2):
                        examples_n_answers += [[example, sum_answers]]
                examples_n_answers = sorted(examples_n_answers,
                                            key=lambda x: x[1])
                # print examples_n_answers
                if len(examples_n_answers) == 0:
                    # If no answers at all, or if all examples have been fully rated, choose a new, random one
                    candidate = None
                else:
                    max_tries = 3
                    tries = 0
                    # Try several times, in case the random example chosen is being answered by someone else
                    while candidate is None and tries < max_tries:
                        # print 'TRIES', tries

                        # Choose one of the examples that has most answers (random, but biased towards more answers)
                        example_idx = int(
                            len(examples_n_answers) *
                            pow(random.random(), BIAS_MOST_ANSWERS))
                        # In case BIAS_MOST_ANSWERS==0:
                        if example_idx == len(examples_n_answers):
                            example_idx = len(examples_n_answers) - 1
                        chosen_example = examples_n_answers[example_idx][0]
                        # Choose a question for that example
                        candidates_example = Question.query.filter(
                            Question.example == chosen_example)
                        # print candidates_example.all()
                        # Among these, only consider questions that are not being answered
                        candidates_example = candidates_example.filter(
                            db.or_(Question.ongoing_since < now - LOCK_TIME,
                                   Question.ongoing_user == current_user.id))
                        # Among these, choose a question that was already answers, but still lacks some:
                        candidate = candidates_example.filter(
                            db.and_(
                                Question.n_answers > 0,
                                Question.n_answers < MAX_ANSWERS)).order_by(
                                    func.random()).first()
                        # print candidate
                        # If all questions are fully answered, choose a new question for this example
                        if candidate is None:
                            # print "New question for same example"
                            candidate = candidates_example.filter(
                                Question.n_answers < MAX_ANSWERS).order_by(
                                    func.random()).first()
                        tries += 1

            # If there was no suitable candidate choose a random one.
            # (e.g. no answers yet, or all questions have been fully answered,
            # or the only questions left have all been seen by current_user,
            # or the only candidates are all being answered by other people...)
            if candidate is None:
                # print("Picking new example")
                candidate = candidates.filter(
                    Question.n_answers < MAX_ANSWERS).order_by(
                        func.random()).first()
        # print candidate, candidate.n_answers
        return candidate.id
示例#14
0
文件: result.py 项目: beachmg/raychen
 def validate_link(self, field):
     results = Result.query.filter(Result.access == Result.PUBLIC).filter_by(link=field.data)
     if self.result:
         results = results.filter(db.not_(Result.id == self.result.id))
     if results.count():
         raise ValidationError, "This Test Link has been existed"
示例#15
0
def validate_path_uniqueness(form, field):
    field.data = field.data.strip('/')
    path = field.data
    if path and File.query.filter(
            db.not_(File.id == form.file_id), File.path == path).count() > 0:
        raise ValidationError(u'Такой путь уже занят.')
示例#16
0
 def validate_link(self, field):
     cycles = Cycle.query.filter_by(link=field.data)
     if self.cycle:
         cycles = cycles.filter(db.not_(Cycle.id == self.cycle.id))
     if cycles.count():
         raise ValidationError, "This Test Link has been existed"