sqlalchemy.func.max

Here are the examples of the python api sqlalchemy.func.max taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

130 Examples 7

3 Source : models.py
with Apache License 2.0
from abhioncbr

    def latest_execution_date(self):
        """
        Returns the latest date for which at least one dag run exists
        """
        session = settings.Session()
        execution_date = session.query(func.max(DagRun.execution_date)).filter(
            DagRun.dag_id == self.dag_id
        ).scalar()
        session.commit()
        session.close()
        return execution_date

    @property

3 Source : blocks.py
with Apache License 2.0
from analyseether

    def get_max_block_number(cls):
        current_session = get_current_session()
        with current_session.db_session_scope():

            max_block_number = current_session.db_session.query(
                               func.max(cls.block_number)).scalar()
        return max_block_number

    @classmethod

3 Source : nearby.py
with GNU Affero General Public License v3.0
from andrewcooke

    def __init__(self, s, activity_group, epsilon, minpts):
        super().__init__(epsilon, minpts)
        self.__s = s
        self.__activity_group = activity_group
        ajlo = aliased(ActivityJournal)
        ajhi = aliased(ActivityJournal)
        self.__max_similarity = self.__s.query(func.max(ActivitySimilarity.similarity)). \
            join(ajlo, ActivitySimilarity.activity_journal_lo_id == ajlo.id). \
            join(ajhi, ActivitySimilarity.activity_journal_hi_id == ajhi.id). \
            filter(ajlo.activity_group == activity_group,
                   ajhi.activity_group == activity_group).scalar()
        if not self.__max_similarity: raise Exception('All activities unconnected')

    def run(self):

3 Source : fact_notification_status_dao.py
with MIT License
from cds-snc

def get_last_send_for_api_key(api_key_id):
    """
    SELECT max(created_at) as last_notification_created
    FROM notifications
    WHERE api_key_id = 'api_key_id'
    GROUP BY api_key_id;
    """

    return (
        db.session.query(func.max(Notification.created_at).label("last_notification_created"))
        .filter(Notification.api_key_id == api_key_id)
        .group_by(Notification.api_key_id)
        .all()
    )


def get_api_key_ranked_by_notifications_created(n_days_back):

3 Source : grading.py
with MIT License
from dgomes

def get_game():
    page = request.args.get('page', 1, type=int)

    q = db.session.query(Game.id, Game.timestamp, Game.player, func.max(Game.score).label('score')).group_by(Game.player).order_by(Game.score.desc(), Game.timestamp.desc())
#    print(q.statement)

    all_games = q.paginate(page, 20, False)
    result = games_schema.dump(all_games.items)
    return jsonify(result)


# endpoint to show player games
@app.route("/highscores/  <  player>", methods=["GET"])

3 Source : grading.py
with MIT License
from dgomes

def get_game():
    page = request.args.get('page', 1, type=int)

    q = db.session.query(Game.id, Game.timestamp, Game.player, Game.level, func.max(Game.score).label('score'), Game.total_steps).group_by(Game.player).order_by(Game.score.desc(), Game.timestamp.desc())
#    print(q.statement)

    all_games = q.paginate(page, 20, False)
    result = games_schema.dump(all_games.items)
    return jsonify(result)


# endpoint to show player games
@app.route("/highscores/  <  player>", methods=["GET"])

3 Source : db_funcs.py
with Apache License 2.0
from Disk1n

def get_latest_version(session):
    return session.query(func.max(Transaction.version)).scalar()


#############
# DB Worker #
#############

class TxDBWorker(Thread):

3 Source : Library.py
with MIT License
from elbakramer

    def get_latest_versions(self, deleted=False):
        session = object_session(self)

        symbols = session.query(Symbol).with_parent(self)

        versions = session.query(Version, func.max(Version.version)).group_by(
            Version.symbol_id
        )
        version = aliased(Version, alias=versions.subquery())
        versions = session.query(version)

        if not deleted:
            versions = versions.filter(version.deleted != True)

        versions = versions.join(symbols.subquery())
        versions = versions.all()
        return versions

    def get_snapshot(self, snapshot):

3 Source : training.py
with MIT License
from ericdaat

