当前位置: 首页>>代码示例>>Python>>正文


Python functions.max函数代码示例

本文整理汇总了Python中sqlalchemy.sql.functions.max函数的典型用法代码示例。如果您正苦于以下问题:Python max函数的具体用法?Python max怎么用?Python max使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了max函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle_save

    def handle_save(self):
        data, errors = self.extractData()
        journal_note = data.pop('note')
        now = datetime.now()

        if errors:
            self.flash(_(u'Es ist ein Fehler aufgetreten!'))
            return FAILURE
        number = data.get('number', 0)
        if number:
            session = get_session('ukhvoucher')
            try:
                from sqlalchemy.sql.functions import max
                oid = int(session.query(max(Voucher.oid)).one()[0]) + 1
            except:
                oid = 100000
            from ukhvoucher.models import Generation
            import json

            p = int(session.query(max(Generation.oid)).one()[0] or 0) + 1
            generation = Generation(
                oid=p,
                date=now.strftime('%Y-%m-%d'),
                type=data['kategorie'],
                data=json.dumps('Manuelle Erzeugung'),
                user=self.request.principal.id,
                uoid=oid
            )

            for idx in range(number):
                voucher = Voucher(
                    creation_date=datetime.now().strftime('%Y-%m-%d'),
                    status=CREATED,
                    cat = data['kategorie'],
                    user_id=self.context.oid,
                    generation_id=p,
                    oid=oid)
                oid += 1
                session.add(voucher)
            session.add(generation)

            # journalize
            entry = JournalEntry(
                date=datetime.now().strftime('%Y-%m-%d'),
                userid=self.request.principal.id,
                action=u"Berechtigungsscheine manuell erstellt",
                #action=u"Add:%s" % self.context.model.__label__,
                oid=str(self.context.oid),
                note=journal_note)
            session.add(entry)

            # redirect
            self.flash(_(u"%s Berechtigungsscheine erstellt" % number))
            self.redirect(self.application_url())
            return SUCCESS
        else:
            self.flash(_(u"The demand must be for at least 1 voucher."))
            self.redirect(self.url(self.context))
            return FAILURE
开发者ID:novareto,项目名称:ukhvoucher,代码行数:59,代码来源:forms.py

示例2: caprate

 def caprate(self, attacker=None):
     maxcap = PA.getfloat("roids", "maxcap")
     mincap = PA.getfloat("roids", "mincap")
     if not attacker or not self.value:
         return maxcap
     modifier = (float(self.value) / float(attacker.value)) ** 0.5
     return max(mincap, min(maxcap * modifier, maxcap))
开发者ID:munin,项目名称:merlin,代码行数:7,代码来源:maps.py

示例3: _nextOrdering

 def _nextOrdering(self, blogId):
     '''
     Provides the next ordering.
     '''
     max = self.session().query(fn.max(BlogPostMapped.Order)).filter(BlogPostMapped.Blog == blogId).scalar()
     if max: return max + 1
     return 1
开发者ID:robchrstr,项目名称:Superdesk,代码行数:7,代码来源:blog_post.py

示例4: get_list

    def get_list(cls, **kw):
        # SELECT client.clientid, job_bytes, max_job FROM client
        # LEFT JOIN (SELECT job.clientid, SUM(job.jobbytes) AS job_bytes FROM job
        # GROUP BY job.clientid) AS vsota ON vsota.clientid = client.clientid
        # LEFT JOIN (SELECT job.clientid, MAX(job.schedtime) AS max_job FROM job
        # GROUP BY job.clientid) AS last_job ON last_job.clientid = client.clientid;
        sum_stmt = Job.query\
            .with_entities(Job.clientid, func.sum(Job.jobbytes).label('job_sumvolbytes'))\
            .group_by(Job.clientid)\
            .subquery('stmt_sub')
        last_stmt = Job.query\
            .with_entities(Job.clientid, func.max(Job.starttime).label('job_maxschedtime')).filter(Job.jobstatus == 'T')\
            .group_by(Job.clientid)\
            .subquery('stmt_max')
        objects = cls.query.with_entities(Client, 'job_sumvolbytes', 'job_maxschedtime', func.count(Job.jobid).label('num_jobs'))\
            .outerjoin(Job, Client.clientid == Job.clientid)\
            .outerjoin(sum_stmt, sum_stmt.c.clientid == Client.clientid)\
            .outerjoin(last_stmt, last_stmt.c.clientid == Client.clientid)\
            .group_by(cls, 'job_sumvolbytes', 'job_maxschedtime')\
            .all()

        # ugly hack since sqlite returns strings for job_maxschedtime
        # TODO: report upstream to sqlalchemy
        if DBSession.bind.dialect.name == 'sqlite':
            def convert_datetime(l):
                if l.job_maxschedtime:
                    l.job_maxschedtime = datetime.datetime.strptime(l.job_maxschedtime, '%Y-%m-%d %H:%M:%S')
                return l
            objects = map(convert_datetime, objects)
        return objects