def retrieve_best_model_params():
    session = Session()

    result = session.query(Model, func.max(Epoch.eval_F1))\
                    .join(Epoch)\
                    .group_by(Model.id)\
                    .order_by(Epoch.eval_F1.desc())\
                    .first()

    return dict(
        model_name=result[0].model_name,
        model_params=result[0].model_params,
        optimizer_name=result[0].optimizer_name,
        optimizer_params=result[0].optimizer_params,
        best_eval_f1_score=result[-1]
    )


def hash_parameters(params):

3 Source : dagrun.py
with Apache License 2.0
from flink-extended

    def get_latest_runs(cls, session=None):
        """Returns the latest DagRun for each DAG"""
        subquery = (
            session.query(cls.dag_id, func.max(cls.execution_date).label('execution_date'))
            .group_by(cls.dag_id)
            .subquery()
        )
        dagruns = (
            session.query(cls)
            .join(
                subquery,
                and_(cls.dag_id == subquery.c.dag_id, cls.execution_date == subquery.c.execution_date),
            )
            .all()
        )
        return dagruns

    @provide_session

3 Source : taskinstance.py
with Apache License 2.0
from flink-extended

    def _get_latest_seq_num(self, session=None):
        """
        Get latest seq num of task execution
        """
        return session.query(func.max(TaskExecution.seq_num)).filter_by(
            dag_id=self.dag_id,
            task_id=self.task_id,
            execution_date=self.execution_date,
        ).scalar()

    @provide_session

3 Source : sql.py
with MIT License
from gatheringhallstudios

def calculate_next_recipe_id(session):
    current_max = session.query(func.max(db.RecipeItem.recipe_id)).scalar() 
    if not current_max:
        return 1
    return current_max + 1

def build_sql_database(output_filename, mhdata):

3 Source : versioned_rows_w_versionid.py
with Apache License 2.0
from gethue

    def __declare_last__(cls):
        alias = cls.__table__.alias()
        cls.calc_is_current_version = column_property(
            select([func.max(alias.c.version_id) == cls.version_id]).where(
                alias.c.id == cls.id
            )
        )

    def new_version(self, session):

3 Source : test_query.py
with Apache License 2.0
from gethue

    def test_clauses(self):
        User, Address = self.classes.User, self.classes.Address

        for (expr, compare) in (
            (func.max(User.id), "max(users.id)"),
            (User.id.desc(), "users.id DESC"),
            (
                between(5, User.id, Address.id),
                ":param_1 BETWEEN users.id AND addresses.id",
            ),
            # this one would require adding compile() to
            # InstrumentedScalarAttribute.  do we want this ?
            # (User.id, "users.id")
        ):
            c = expr.compile(dialect=default.DefaultDialect())
            assert str(c) == compare, "%s != %s" % (str(c), compare)


class ExpressionTest(QueryTest, AssertsCompiledSQL):

3 Source : test_query.py
with Apache License 2.0
from gethue

    def test_aggregate_fn(self):
        User = self.classes.User
        session = Session()
        with self._assert_bind_args(session):
            session.query(func.max(User.name)).all()

    def test_bulk_update_no_sync(self):

3 Source : test_query.py
with Apache License 2.0
from gethue

    def _test_expr(self, fixture):
        User, Address = self.classes("User", "Address")

        s = Session(query_cls=fixture())

        q = s.query(func.max(User.id).label("max"))
        eq_(q.scalar(), 10)

    def _test_expr_undocumented_query_constructor(self, fixture):

3 Source : test_query.py
with Apache License 2.0
from gethue

    def _test_expr_undocumented_query_constructor(self, fixture):
        # see #4269.  not documented but already out there.
        User, Address = self.classes("User", "Address")

        s = Session(query_cls=fixture())

        q = Query(func.max(User.id).label("max")).with_session(s)
        eq_(q.scalar(), 10)

    def test_plain_get(self):

3 Source : test_functions.py
with Apache License 2.0
from gethue

    def test_funcfilter_fromobj_fromfunc(self):
        # test from_obj generation.
        # from func:
        self.assert_compile(
            select(
                [
                    func.max(table1.c.name).filter(
                        literal_column("description") != None  # noqa
                    )
                ]
            ),
            "SELECT max(mytable.name) FILTER (WHERE description "
            "IS NOT NULL) AS anon_1 FROM mytable",
        )

    def test_funcfilter_fromobj_fromcriterion(self):

3 Source : test_selectable.py
with Apache License 2.0
from gethue

    def test_labeled_select_correspoinding(self):
        l1 = select([func.max(table1.c.col1)]).label("foo")

        s = select([l1])
        eq_(s.corresponding_column(l1), s.c.foo)

        s = select([table1.c.col1, l1])
        eq_(s.corresponding_column(l1), s.c.foo)

    def test_select_alias_labels(self):

3 Source : vulnerability.py
with Apache License 2.0
from google

    def next_version_number(self):
        prev_version = (
            Vulnerability.query.filter_by(vcdb_id=self.vcdb_id)
            .with_entities(func.max(Vulnerability.version))
            .first()[0]
        )
        if not prev_version:
            prev_version = 0
        return prev_version + 1

    @staticmethod

3 Source : blocks.py
with Apache License 2.0
from grin-pool

    def get_latest(cls, n=None):
        highest = database.db.getSession().query(func.max(Blocks.height)).scalar()
        if n == None:
            return database.db.getSession().query(Blocks).filter(Blocks.height == highest).first()
        else:
            return list(database.db.getSession().query(Blocks).filter(Blocks.height >= highest-n).order_by(asc(Blocks.height)))

    # Get record(s) by height and range
    @classmethod

3 Source : grin_stats.py
with Apache License 2.0
from grin-pool

    def get_latest(cls, range=None):
        highest = database.db.getSession().query(func.max(Grin_stats.height)).scalar()
        if range == None:
            return database.db.getSession().query(Grin_stats).filter(Grin_stats.height == highest).first()
        else:
            h_start = highest-(range-1)
            return list(database.db.getSession().query(Grin_stats).filter(Grin_stats.height >= h_start).order_by(asc(Grin_stats.height)))


    # Get record(s) by height and optional historical range
    @classmethod

3 Source : pool_blocks.py
with Apache License 2.0
from grin-pool

    def get_latest(cls, n=None, id=None):
        highest = database.db.getSession().query(func.max(Pool_blocks.height)).scalar()
        if n is None:
            if id is None:
                return database.db.getSession().query(Pool_blocks).filter(Pool_blocks.height == highest).first()
            else:
                return database.db.getSession().query(Pool_blocks).filter(and_(Pool_blocks.height == highest, Pool_blocks.found_by == id)).first()
        else:
            if id is None:
                return list(database.db.getSession().query(Pool_blocks).order_by(desc(Pool_blocks.height)).limit(n))
            else:
                return list(database.db.getSession().query(Pool_blocks).filter(Pool_blocks.found_by == id).order_by(desc(Pool_blocks.height)).limit(n))

    # Get record(s) by height
    @classmethod

3 Source : pool_blocks.py
with Apache License 2.0
from grin-pool

    def get_by_height(cls, height, range=None, id=None):
        if height == 0:
            height = database.db.getSession().query(func.max(Pool_blocks.height)).scalar()
        if range == None:
            if id is None:
                return database.db.getSession().query(Pool_blocks).filter(Pool_blocks.height == height).first()
            else:
                return database.db.getSession().query(Pool_blocks).filter(and_(Pool_blocks.height == height, Pool_blocks.found_by == id)).first()
        else:
            if id is None:
                return list(database.db.getSession().query(Pool_blocks).filter(Pool_blocks.height   <  = height).order_by(desc(Pool_blocks.height)).limit(range))
            else:
                return list(database.db.getSession().query(Pool_blocks).filter(and_(Pool_blocks.height  < = height, Pool_blocks.found_by == id)).order_by(desc(Pool_blocks.height)).limit(range))

    # Get records falling within requested time range
    @classmethod

3 Source : pool_stats.py
with Apache License 2.0
from grin-pool

    def get_latest(cls, n=None):
        highest = database.db.getSession().query(func.max(Pool_stats.height)).scalar()
        if n == None:
            return database.db.getSession().query(Pool_stats).filter(Pool_stats.height == highest).first()
        else:
            return list(database.db.getSession().query(Pool_stats).filter(Pool_stats.height >= highest-n).order_by(asc(Pool_stats.height)))

    # Get record(s) by height
    @classmethod