开发者ID:gypsymauro,项目名称:almir,代码行数:30,代码来源:models.py

示例5: testing_function_4

def testing_function_4(query_module):
    models_module = sqlalchemy_models
    query = query_module.get_query(max(models_module.Author.id))

    rows = query.all()
    result = map(extract_row, rows)
    return str(result)
开发者ID:badock,项目名称:rome,代码行数:7,代码来源:functions_compatibility.py

示例6: _nextCId

 def _nextCId(self):
     '''
     Provides the next change Id.
     '''
     max = self.session().query(fn.max(BlogPostMapped.CId)).scalar()
     if max: return max + 1
     return 1
开发者ID:robchrstr,项目名称:Superdesk,代码行数:7,代码来源:blog_post.py

示例7: find_score

def find_score(filename, id, userid):
    """
    the import here is done inside because else a cyclic import situation arrises but as this
    method runs inside another process so the time consumed doesnt matter
    :param filename:
    :param id:
    :return:
    """
    from manage import app

    with app.app_context():
        with open(filename) as file:
            length = len(file.read())
        question = Question.query.filter(Question.id == id).first()
        maxS = question.max_score
        print(length, maxS)
        score = ((maxS - length) / maxS) * 100
        if score < 1:
            score = 1
        submission = Submission(user_id=userid, question_id=id, \
                                result=True, result_score=score, result_message="Solved")

        db.session.add(submission)
        db.session.commit()
        db.create_all()
        all_submissions = db.session.query(functions.max(Submission.result_score)).filter(Submission.user_id==userid).group_by(
            Submission.question_id).all()
        user = User.query.filter(User.id == userid).first()
        user.total_score = sum((x[0] for x in all_submissions))
        db.session.commit()
        print("done")
开发者ID:gitter-badger,项目名称:FlaskWars,代码行数:31,代码来源:routes.py

示例8: impacted_hls

    def impacted_hls(self, *args):
        """
        Renvoie une requête portant sur les services de haut niveau impactés.

        @param args: Liste d'éléments à récupérer dans la requête.
        @type args: Une C{DeclarativeBase} ou une liste de C{Column}s.
        @return: Une C{Query} portant sur les éléments demandés.
        @rtype: C{sqlalchemy.orm.query.Query}
        """
        from vigilo.models.tables import HighLevelService, \
                                            ImpactedHLS, ImpactedPath

        if not args:
            args = [HighLevelService]

        imp_hls1 = aliased(ImpactedHLS)
        imp_hls2 = aliased(ImpactedHLS)

        subquery = DBSession.query(
            functions.max(imp_hls1.distance).label('distance'),
            imp_hls1.idpath
        ).join(
            (ImpactedPath, ImpactedPath.idpath == imp_hls1.idpath)
        ).filter(ImpactedPath.idsupitem == self.idsupitem
        ).group_by(imp_hls1.idpath).subquery()

        services_query = DBSession.query(*args).distinct(
        ).join(
            (imp_hls2, HighLevelService.idservice == imp_hls2.idhls),
            (subquery, subquery.c.idpath == imp_hls2.idpath),
        ).filter(imp_hls2.distance == subquery.c.distance)

        return services_query
开发者ID:vigilo,项目名称:models,代码行数:33,代码来源:supitem.py