3 Source : pool_stats.py
with Apache License 2.0
from grin-pool

    def get_by_height(cls, height, range=None):
        if height == 0:
            height = database.db.getSession().query(func.max(Pool_stats.height)).scalar()
        if range == None:
            return database.db.getSession().query(Pool_stats).filter(Pool_stats.height == height).first()
        else:
            h_start = height-(range-1)
            h_end = height
            return list(database.db.getSession().query(Pool_stats).filter(and_(Pool_stats.height >= h_start, Pool_stats.height   <  = h_end)).order_by(asc(Pool_stats.height)))

    # Get stats by timestamp
    @classmethod

3 Source : worker_shares.py
with Apache License 2.0
from grin-pool

    def get_latest_height(cls, id=None):
        if id is None:
            return database.db.getSession().query(func.max(Worker_shares.height)).scalar()
        else:
            return database.db.getSession().query(Worker_shares.height).\
                                            filter(Worker_shares.user_id == id).\
                                            order_by(Worker_shares.height.desc()).\
                                            first()[0]

    # Get list of all worker share records by height and optionally range
    @classmethod

3 Source : worker_stats.py
with Apache License 2.0
from grin-pool

    def get_latest(cls):
        last_height = database.db.getSession().query(func.max(Worker_stats.height)).scalar()
        if last_height is None:
            return None
        return database.db.getSession().query(Worker_stats).filter(Worker_stats.height == last_height).first()

    # Get the most recent stats record for specified worker
    @classmethod

3 Source : preassembly.py
with GNU General Public License v3.0
from indralab

def list_latest_raw_stmts(db):
    """Return a dict of the most recent new raw statement for each type."""
    from sqlalchemy import func
    res = (db.session.query(db.RawStatements.type,
                            func.max(db.RawStatements.create_date))
                     .group_by(db.RawStatements.type)
                     .all())
    return {k: v for k, v in res}


def run_preassembly(mode, project_name):

3 Source : reading.py
with GNU General Public License v3.0
from indralab

    def get_latest_updates(db):
        """Get the date of the latest update."""
        res = (db.session.query(db.ReadingUpdates.reader,
                                func.max(db.ReadingUpdates.latest_datetime))
               .group_by(db.ReadingUpdates.reader))
        return {reader: last_updated for reader, last_updated in res}

    @classmethod

3 Source : computer.py
with Apache License 2.0
from lightforever

    def all_with_last_activtiy(self):
        query = self.query(Computer, func.max(Docker.last_activity)). \
            join(Docker, Docker.computer == Computer.name). \
            group_by(Computer.name)
        res = []
        for c, a in query.all():
            c.last_activity = a
            res.append(c)
        return res

    def gpu_available(self):

3 Source : project.py
with Apache License 2.0
from lightforever

    def all_last_activity(self):
        query = self.query(Project,
                           func.max(Task.last_activity)). \
            join(Dag, Dag.project == Project.id, isouter=True). \
            join(Task, isouter=True). \
            group_by(Project.id)

        res = query.all()
        for p, last_activity in res:
            p.last_activity = last_activity
        return [r[0] for r in res]

    def by_name(self, name: str):

3 Source : headers_repository.py
with MIT License
from mempoolco

    def get_best_blockhash(self) -> str:
        session = self.session()
        _id = session.query(func.max(database.Header.id)).one_or_none()
        best_header = _id and session.query(database.Header).filter_by(id=_id[0]).one_or_none()
        best_blockhash = best_header and best_header.blockhash
        return best_blockhash and binascii.hexlify(best_blockhash).decode()

    def get_best_header(self):

3 Source : vote.py
with MIT License
from OneGov

    def last_ballot_change(cls):
        expr = select([func.max(Ballot.last_change)])
        expr = expr.where(Ballot.vote_id == cls.id)
        expr = expr.label('last_ballot_change')
        return expr

    @hybrid_property

3 Source : scan_jobs.py
with MIT License
from OneGov

    def next_delivery_number(self, municipality_id):
        """ Returns the next delivery number for the given municipality. """
        query = self.session.query(func.max(ScanJob.delivery_number))
        query = query.filter_by(municipality_id=municipality_id)
        return (query.scalar() or 0) + 1

    def add(self, **kwargs):

3 Source : historical_crypto_fiat_rate.py
with MIT License
from singnet

    def get_max_rates(self, crypto_symbol, fiat_symbol, limit, multiplier):
        try:
            result = self.session.query(func.max(Rate.crypto_rate).label("max")).filter(
                and_(Rate.crypto_symbol == crypto_symbol, Rate.fiat_symbol == fiat_symbol)).order_by(
                Rate.id.desc()).limit(limit).first()

            self.session.commit()
            if result.max is not None:
                return result.max * Decimal(multiplier)
            else:
                return None
        except Exception as e:
            self.session.rollback()
            raise e

3 Source : season_scraper.py
with MIT License
from Spencer-Weston

def add_rows(session, schedule, rows):
    """Add rows into the schedule if they contain games past the most recent game in schedule.

    Args:
        session: An instantiated sqlalchemy session
        schedule: A mapped schedule table
        rows: rows compatible with schedule
    """
    most_recent_game = session.query(func.max(schedule.start_time)).one()[0]  # The most recent game in the database
    most_recent_game = most_recent_game.replace(tzinfo=rows[0]["start_time"].tzinfo)  # Unify timezones
    new_rows = [row for row in rows if row["start_time"] > most_recent_game]
    new_row_objects = []
    for row in new_rows:
        new_row_objects.append(schedule(**row))
    session.add_all(new_row_objects)


def scrape():

3 Source : versioned_rows_w_versionid.py
with MIT License
from sqlalchemy

    def __declare_last__(cls):
        alias = cls.__table__.alias()
        cls.calc_is_current_version = column_property(
            select(func.max(alias.c.version_id) == cls.version_id).where(
                alias.c.id == cls.id
            )
        )

    def new_version(self, session):

3 Source : test_functions.py
with MIT License
from sqlalchemy

    def test_funcfilter_fromobj_fromfunc(self):
        # test from_obj generation.
        # from func:
        self.assert_compile(
            select(
                func.max(table1.c.name).filter(
                    literal_column("description") != None  # noqa
                )
            ),
            "SELECT max(mytable.name) FILTER (WHERE description "
            "IS NOT NULL) AS anon_1 FROM mytable",
        )

    def test_funcfilter_fromobj_fromcriterion(self):

3 Source : test_selectable.py
with MIT License
from sqlalchemy

    def test_labeled_select_corresponding(self):
        l1 = select(func.max(table1.c.col1)).label("foo")

        s = select(l1)
        eq_(s.corresponding_column(l1), s.selected_columns.foo)

        s = select(table1.c.col1, l1)
        eq_(s.corresponding_column(l1), s.selected_columns.foo)

    def test_labeled_subquery_corresponding(self):

3 Source : test_selectable.py
with MIT License
from sqlalchemy

    def test_labeled_subquery_corresponding(self):
        l1 = select(func.max(table1.c.col1)).label("foo")
        s = select(l1).subquery()

        eq_(s.corresponding_column(l1), s.c.foo)

        s = select(table1.c.col1, l1).subquery()
        eq_(s.corresponding_column(l1), s.c.foo)

    def test_select_alias_labels(self):

0 Source : views.py
with Apache License 2.0
from abhioncbr

    def task_stats(self, session=None):
        TI = models.TaskInstance
        DagRun = models.DagRun
        Dag = models.DagModel

        LastDagRun = (
            session.query(DagRun.dag_id, sqla.func.max(DagRun.execution_date).label('execution_date'))
                .join(Dag, Dag.dag_id == DagRun.dag_id)
                .filter(DagRun.state != State.RUNNING)
                .filter(Dag.is_active == True)
                .filter(Dag.is_subdag == False)
                .group_by(DagRun.dag_id)
                .subquery('last_dag_run')
        )
        RunningDagRun = (
            session.query(DagRun.dag_id, DagRun.execution_date)
                .join(Dag, Dag.dag_id == DagRun.dag_id)
                .filter(DagRun.state == State.RUNNING)
                .filter(Dag.is_active == True)
                .filter(Dag.is_subdag == False)
                .subquery('running_dag_run')
        )

        # Select all task_instances from active dag_runs.
        # If no dag_run is active, return task instances from most recent dag_run.
        LastTI = (
            session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
                .join(LastDagRun, and_(
                LastDagRun.c.dag_id == TI.dag_id,
                LastDagRun.c.execution_date == TI.execution_date))
        )
        RunningTI = (
            session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
                .join(RunningDagRun, and_(
                RunningDagRun.c.dag_id == TI.dag_id,
                RunningDagRun.c.execution_date == TI.execution_date))
        )

        UnionTI = union_all(LastTI, RunningTI).alias('union_ti')
        qry = (
            session.query(UnionTI.c.dag_id, UnionTI.c.state, sqla.func.count())
                .group_by(UnionTI.c.dag_id, UnionTI.c.state)
        )

        data = {}
        for dag_id, state, count in qry:
            if dag_id not in data:
                data[dag_id] = {}
            data[dag_id][state] = count
        session.commit()

        payload = {}
        for dag in dagbag.dags.values():
            payload[dag.safe_dag_id] = []
            for state in State.task_states:
                try:
                    count = data[dag.dag_id][state]
                except:
                    count = 0
                d = {
                    'state': state,
                    'count': count,
                    'dag_id': dag.dag_id,
                    'color': State.color(state)
                }
                payload[dag.safe_dag_id].append(d)
        return wwwutils.json_response(payload)

    @expose('/code')