示例9: clean_stale_tasks

def clean_stale_tasks():

    from maproulette.models import db, Task, Action
    from sqlalchemy.sql.functions import max
    from datetime import datetime, timedelta
    import pytz

    current_time = datetime.now(pytz.utc)
    stale_threshold = current_time - timedelta(hours=1)
    counter = 0

    for task in (
        db.session.query(Task)
        .filter(Task.currentaction.in_(["assigned", "editing"]))
        .join(Task.actions)
        .group_by(Task.id)
        .having(max(Action.timestamp) < stale_threshold)
        .all()
    ):
        task.append_action(Action("available"))
        db.session.add(task)
        print "setting task %s to available" % (task.identifier)
        counter += 1
    db.session.commit()
    print "done. %i tasks made available" % counter
开发者ID:EdwardHinkle,项目名称:maproulette,代码行数:25,代码来源:manage.py

示例10: query_ordered

 def query_ordered(cls):
     # order by most recent last_seen OR key transaction
     newest_date = functions.max(
         functions.coalesce(User.last_seen, 0),
         functions.coalesce(KeyTransaction.start, 0)
     )
     query = Key.query.outerjoin(Key.holder).outerjoin(Key.current_transaction)
     return query.order_by(db.desc(newest_date))
开发者ID:ktt-ol,项目名称:poisk,代码行数:8,代码来源:models.py

示例11: index

def index():
    if current_user.is_authenticated():
        all_questions = Question.query.all()
        all_submissions = db.session.query(Submission.question_id,functions.max(Submission.result_score),Submission.result_message,Submission.result).filter(Submission.user_id==current_user.id).group_by(
            Submission.question_id).all()
        return render_template("index.html", all_quest=all_questions,allsubmission =all_submissions)
    flash("you need to login to see the questions", category="warning")
    return redirect(url_for("auth.login"))
开发者ID:gitter-badger,项目名称:FlaskWars,代码行数:8,代码来源:routes.py

示例12: getInvoiceId

def getInvoiceId():
    from ukhvoucher.models import Invoice
    from sqlalchemy.sql.functions import max
    session = get_session('ukhvoucher')
    try:
        oid = int(session.query(max(Invoice.oid)).one()[0]) + 1
    except:
        oid = 100000
    return unicode(oid)
开发者ID:novareto,项目名称:ukhvoucher,代码行数:9,代码来源:interfaces.py

示例13: get_stale_assigned_tasks

def get_stale_assigned_tasks():
    """returns all assigned tasks that are stale"""

    # select t.id from tasks t, actions a where
    # a.task_id = t.id and t.currentaction = 'assigned'
    # group by t.id having now() - max(a.timestamp) < interval '1 day';
    return db.session.query(Task).filter_by(
        currentaction='assigned').join(Task.actions).group_by(
        Task.id).having(max(Action.timestamp) > stale_threshold).all()
开发者ID:Koblaid,项目名称:maproulette,代码行数:9,代码来源:unassign.py

示例14: _setup_next_sequence

 def _setup_next_sequence(cls, *args, **kwargs):
     """Compute the next available PK, based on the 'pk' database field."""
     session = cls.FACTORY_SESSION
     model = cls.FACTORY_FOR
     pk = getattr(model, model.__mapper__.primary_key[0].name)
     max_pk = session.query(max(pk)).one()[0]
     if isinstance(max_pk, int):
         return max_pk + 1 if max_pk else 1
     else:
         return 1
开发者ID:4ell,项目名称:factory_boy,代码行数:10,代码来源:alchemy.py

示例15: stats

 def stats(self):
     """
     select host, count(pk), min(created), max(created) from responses group by host;
     """
     q = select([
         responses.c.host.label('host'),
         functions.count(responses.c.pk).label('amount'),
         functions.min(responses.c.created),
         functions.max(responses.c.created),
     ]).group_by('host').order_by(desc('amount'))
     return self.db.execute(q).fetchall()
开发者ID:clld,项目名称:clldclient,代码行数:11,代码来源:cache.py


注:本文中的sqlalchemy.sql.functions.max函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。