0 Source : views.py
with Apache License 2.0
from abhioncbr

    def task_stats(self):
        TI = models.TaskInstance
        DagRun = models.DagRun
        Dag = models.DagModel
        session = Session()

        LastDagRun = (
            session.query(DagRun.dag_id, sqla.func.max(DagRun.execution_date).label('execution_date'))
            .join(Dag, Dag.dag_id == DagRun.dag_id)
            .filter(DagRun.state != State.RUNNING)
            .filter(Dag.is_active == True)
            .group_by(DagRun.dag_id)
            .subquery('last_dag_run')
        )
        RunningDagRun = (
            session.query(DagRun.dag_id, DagRun.execution_date)
            .join(Dag, Dag.dag_id == DagRun.dag_id)
            .filter(DagRun.state == State.RUNNING)
            .filter(Dag.is_active == True)
            .subquery('running_dag_run')
        )

        # Select all task_instances from active dag_runs.
        # If no dag_run is active, return task instances from most recent dag_run.
        LastTI = (
            session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
            .join(LastDagRun, and_(
                LastDagRun.c.dag_id == TI.dag_id,
                LastDagRun.c.execution_date == TI.execution_date))
        )
        RunningTI = (
            session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
            .join(RunningDagRun, and_(
                RunningDagRun.c.dag_id == TI.dag_id,
                RunningDagRun.c.execution_date == TI.execution_date))
        )

        UnionTI = union_all(LastTI, RunningTI).alias('union_ti')
        qry = (
            session.query(UnionTI.c.dag_id, UnionTI.c.state, sqla.func.count())
            .group_by(UnionTI.c.dag_id, UnionTI.c.state)
        )

        data = {}
        for dag_id, state, count in qry:
            if dag_id not in data:
                data[dag_id] = {}
            data[dag_id][state] = count
        session.commit()
        session.close()

        payload = {}
        for dag in dagbag.dags.values():
            payload[dag.safe_dag_id] = []
            for state in State.task_states:
                try:
                    count = data[dag.dag_id][state]
                except:
                    count = 0
                d = {
                    'state': state,
                    'count': count,
                    'dag_id': dag.dag_id,
                    'color': State.color(state)
                }
                payload[dag.safe_dag_id].append(d)
        return wwwutils.json_response(payload)

    @expose('/code')

0 Source : models.py
with Apache License 2.0
from abhioncbr

    def get_latest_runs(cls, session):
        """Returns the latest DagRun for each DAG. """
        subquery = (
            session
            .query(
                cls.dag_id,
                func.max(cls.execution_date).label('execution_date'))
            .group_by(cls.dag_id)
            .subquery()
        )
        dagruns = (
            session
            .query(cls)
            .join(subquery,
                  and_(cls.dag_id == subquery.c.dag_id,
                       cls.execution_date == subquery.c.execution_date))
            .all()
        )
        return dagruns


class Pool(Base):

0 Source : views.py
with Apache License 2.0
from abhioncbr

    def task_stats(self):
        TI = models.TaskInstance
        DagRun = models.DagRun
        Dag = models.DagModel
        session = Session()

        LastDagRun = (
            session.query(DagRun.dag_id, sqla.func.max(DagRun.execution_date).label('execution_date'))
                .join(Dag, Dag.dag_id == DagRun.dag_id)
                .filter(DagRun.state != State.RUNNING)
                .filter(Dag.is_active == True)
                .group_by(DagRun.dag_id)
                .subquery('last_dag_run')
        )
        RunningDagRun = (
            session.query(DagRun.dag_id, DagRun.execution_date)
                .join(Dag, Dag.dag_id == DagRun.dag_id)
                .filter(DagRun.state == State.RUNNING)
                .filter(Dag.is_active == True)
                .subquery('running_dag_run')
        )

        # Select all task_instances from active dag_runs.
        # If no dag_run is active, return task instances from most recent dag_run.
        LastTI = (
            session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
                .join(LastDagRun, and_(
                LastDagRun.c.dag_id == TI.dag_id,
                LastDagRun.c.execution_date == TI.execution_date))
        )
        RunningTI = (
            session.query(TI.dag_id.label('dag_id'), TI.state.label('state'))
                .join(RunningDagRun, and_(
                RunningDagRun.c.dag_id == TI.dag_id,
                RunningDagRun.c.execution_date == TI.execution_date))
        )

        UnionTI = union_all(LastTI, RunningTI).alias('union_ti')
        qry = (
            session.query(UnionTI.c.dag_id, UnionTI.c.state, sqla.func.count())
                .group_by(UnionTI.c.dag_id, UnionTI.c.state)
        )

        data = {}
        for dag_id, state, count in qry:
            if dag_id not in data:
                data[dag_id] = {}
            data[dag_id][state] = count
        session.commit()
        session.close()

        payload = {}
        for dag in dagbag.dags.values():
            payload[dag.safe_dag_id] = []
            for state in State.task_states:
                try:
                    count = data[dag.dag_id][state]
                except:
                    count = 0
                d = {
                    'state': state,
                    'count': count,
                    'dag_id': dag.dag_id,
                    'color': State.color(state)
                }
                payload[dag.safe_dag_id].append(d)
        return wwwutils.json_response(payload)

    @expose('/code')

0 Source : cli_sql.py
with MIT License
from ADE-Scheduler

def load(input):
    """
    Loads the database from a dumpfile.
    Tested with PostgreSQL, MySQL & SQLite.
    """
    db = app.config["MANAGER"].database
    tables = [
        md.Role,
        md.User,
        md.Schedule,
        md.Link,
        md.Property,
        md.Usage,
        md.ApiUsage,
    ]

    with open(input, "rb") as f:
        with db.session.no_autoflush:
            while True:
                try:
                    row = pkl.load(f)
                    db.session.merge(row)
                except EOFError:
                    break

    if db.session.bind.dialect.name == "postgresql":
        # https://stackoverflow.com/questions/37970743/postgresql-unique-violation-7-error-duplicate-key-value-violates-unique-const/37972960#37972960
        for table in tables:
            val = db.session.query(func.max(table.id)).scalar()
            name = table.__tablename__
            if val:
                db.session.execute(
                    f"SELECT setval(pg_get_serial_sequence('{name}', 'id'), {val+1}, false) FROM {name};"
                )

    db.session.commit()
    click.echo(f'Successfully loaded data from file "{input}".')


@sql.command()

0 Source : api_v1.py
with MIT License
from agamgn

    def post(self):
        reqs={'code':200,'msg':'发表成功','data':{}}
        dict = request.form
        uid=session['uid']

        if dict['is_zhiding'] =='true':
            istop=1

        else:
            istop=0
        jzposts = JzkPost(
            uid=uid,
            title=dict['title'],
            content=dict['content'],
            wages=dict['wages'],
            benefits=dict['benefits'],
            need_num=dict['need_num'],
            start_time=dict['start_time'],
            end_time=dict['end_time'],
            addres=dict['addres'],
            other=dict['other'],
            is_top=istop,
            jianzhi_type=dict['jianzhi_type'],
            jianzhi_time_type=dict['jianzhi_time_type'],
            people=dict['people'],
            people_tel=dict['people_tel'],
        )
        db.session.add(jzposts)
        db.session.commit()
        id=db.session.query(func.max(JzkPost.id)).one()[0]
        rdb.set(id, '倒计时的时间', 10)
        try:
            redis_save_time(id).send(None)
        except StopIteration as e:
            print("我已经停止了")

        return jsonify(reqs)


class app_me(Resource):

0 Source : server.py
with MIT License
from alexmojaki

def file_view(session, path):
    path = fix_abs_path(path)

    # Get all calls and functions in this file
    filtered_calls = (session.query(*(Call.basic_columns + Function.basic_columns))
                      .join(Function)
                      .filter_by(file=path)
                      .subquery('filtered_calls'))

    # Get the latest call *time* for each function in the file
    latest_calls = session.query(
        filtered_calls.c.name,
        sqlalchemy.func.max(filtered_calls.c.start_time).label('maxtime')
    ).group_by(
        filtered_calls.c.name,
    ).subquery('latest_calls')

    # Get the latest call for each function
    query = session.query(filtered_calls).join(
        latest_calls,
        sqlalchemy.and_(
            filtered_calls.c.name == latest_calls.c.name,
            filtered_calls.c.start_time == latest_calls.c.maxtime,
        )
    ).order_by(filtered_calls.c.start_time.desc())
    funcs = group_by_attr(query, 'type')

    # Add any functions which were never called
    all_funcs = sorted(session.query(Function.name, Function.type)
                       .filter_by(file=path)
                       .distinct())
    func_names = {row.name for row in query}
    for func in all_funcs:
        if func.name not in func_names:
            funcs[func.type].append(func)

    return render_template('file.html',
                           funcs=funcs,
                           is_ipython=path == IPYTHON_FILE_PATH,
                           full_path=path,
                           short_path=basename(path))


@app.route('/file/  <  file:path>/__function__/ < func_name>')

0 Source : summary.py
with GNU Affero General Public License v3.0
from andrewcooke

    def _calculate_value(self, s, statistic_name, summary, order_asc, start_time, finish_time, interval, measures):

        t = _tables()
        sjx = inspect(STATISTIC_JOURNAL_CLASSES[statistic_name.statistic_journal_type]).local_table
        units = statistic_name.units
        activity_group_id = interval.activity_group.id if interval.activity_group else None

        if summary == S.MAX:
            result = func.max(sjx.c.value)
        elif summary == S.MIN:
            result = func.min(sjx.c.value)
        elif summary == S.SUM:
            result = func.sum(sjx.c.value)
        elif summary == S.CNT:
            result = func.count(sjx.c.value)
            units = None
        elif summary == S.AVG:
            result = func.avg(sjx.c.value)
        elif summary == S.MSR:
            self._calculate_measures(s, statistic_name, order_asc, start_time, finish_time, interval, measures)
            return None, None
        else:
            raise Exception('Bad summary: %s' % summary)

        stmt = select([result]). \
            select_from(sjx).select_from(t.sj).select_from(t.src). \
            where(and_(t.sj.c.id == sjx.c.id,
                       t.sj.c.statistic_name_id == statistic_name.id,
                       t.sj.c.time >= start_time,
                       t.sj.c.time   <   finish_time,
                       t.sj.c.source_id == t.src.c.id,
                       t.src.c.activity_group_id == activity_group_id))

        return next(s.connection().execute(stmt))[0], units

    def _describe(self, statistic_name, summary, interval):

0 Source : traffic_violations_aggregator.py
with GNU General Public License v3.0
from bdhowald

    def _perform_campaign_lookup(self,
                                 included_campaigns:
                                 list[Campaign]) -> list[
            Tuple[str, int, int]]:

        LOG.debug('Performing lookup for campaigns.')

        result: list[Tuple[str, int, int]] = []

        for campaign in included_campaigns:

            subquery = campaign.plate_lookups.session.query(
                PlateLookup.plate, PlateLookup.state, func.max(PlateLookup.created_at).label(
                    'most_recent_campaign_lookup'),).group_by(
                PlateLookup.plate, PlateLookup.state).filter(
                    and_(PlateLookup.campaigns.any(Campaign.id.in_([campaign.id])), PlateLookup.count_towards_frequency == True)).subquery('subquery')

            full_query = PlateLookup.query.join(subquery,
                                                (PlateLookup.plate == subquery.c.plate) &
                                                (PlateLookup.state == subquery.c.state) &
                                                (PlateLookup.created_at ==
                                                    subquery.c.most_recent_campaign_lookup)).order_by(subquery.c.most_recent_campaign_lookup.desc(), PlateLookup.created_at.desc())

            campaign_lookups = full_query.all()

            campaign_vehicles: int = len(campaign_lookups)
            campaign_tickets: int = sum(
                [lookup.num_tickets for lookup in campaign_lookups])

            result.append(
                (campaign.hashtag, campaign_vehicles, campaign_tickets))

        return result

    def _perform_plate_lookup(self,

See More Examples